Problems with JTABLEs

How can I make a non editable JTable? And...
How can I set the columns in my JTable to not be reorganizable?
I'd like someone to help me if posible.
Thanks.
Y si me lee alguien que sepa espa�ol, mi problema es:
En mi aplicaci�n uso una JTable dentro de un ScrollPane y luego visualizo la JTable que contiene unos datos que he leido de una base de datos. �Com� puedo hacer para impedir que las celdas de la tabla se puedan editar? Y... �C�mo impido que las columnas de la tabla se puedan reorganizar usando el rat�n?
Muchas gracias a todos.
Saludos.

Hi,
you should not be afraid of this column repositioning feature - the columns in your table model (your data) do not change this way - they stay on their postions, but you will have to use the getValueAt(...) method of the table model with your model indices, not that one of the JTable class, which uses column model indices.
Say, if you only want a JTable to be not editable and you have used the constructor
JTable jt = new JTable(myDataArray,myColumnNames);
to create it from an Object[][] and a String[] - you can simply use an inner class to achieve this:
DefaultTableModel m = new DefaultTableModel(myDataArray,myColumnNames) {
public boolean isCellEditable(int row,int column) { return false; }};
JTable jt = new JTable(m);
to retrieve cell data from this model use:
Object obj = m.getValueAt(row,column);
See the documentation of DefaultTableModel for more information
greetings Marsian

Similar Messages

  • Selection Problem with JTable

    Hello,
    i have a selection problem with JTable. I want to allow only single cell selection and additionally limit the selection to the first column.
    I preffered the style from MS Outlook Express where you can select the email accounts to edit.
    It is a table like this:
    Account name  |   Type  |   ...
    --------------|---------|---------------------
    Hotmail       |   POP3  |
    GMX           |   IMAP  |The selection should be only avaibable at 'Hotmail' or 'GMX' - not at 'POP3', 'IMAP' or as complete row selection.
    Please help me!
    Thanks.
    Warlock

    Maybe this will helpimport java.awt.*;
    import javax.swing.*;
    public class Test3 extends JFrame {
      public Test3() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        String[] head = {"One", "Two"};
        String[][] data = {{"R1-C1", "R1-C2"}, {"R2-C1", "R2-C2"}};
        JTable jt = new JTable(data, head);
        jt.getColumnModel().setSelectionModel(new MyTableSelectionModel());
        content.add(new JScrollPane(jt), BorderLayout.CENTER);
        jt.setCellSelectionEnabled(true);
        jt.setRowSelectionAllowed(false);
        jt.setColumnSelectionAllowed(false);
        setSize(300, 300);
        setVisible(true);
      public static void main(String[] arghs) { new Test3(); }
    class MyTableSelectionModel extends DefaultListSelectionModel {
      public void setSelectionInterval(int index0, int index1) {
        super.setSelectionInterval(0, 0);
    }

  • Another problem with JTable

    Hi,
    I have encountered a problem with JTable, i am trying to display some 15 columns and their values , one of the columns value is null, then the JTable is not displaying its value from this column(which is with null value) onwards.
    Can anybody assiss me in this matter.
    Regards
    khiz_eng

    I don't know If I can fix your problem, but
    I know just that it works on my PC.... It's very very
    slow... I don't know how to insert PageSetUp option... I have to study the problem.....
    However I don't think it's a hard problem....
    I want ask to you if you have found some problems when you are in Editing mode in a cell.....
    in the jdk1.2 version I could save while was in editing mode using the editingStopped method.
    It permit to update all data .... also the data in the cell I was editing.
    in the jdk 1.3 if I use this method It doesn't work properly... It maybe destroy the content object in the Cell..... because I'm able to print all the table except the editing cell (it throw an exception...)
    What's changed????
    I don't know...
    Can u help me?

  • A problem with JTable

    Hi !
    I have a problem with JTable - would like to use this component as a simple list of rows taken from a database : don't want to be able select or set a focus to a column - want only to be able select and set focus to a row ( just like in the menus). How to disable "focusability" for a cell with JTable ? Could You help me ?
    thnx in advance

    The Border is changed by the renderer, depending on whether the cell has focus or not. So you will need to create custom renderers without a Border. Something like:
    class NoBorderRenderer extends DefaultTableCellRenderer
         public Component getTableCellRendererComponent(
              JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
              super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
              setBorder(null);
              return this;
    }

  • Problem with JTable and JPanel

    Hi,
    I'm having problems with a JTable in a JPanel. The code is basicly as follows:
    public class mainFrame extends JFrame
            public mainFrame()
                    //A menu is implemeted giving rise to the following actions:
                    public void actionPerformed(ActionEvent evt)
                            String arg = evt.getActionCommand();
                            if(arg.equals("Sit1"))
                            //cells, columnNames are initiated correctly
                            JTable table = new JTable(cells,columnNames);
                            JPanel holdingPanel = new JPanel();
                            holdingPanel.setLayout( new BorderLayout() );
                            JScrollPane scrollPane = new JScrollPane(holdingPanel);
                            holdingPanel.setBackground(Color.white);
                            holdingPanel.add(table,BorderLayout.CENTER);
                            add(scrollPane, "Center");
                            if(arg.equals("Sit2"))
                                    if(scrollPane !=null)
                                            remove(scrollPane);validate();System.out.println("ScrollPane");
                                    if(holdingPanel !=null)
                                            remove(holdingPanel);
                                    if(table !=null)
                                            remove(table);table.setVisible(false);System.out.println("table");
                            //Put other things on the holdingPanel....
            private JScrollPane scrollPane;
            private JPanel holdingPanel;
            private JTable table;
    }The problem is that the table isn't removed. When you choose another situation ( say Sit2), at first the table apparently is gone, but when you press with the mouse in the area it appeared earlier, it appears again. How do I succesfully remove the table from the panel? Removing the panel doesn't seem to be enough. Help is much appreciated...
    Best regards
    Schwartz

    If you reuse the panel and scroll pane throughout the application,
    instantiate them in the constructor, not in an often-called event
    handler. In the event handler, you only do add/remove of the table
    on to the panel. You can't remove the table from the container
    which does not directly contain it.
    if (arg.equals("Sit2")){
      holdingPanel.remove(table);
      holdingPanel.revalidate();
      holdingPanel.repaint(); //sometimes necessary
    }

  • Scrollbar problem with JTable.

    Hi,
    I have 45 columns in a JTable. Please remember this is customize, we can change the number of columns dynamically, at max they can be 2 columns.
    i was having a problem with display the columns names in my Frame. I posted at http://forum.java.sun.com/thread.jspa?threadID=5167358&messageID=9641265#9641265
    I got the solution. Thanks for that.
    But as i said these columns are customized.
    when i am having 2 columns in my JTable, table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF ); is behaving differently, it's not occupying the complete JFrame. Lots of space is left out beside these 2 columns.
    When i comment this line, then those 2 columns are occupying my complete Frame.
    these two colmns should occupy my complete Frame and if i select 45 columns i should get scroll bar at botton with complete column NAMES.
    Hope i am clear.
    My Snippet
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.util.*;
    public class SimpleTable extends JPanel {
        private boolean DEBUG = false;
        public SimpleTable() {
            super(new BorderLayout());
                        String[][] values = new String[10][];
            String[] columnNames = {
                                                                                    "First Name","Last Name","Sport","# of Years","Vegetarian","First Name","Last Name","Sport","# of Years","Vegetarian","First Name","Last Name","Sport","# of Years","Vegetarian","First Name","Last Name","Sport","# of Years","Vegetarian","First Name","Last Name","Sport","# of Years","Vegetarian","First Name","Last Name","Sport","# of Years","Vegetarian","First Name","Last Name","Sport","# of Years","Vegetarian","First Name","Last Name","Sport","# of Years","Vegetarian","First Name","Last Name","Sport","# of Years","Vegetarian"
            Object[][] data = {
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Integer(10), new Boolean(false)},
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Integer(10), new Boolean(false)},
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Integer(10), new Boolean(false)},
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Integer(10), new Boolean(false)},
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Integer(10), new Boolean(false)},
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Integer(10), new Boolean(false)},
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Integer(10), new Boolean(false)},
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Integer(10), new Boolean(false)},
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Integer(10), new Boolean(false)}
                        DefaultTableModel defaulttablemodel = new DefaultTableModel(data,columnNames);
            final JTable table = new JTable(defaulttablemodel)
                 public boolean isCellEditable(int row,int column)
                                  return false;
                        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
                        //table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
                        JScrollPane scrollPane = new JScrollPane(table);
                        add(scrollPane);
        private static void createAndShowGUI() {
            JFrame frame = new JFrame("SimpleTable");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            SimpleTable newContentPane = new SimpleTable();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }

    Thank You camickr, it's serving my purpose.
    Just for a clarrification :
    table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
    table.setAutoscrolls(false);without using these lines also my purpose is serving.....then y do we need above two lines of code. r they necessary
    i mean, this snippet is sufficient.
    public boolean getScrollableTracksViewportWidth()
         return getPreferredSize().width < getParent().getWidth();
    }

  • Problems with JTable Renderer

    I have a problem with applying a custom renderer. I know the renderer works so thats not the problem. If I do like this:
    DefaultTableModel aDefaultTableModel = new DefaultTableModel(data, columnNames);
    it works. But if I do like this:
    DefaultTableModel aDefaultTableModel;
    aDefaultTableModel.setDataVector(data, columNames);
    is doesn't, why?

    I think maybe it's not the renderer at all. It may be my custom TableModel thats causing problems. Now this doesn't work:
    private JTable aTable;
    private CustomTableModel aTableModel;
    public MyProgram() {
    aTableModel = new CustomTableModel();
    aTable = new JTable(aTableModel);
    aTableModel.setData(data, columnNames);
    private class CustomTableModel {
    private String[] columnNames = null;
    private Object[][] data = null;
    public CustomTableModel() {
    columnNames = new String[0];
    data = new Object[0][0];
    ... snip
    public void setData(Object[][] data, String[] columnNames) {
    this.data = data;
    this.columnNames = columnNames;
    fireTableDataChanged();
    ... snip
    Now, why doesn't that setData method work??

  • Problems with JTable

    Hi All,
    I am facing some problems in JTable :
    1) How to remove all lines between cells, neither i should have column nor row lines....there should not be any lines between any cell at all.
    2) If i select a perticular cell, complete row is getting selected with a blue background, that should not happen at all.....row should not get select....
    3) How to make a cell non editable.
    Regards,
    Ravi

    1) Read the API. Check out the set??? methods until you fine what you want
    2) Read the API. Check out the methods that deal with row and column selection
    3) Override isCellEditable(...) method of JTable or DefaultTableModel

  • Problem with JTable in a JScrollPane

    Hello all,
    I have a problem using JTable, that the number of columns is very big,
    and the JScrollPane shows only vertical ScrollBar, isn't there any way to show a horizontal ScrollBar, to show the other columns without being bunched.
    Thanks in advance.

    table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );

  • Problem with JTable checkbox

    In my table I have a column of checkboxes. If user clicks any checkbox, the program will first check for some condition and pop out a warning dialog saying that "the action will change the current mode. are you sure you want to continue?". If user select "yes", some action are taken and the checkbox should be selected. Now the problem is that after user select "yes", the checkbox is not selected. (Same as when you press your mouse at a checkbox and then drag it out the checkbox cell, the actions are taken but the checkbox is not selected.)
    The code for the cell editor is as follows:
    public Component getTableCellEditorComponent(JTable table, Object value,
               boolean isSelected, int row, int column) {
             if (value instanceof ComboString) { // ComboString
               flg = COMBO;
               String str = (value == null) ? "" : value.toString();
               System.out.println("+++++++ " + row+" : "+column+"  flg: "+flg);
               return cellEditors[COMBO].getTableCellEditorComponent(table, str,
                   isSelected, row, column);
             else if (value instanceof Boolean) {                    
               flg = BOOLEAN;
               Boolean check = Boolean.getBoolean(value.toString());
                          // promptContinue returns true for continue, false for return; inside it a dialog box is popped for user selection "continue or not"
                          if(!promptContinue()){
                                return null;
               return cellEditors[BOOLEAN].getTableCellEditorComponent(table,
                   value, isSelected, row, column);
             

    Thanks. But my problem is not with stopping the editor, but with continuing the editor. Following is the code of getCellEditorValue()
    public Object getCellEditorValue() {
             switch (flg) {
             case COMBO:
               String str = (String) comboBox.getSelectedItem();
               return new ComboString(str);
             case BOOLEAN:
             case STRING:
               return cellEditors[flg].getCellEditorValue();
             default:
               return null;
                }I am not very sure whether it is the problem of cell editor or cell renderer, because it seems the code for continue condition is actually executed which is supposed to make the checkbox checked, but the result turns to be that the checkbox is not checked.

  • Urgent :problem with JTable on server program

    hi all i am writing an internet cafe timer.there is a table with the following colums:PC Name,IP Address,Status,Time Left, Time Login. ,on the server GUI. Whenever a client connects,a new row having the clients details is added to the table model, which reflects on the table.but if a client disconnects and reconnects, i want it to search thru the rows in the model, if there is a row with its information already,it shouls simply update the status column to "Reconnected", and not add an entirly new row, but if there is no row with its information, it can then add a new row with its information.
    Simply put, when a client connects,it should check
    1)if the table is empty, add a new row;
    2)else, check if tabe already has a row for the client, then update the row,else add a new row.
    its not working this way.it only works for the first client to connect,if other clients connect and disconnect,it still adds a new row, instaed of updating.
    the method doTable() in class ClientThread is what i use .please check it out and help me.
    i have a thread for each client.when a client connects, the server starts the thread and passes an instance of the server ui to the thread, so the threads acess the tablemodel thru this instance.
    Here is a simple run down of my classes
    CafeServer.java
    * @(#)CafeServer.java
    * @author obinna
    * @version 1.00 2007/3/10
    import java.net.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import java.sql.*;
    public class CafeServer {
         int serverPort;
         int serverLimit;
         //ServerSocket serversocket;
         private static int rownum = -1;
         private static Connection conn;
         private static CafeServerUI serverUI;
    * Creates a new instance of <code>CafeServer</code>.
    public CafeServer() {
         try{
              Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
              conn = DriverManager.getConnection("jdbc:odbc:cafetimer","","");
              System.out.println("connection established with cafetimer database");
         }catch(Exception ex){
              JOptionPane.showMessageDialog(null,"Cannot find database");
              serverUI = new CafeServerUI( this,conn );
    public void closeServer(){
         System.exit(0);
    public static void main(String[] args) throws IOException{
    // TODO code application logic here
    try{
         UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
         new CafeServer();
    catch(Exception ex){
         JOptionPane.showMessageDialog(null,"Could Not Find System Look and Feel.\nDefault L&F Loaded.");
         JFrame.setDefaultLookAndFeelDecorated(true);
    ServerSocket serverSocket = null;
    boolean listening = true;
    try {
    serverSocket = new ServerSocket(4444);
    } catch (IOException e) {
    System.err.println("Could not listen on port: 4444.");
    System.exit(-1);
    while (listening)
         new ClientThread(serverSocket.accept(),serverUI,conn).start();
    serverSocket.close();
    CafeServerUI.java
    //import statements.......................................
    public class CafeServerUI extends JFrame{
         public Vector pins = new Vector<String>();
         public DefaultTableModel model;
         public JTable table;
         protected JTextArea msgarea;
         protected JScrollPane scrpane;
         protected JPanel mainp,northp,leftp,rightupp,rightp;
         protected String[] colnames = {"Computer Name","IP Ad
    .............................................................constrctor follows
    ClientThread.java
    import java.io.*;
    import java.net.*;
    import java.sql.*;
    public class ClientThread extends Thread{
         private Socket socket = null;
         private String pin, timeleft, pin3,timeleft3,tleft;
         private CafeServerUI csui = null;
         private Ticket ticket;
         private RemainingTime remtime;
         private String hostname,ipadd;
         private int rownum;
         private Connection conn;
         private Statement stmt;
         private ResultSet rs;
         private boolean found;
         public ObjectOutputStream outputStream;
         public ObjectInputStream inputStream;
         private Admin admin;
         boolean found2 = false;
         //private String[] newrow = new String[5];
    public ClientThread(Socket socket,CafeServerUI csui,Connection conn) {
              super("Client Thread");
              this.socket = socket;
              this.csui = csui;
              this.conn = conn;
              try{
                   stmt = this.conn.createStatement();
              }catch(Exception ex){
                   System.out.println(ex.getMessage() + " : " + ex);
              //this.rownum = rownum;
              hostname = this.socket.getInetAddress().getHostName();
              ipadd = this.socket.getInetAddress().getHostAddress();
              //sString[] newrow = {hostname,ipadd,"Connected","",""};
              doTable();
              //System.out.print("table row " + this.rownum);
              this.csui.oos.addElement(ClientThread.this);
    public void doTable(){
         String[] newrow = {hostname,ipadd,"Connected","",""};
         if(this.csui.model.getRowCount() == 0){
                   this.csui.model.addRow(newrow);
              }else{
                   for(int i=0; i < this.csui.model.getRowCount(); i++ ){
                        String hname = (String)this.csui.model.getValueAt(i,0);
                        if(hname.equalsIgnoreCase(hostname)){
                             this.csui.model.setValueAt("Re Connected",i,2);
                             break;
                        }else{
                             this.csui.model.addRow(newrow);
                             break;
    .....public void run()....

    In the UI is defined the InputMap/ActionMap pair to respond to keys. There is defined an action for ENTER. I have had the same problem, and the only thing that worked for me was to clear the actionMap, and reassign some keys to their original action, and some (e.g. ENTER, TAB) to my actions. This worked. With TAB is harder beacuse i guess it's deeper in the JVM implemented, but after a while i've managed to overwrite that too.

  • Essential problem with JTable Selections?

    As far as I noticed a JTable actually consists of multiple Lists.
    For example; If I want to navigate horizontal and vertical (diagnal) from one cell to another I have to use two ListSelectionListeners.
    One ListSelectionListener to determine row-selection changes and the second ListSelectionListener to determine column-selection changes.
    table.getSelectionModel().addListSelectionListener(listener);
    table.getColumnModel().getSelectionModel().addListSelectionListener(listener);Due to this way the valueChanged(ListSelectionEvent e) method defined by the ListSelectionListener interface is called two times when navigating in two directions and called once when navigating in one dimension.
    Can this problem easily be solved or is this an idea for improvement?
    P.S. I don't need the solving of this issue to help me progress with my current dev. It's just something that cracks my mind at four o'clock in the night.

    You're completly right. I did not formulate the question good enough (ahh well.. my first post). What I meant was the detection of selection events, by a mouse click for example.
    The JTable.changeSelection(row, column, toggle, extend) is used to programmatically change the selection itself. In matter of fact, I believe the mouse and/or keyboard actions even use this method to peform their tasks when clicking on a cell.
    In my case, the row and column index of the cell being clicked have to be passed when a user clicks it in the Jtable.
    I've made a JFrame program that shows an image when a cell is clicked. When the cell that is being clicked is in the same row or in the the same column as the previous selected cell, the picture is loaded once. When the newly clicked cell is in a different row and in a different column, the picture is loaded twice.
    I've made an executable. I would like to post it, but I don't know whether that is common in this community.
    Code in DistanceFinder which extends JFrame:
    MySelectionListener listener = new MySelectionListener(cityTable, imageLabel);
            cityTable.getSelectionModel().addListSelectionListener(listener);
            cityTable.getColumnModel().getSelectionModel()
                .addListSelectionListener(listener);
    MySelectionListener:
    package gui;
    import gui.MyLabel;
    import java.awt.Toolkit;
    import javax.swing.ImageIcon;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JTable;
    import javax.swing.ListSelectionModel;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    * @author Iwan
    public class MySelectionListener implements ListSelectionListener {
         private JTable jtable;
         private MyLabel imageLabel;
         public MySelectionListener(JTable jtable, MyLabel imageLabel) {
              // TODO Auto-generated constructor stub
              this.jtable = jtable;
              this.imageLabel = imageLabel;
         /* (non-Javadoc)
          * @see javax.swing.event.ListSelectionListener#valueChanged(javax.swing.event.ListSelectionEvent)
         @Override
         public void valueChanged(ListSelectionEvent e) {
              // If cell selection is enabled, both row and column change events are fired
            if ((e.getSource() == jtable.getSelectionModel() || e.getSource() == jtable.getColumnModel().getSelectionModel())
                      && !e.getValueIsAdjusting()
                      && jtable.getSelectedColumn() != jtable.getSelectedRow()
                      && jtable.getSelectedColumn() != 0
                      && jtable.getSelectedRow() != 0 ){
                 imageLabel.setImage(getSelectedCell(jtable));
         private int[] getSelectedCell(JTable jtable){
              int[] selectedCell = {jtable.getSelectedColumn(), jtable.getSelectedRow()};
              return selectedCell;
         private void showInfoBox(JTable jtable, ListSelectionEvent e){
              JOptionPane.showMessageDialog(null, "Row changed to: " + jtable.getSelectedRow()
                        + "\n Column changed to: " + jtable.getSelectedColumn()
                        + "\nFirst: " + e.getFirstIndex()
                        + "\nLast: " + e.getLastIndex());
    }So the question remains:
    The valueChanged(ListSelectionEvent e) method defined by the ListSelectionListener interface is called two times when navigating in two directions and called once when navigating in one dimension.
    Can this problem easily be solved or is this an idea for improvement?

  • (URGENT) problem with JTable: can't catch ENTER and control focus in JTable

    I hava a JTable and a AbstractTableModel.
    Here is what i want to DO.
    When I press the ENTER or TAB I want to set focus to cell wich is 2 position away from the the sell I am editing
    on the same row in the JTable. How can I do this.
    in fact, that is my real question HOW to ?
    When I press the ENTER or TAB in JTABLE I want to tell to JTable which cell to grab the focus

    In the UI is defined the InputMap/ActionMap pair to respond to keys. There is defined an action for ENTER. I have had the same problem, and the only thing that worked for me was to clear the actionMap, and reassign some keys to their original action, and some (e.g. ENTER, TAB) to my actions. This worked. With TAB is harder beacuse i guess it's deeper in the JVM implemented, but after a while i've managed to overwrite that too.

  • Problem with JTable with JCheckBox as Header

    Hi,
    We have a JCheckBox as JTable Header. And respective data in that column also check boxes. For data check boxes, just i am sending Boolean object to object[][] data array. I am getting check Boxes as data components.
    For Header, i have create a TableRender object which is returning JCheckBox.
    Here my problem is,
    1) When i select a Header check box, all the check boxes are getting selected.
    2) Now we can reselect an data Check Box. When i reselect any data checkBox, Header CheckBox should be reselected. This is not happening. I was tried lot. Can any body give a solution to solve this problem.
    Please .... Please ...
    Thanks
    Mohan

    just call this method with null param on the JTable
    table.setTableHeader(null);
    cheers
    krishna

  • Flipping problems with JTables

    I have a JTable (with scroll bar ) and a JButton inside a Jframe.
    When I push the JButton another JFrame appears with another JTable inside.
    The problem is that when I close the upper JFrame and I try to move the scroll bar of the JTable inside the father JFrame it starts to flip doing an horrible effect for the general lauyout.The solution it could be overwrite the paint method....but actually for my Java knowledges is impossibe. Help !

    Sorry I mean flashing problems (not flipping.)
    The code is:
    JPanel p1=new JPanel();
    Label lab1=new Label(" LABORATORIO ANALISI CLINICHE");
    Label lab2=new Label(" Dr.ssa xxxxxxxxxxxx ");
         Label lab3=new Label(" C/o xxxxxxxxxxxxx ");
         Label lab4=new Label(" Via xxxxxxxxxxx nr 5/7");
         Label lab5=new Label(" 86100 xxxxxxxxxx");
    Label lab6=new Label(" tel. xxxxxxxxxx");
         p1.setLayout(new GridLayout(6,1));
    p1.add(lab1);
    p1.add(lab2);
    p1.add(lab3);
    p1.add(lab4);
    p1.add(lab5);
    p1.add(lab6);
    Report myReport=new Report(tableModels[p.getSelectedIndex()],"Printer Manager",p1);
    Actually Report is a class that prepare a JFrame with a JPanel and inside the JPanel there is a JScrollPane that get the JTable.That's the code for the Report class:
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.print.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.Dimension;
    public class Report extends Frame implements Printable
    JFrame frame;
    JTable tableView;
    JComponent component_dummy;
    public Report(AbstractTableModel tableModel,String title,JComponent component)
    super(title);
    this.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) { dispose(); } } );
    final String[] headers = {"Description", "open price",
         "latest price", "End Date", "Quantity"};
    final Object[][] data = {
    {"Box of Biros", "1.00", "4.99", new Date(), new Integer(2)},
    {"Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
    {"legal pad", "1.00", "2.49", new Date(), new Integer(1)},
    {"tape", "1.00", "1.49", new Date(), new Integer(1)},
    {"stapler", "4.00", "4.49", new Date(), new Integer(1)},
    {"legal pad", "1.00", "2.29", new Date(), new Integer(5)}
    TableModel dataModel = new AbstractTableModel() {
    public int getColumnCount() { return headers.length; }
    public int getRowCount() { return data.length;}
    public Object getValueAt(int row, int col) {
         return data[row][col];}
    public String getColumnName(int column) {
         return headers[column];}
    public Class getColumnClass(int col) {
    return getValueAt(0,col).getClass();}
    public boolean isCellEditable(int row, int col) {
    return (col==1);}
    public void setValueAt(Object aValue, int row, int column) {
    data[row][column] = aValue;
    dataModel=tableModel;
    tableView = new JTable(dataModel);
    // component_dummy= new JComponent();
    component_dummy=component;
    JScrollPane scrollpane = new JScrollPane(tableView);
    scrollpane.setPreferredSize(new Dimension(600,300));
    this.setLayout(new BorderLayout());
    this.add(BorderLayout.NORTH,component);
    this.add(BorderLayout.CENTER,scrollpane);
    JButton printButton= new JButton();
    printButton.setText("Stampa");
    //this.getContentPane().add(BorderLayout.SOUTH,printButton);
    this.add(BorderLayout.SOUTH,printButton);
    // for faster printing turn double buffering off
    RepaintManager.currentManager(
         frame).setDoubleBufferingEnabled(false);
    printButton.addActionListener( new ActionListener(){
    public void actionPerformed(ActionEvent evt) {
    PrinterJob pj=PrinterJob.getPrinterJob();
    pj.setPrintable(Report.this);
    pj.printDialog();
    try{
    pj.print();
    }catch (Exception PrintException) {}
    this.setVisible(true);
    this.pack();
    public int print(Graphics g, PageFormat pageFormat,
    int pageIndex) throws PrinterException
         Graphics2D g2 = (Graphics2D) g;
         g2.setColor(Color.black);
         int fontHeight=g2.getFontMetrics().getHeight();
         int fontDesent=g2.getFontMetrics().getDescent();
         //leave room for page number
         double pageHeight = pageFormat.getImageableHeight()-fontHeight;
         double pageWidth = pageFormat.getImageableWidth();
         double tableWidth = (double) tableView.getColumnModel().getTotalColumnWidth();
         double scale = 1;
         if (tableWidth >= pageWidth)
              scale = pageWidth / (tableWidth+(int)(pageWidth/2-pageWidth*0.43));
         double headerHeightOnPage=
    tableView.getTableHeader().getHeight()*scale;
         double tableWidthOnPage=tableWidth*scale;
         double oneRowHeight=(tableView.getRowHeight()+
    tableView.getRowMargin())*scale;
         int numRowsOnAPage=
    (int)((pageHeight-headerHeightOnPage)/oneRowHeight);
         double pageHeightForTable=oneRowHeight*numRowsOnAPage;
         int totalNumPages= (int)Math.ceil((
    (double)tableView.getRowCount())/numRowsOnAPage);
         if(pageIndex>=totalNumPages)
    return NO_SUCH_PAGE;
    g2.translate(0f,0f);
         g2.drawString("Laboratorio analisi Cliniche",(int)(pageWidth/2-pageWidth*0.33),
    (int)(pageHeight+fontHeight-fontDesent-pageHeight*0.86));
    g2.drawString("Dr.ssa xxxxxxxxx",(int)(pageWidth/2-pageWidth*0.33),
    (int)(pageHeight+fontHeight-fontDesent-pageHeight*0.82));
    g2.drawString("C/o xxxxxxxxxxxxxx",(int)(pageWidth/2-pageWidth*0.33),
    (int)(pageHeight+fontHeight-fontDesent-pageHeight*0.78));
    g2.drawString("Via xxxxxxxxxxx",(int)(pageWidth/2-pageWidth*0.33),
    (int)(pageHeight+fontHeight-fontDesent-pageHeight*0.74));
    g2.drawString("86100 xxxxxxxxx",(int)(pageWidth/2-pageWidth*0.33),
    (int)(pageHeight+fontHeight-fontDesent-pageHeight*0.70));
    g2.drawString("tel. 0874/316147-91720",(int)(pageWidth/2-pageWidth*0.33),
    (int)(pageHeight+fontHeight-fontDesent-pageHeight*0.66));
    //      g2.translate(0f,headerHeightOnPage);
         g2.translate((int)(pageWidth/2-pageWidth*0.33),-pageIndex*pageHeightForTable+(pageHeight+fontHeight-fontDesent-pageHeight*0.56));
         //If this piece of the table is smaller than the size available,
         //clip to the appropriate bounds.
         if (pageIndex + 1 == totalNumPages)
    int lastRowPrinted = numRowsOnAPage * pageIndex;
    int numRowsLeft = tableView.getRowCount() - lastRowPrinted;
    g2.setClip(0,(int)(pageHeightForTable * pageIndex),
    (int) Math.ceil(tableWidthOnPage),
    (int) Math.ceil(oneRowHeight * numRowsLeft));
         //else clip to the entire area available.
         else
    g2.setClip(0, (int)(pageHeightForTable*pageIndex),
    (int) Math.ceil(tableWidthOnPage),
    (int) Math.ceil(pageHeightForTable));
         g2.scale(scale,scale);
         tableView.paint(g2);
    g2.scale(1/scale,1/scale);
         g2.translate(0,pageIndex*pageHeightForTable);
         g2.translate(0, -headerHeightOnPage);
         g2.setClip(0, 0,(int) Math.ceil(tableWidthOnPage),
    (int)Math.ceil(headerHeightOnPage));
         g2.scale(scale,scale);
         tableView.getTableHeader().paint(g2); //paint header at top
         return Printable.PAGE_EXISTS;
    public static void main(String[] args)
    do you think that there are problems because the print method ? or mayby because I clipped the graphics area ?

Maybe you are looking for

  • Noob needs help: DrWeb-DAEMON - A message has not been checked due to licen

    I keep getting these emails (see below). Can someone please tell me what part of the email system is generating these emails? Are they normal? They seem to be blocking mostly spam (which is good) but, there is some email that is being blocked that I

  • Thunderbolt Hard Drive Not Recognized

    I've got a brand new Seagate Backup Plus 1tb hard drive and when I plug it in to the Thunderbolt input on my Mid 2010 Macbook Pro running Lion, it's not recognized in Finder. I looked in Disk Utility and it's not there. I looked in About this Mac and

  • Accepting Credit Card Payments

    Please be patient, this is new for me. I know the bare minimum, and have only designed basic web sites. (I'm primarily a print designer.) I have a client that needs to be able to accept credit card payments on his site. No shopping cart, no products

  • Accessing Sql Server from AS400 Java program

    Hi everybody, I am trying to access Sql Server from an AS400 Java program. I have tried various Sql Server JDBC drivers including the Microsoft one but no luck yet. When i try to compile my Java program (with driver file in the classpath) it gives so

  • Transaction data from one cost center to another cost center

    Hi All Can any one tel me how to move the Transaction data from one cost center to another cost center . My scenario is basically : Users posted for  company code 1003 for Cost center S00570 for the period 01.04.2007  to 30.11.2007 but it has to go t