Tricky problem in JTable

Hi there,
I am trying to make a JTable display the keyText of all the keys pressed, meaning if I write an "A" I want it to be shown as " shift + a ". Now I'm not quite sure about the way to handle the focus and how to trigger of the action that makes the editing textField receive the focus. Currently, when the table is called for the first time or when I switch between the fields, no modifier or actionKey can be displayed until the first keyTypedEvent. E.g when I press the a-key I get to be shown an "a". After having done This I get "Aa" or, having pressed the shift-key, "shift" and then "AA". The keyListener is added to the textField and as new instance to the table as well. Can anybody tell me, how to modify myKeyListener to directly focus the textField or give me any idea for a different approach of this problem?
Thanks in advance, Bjorn
package com.brain.keymap;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class MyKeyListener implements KeyListener{
    public MyKeyListener() {
        super();
    public void keyTyped(KeyEvent e) {
    public void keyPressed(KeyEvent e) {
        boolean focus = false;
        Component c, editor;
        int keyCode = e.getKeyCode();
        c = (Component) e.getSource();
        if (c instanceof InputTable) {
            InputTable tbl = (InputTable) c;
            editor = tbl.getEditorComponent();
            if (editor instanceof JTextField) {
                ((JTextField) editor).setText(KeyEvent.getKeyText(keyCode));
                e.consume();
        }else {
            if( c instanceof JTextField){
                ((JTextField) c).setText(KeyEvent.getKeyText(keyCode));
                e.consume();
    public void keyReleased(KeyEvent e) {
}

Hey scheide,
thanks, it was the tip about consuming the consuming the keyStroke that solved it. I simply had to consume the keyTypedEvent. Now It all works fine. Just in case you might want to have a look at it, here's the code.
public class MyKeyListener implements KeyListener{
    String input = "", temp;
    public MyKeyListener() {
        super();
    public void keyTyped(KeyEvent e) {
        e.consume();
    public void keyPressed(KeyEvent e) {
        createInput(e);
    public void keyReleased(KeyEvent e) {
    public void createInput(KeyEvent e){
        Component c, editor = null;
        int keyCode = e.getKeyCode();
        //disable focusTraversal except for tab and enter
        if (!(keyCode == KeyEvent.VK_ENTER || keyCode == KeyEvent.VK_TAB)){
            try{
                editor.setFocusTraversalKeysEnabled(false);
            }catch(NullPointerException ex){}
        c = (Component) e.getSource();
        if (c instanceof InputTable) {
            InputTable tbl = (InputTable) c;
            editor = tbl.getEditorComponent();
            //focussing the table in field [0/0] at first call of table
            if (editor == null) {
                try{
                    int row = tbl.getSelectedRow();
                    int column = tbl.getSelectedColumn();
                    if( row == -1 )
                        row = 0;
                    if( column == -1)
                        column = 0;
                    tbl.editCellAt(row , column );
                    editor = tbl.getEditorComponent();
                }catch(Exception ex){}
            if( editor instanceof JTextField && !(keyCode == KeyEvent.VK_TAB || keyCode == KeyEvent.VK_ENTER )){
                if (input == ""){
                    input = (KeyEvent.getKeyText(keyCode));
                    ((JTextField) editor).setText(input);
                    temp = input;
                }else{
                    input = input.concat(" + ").concat(KeyEvent.getKeyText(keyCode));
                    ((JTextField) editor).setText(input);
                    temp = input;
            //when editing the input call of method editFieldValue
        }else if( c instanceof JTextField){
            ((JTextField) c).setText(editFieldValue(temp, e));
        //clear the inputString in case of tab or enter
        if(keyCode == KeyEvent.VK_TAB || keyCode == KeyEvent.VK_ENTER ){
            input = "";
    public String editFieldValue(String val, KeyEvent event){
        int code;
        String value = val;
        code = event.getKeyCode();
        StringTokenizer tokenizer;
        switch(code){
            case KeyEvent.VK_BACK_SPACE:
                int count = 0;
                tokenizer = new StringTokenizer(value,"+");
                value = "";
                while ( count < tokenizer.countTokens()){
                    value = value.concat("+").concat(tokenizer.nextToken());
                    count++;
                break;
        return value;
}Now I am trying to design a way to edit the input when the JTextfield has the focus. I don't really think I am trying in the right spot, since both the JTable and the TextField get different instances of the KeyListener.
I guess, I'll try and make a different Listener for the Textfield.
One more time thanks a lot for your help, Bjorn

Similar Messages

  • Tricky problem calling JTable

    Hi,
    I am pretty new to swing. I wish to create in a JFrame a menuItem "Open" which causes a table of database primary key entries to popup. On clicking on the desired entry another table is added to the JFrame showing all the database fields for that Primary key entry.
    I have the popup "open" table when I click on the Open menuItem in the JFrame and I have a mouseListener incorporated for a click on a table row. When I make the click I want a table to popup in my original Jframe. MY Question..
    How do I get my mouseListener to find or point to the original JFrame (which actually called the "open" table in the first place).
    i.e see picture (meant to show a loop)
    JFrame class ----> instantiates "Open" table ----->
    <---------<---<--<-------------<---------------<-
    instantiates another table in the original JFrame
    Is is possible or how do you code this loop
    thanks
    Willie

    I normally do this by using an anon inner class for the event of the button. Inside that you can refer to the JFrame. It would look something like this:
    public class YourFrame extends JFrame {
       public void initComponents() {
       // initialize your components
       JMenuItem open = ...;
       open.addActionListener( new ActionListener() {
          public void actionPerformed( ActionEvent ae ) {
             // do what you want with the JFrame
             JFrame.this.getContentPane().add( new JTable() );
    }I hope I didn't mess up the syntax.

  • 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 );

  • 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);
    }

  • Problem in JTable cell renderer

    Hi
    One problem in JTable cell. Actually I am using two tables while I am writing renderer for word raping in first table .. but it is affected in last column only remain is not being effected�. Please chaek it out what is exact I am missing�
    Thanks
    package com.apsiva.tryrowmerge;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.ArrayList;
    import java.util.EventObject;
    import java.util.Hashtable;
    import java.net.*;
    import javax.swing.*;
    import javax.swing.border.Border;
    import javax.swing.border.EmptyBorder;
    import javax.swing.event.*;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    class Item_Details extends JFrame {
        ApsJTable itemTable = null;
         ApsJTable imageTable = null;     
         ArrayList data = new ArrayList();
         String[] columns = new String[2];
         ArrayList data1 = new ArrayList();
         String[] columns1 = new String[2];
         ItemTableModel itemTableModel = null;
         ItemTableModel itemTableModel1 = null;
         public Item_Details()
              super("Item Details");          
             this.setSize(600,100);
             this.setBackground(Color.WHITE);
              this.setVisible(true);
             init();          
         private void init(){
              ////////////// Get data for first Table Model  ////////////////////////////
              data = getRowData();
              columns = getColData();
              System.out.println(columns[0]);
             itemTableModel = new ItemTableModel(data,columns);
             /////////////Get Data for Second Table Model //////////////////////////////
              try{
                        data1 = getRowData1();
                 }catch(Exception e){}
              columns1 = getColumns1();
             itemTableModel1 = new ItemTableModel(data1,columns1);
             ///////////// Set Data In Both Table Model //////////////////////////////////
              itemTable = new ApsJTable(itemTableModel);
              imageTable = new ApsJTable(itemTableModel1);
              this.itemTable.setShowGrid(false);
              this.imageTable.setShowGrid(false);
              this.itemTable.setColumnSelectionAllowed(false);
              this.imageTable.setColumnSelectionAllowed(false);
              System.out.println(itemTable.getColumnCount());
              this.imageTable.setRowHeight(getImageHeight()+3);
              JScrollPane tableScrollPane = new JScrollPane(this.imageTable,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              tableScrollPane.setRowHeaderView(this.itemTable);
              //itemTable.getColumnModel().getColumn(0).setMaxWidth(200);
              itemTable.getColumnModel().getColumn(0).setPreferredWidth(200);
              itemTable.getColumnModel().getColumn(1).setPreferredWidth(600);
              tableScrollPane.getRowHeader().setPreferredSize(new Dimension(800, 0));
              itemTable.getTableHeader().setResizingAllowed(false);
              itemTable.getTableHeader().setReorderingAllowed(false);
              itemTable.setColumnSelectionAllowed(false);
              //itemTable.setRowHeight(25);
              itemTable.setCellSelectionEnabled(false);
              itemTable.setFocusable(false);
              imageTable.getTableHeader().setReorderingAllowed(false);
              imageTable.setFocusable(false);
              imageTable.setCellSelectionEnabled(false);
              //tableScrollPane.setOpaque(false);
              itemTable.setAutoCreateColumnsFromModel(false);
              int columnCount = itemTable.getColumnCount();
              for(int k=0;k<columnCount;k++)
                   TableCellRenderer renderer = null;
                   TableCellEditor editor = null;
                   renderer = new TextAreaCellRenderer();     // NEW
              //     editor = new TextAreaCellEditor();     
              //     TableColumn column = new TableColumn(k,itemTable.getColumnModel().getColumn(k).getWidth(),renderer, editor);
                   System.out.println(k);
                   itemTable.getColumnModel().getColumn(k).setCellRenderer(renderer);          
                   //itemTable.getColumnModel().getColumn(k).setCellEditor(editor);
                   /*itemTable.getColumnModel().getColumn(1).setCellRenderer(new TextAreaCellRenderer());
                   itemTable.getColumnModel().getColumn(1).setCellEditor(new TextAreaCellEditor());*/
    //               itemTable.setShowGrid(false);
                   //itemTable.addColumn(column);
                   //itemTable.getColumnModel().getColumn(k).setCellRenderer(new MultiLineCellRenderer());
                   //itemTable.getColumnModel().getColumn(k).setCellEditor(new TextAreaCellEditor());
    ////////////---------------------- Here background color is being set--------------//////////////////
              this.imageTable.getParent().setBackground(Color.WHITE);
              this.itemTable.getParent().setBackground(Color.WHITE);
              tableScrollPane.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER,this.itemTable.getTableHeader());
              getContentPane().add(tableScrollPane,BorderLayout.CENTER);
              getContentPane().setVisible(true);
         public static void main(String[] str){
              com.incors.plaf.alloy.AlloyLookAndFeel.setProperty("alloy.licenseCode", "2005/05/28#[email protected]#1v2pej6#1986ew");
              try {
                javax.swing.LookAndFeel alloyLnF = new com.incors.plaf.alloy.AlloyLookAndFeel();
                javax.swing.UIManager.setLookAndFeel(alloyLnF);
              } catch (javax.swing.UnsupportedLookAndFeelException ex) {
              ex.printStackTrace();
              Item_Details ID = new Item_Details();
              ID.setVisible(true);
    public ArrayList getRowData()
         ArrayList rowData=new ArrayList();
         Hashtable item = new Hashtable();
         item.put(new Long(0),new String("Item No:aaaaaaa aaaaaaaa aaaaaaaaa aaaaaa"));
         item.put(new Long(1),new String("RED-1050"));
         rowData.add(0,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Description:rt r trtrt rttrytrr tytry trytry tr tr rty thyjyhjhnhnhgg hhjhgjh"));
         item.put(new Long(1),new String("SYSTEM 18 mbh COOLING 13 mbh HEATING 230/208 v POWER AIRE "));
         rowData.add(1,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Stage:"));
         item.put(new Long(1),new String("Draft"));
         rowData.add(2,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Price: "));
         item.put(new Long(1),new String("999.00"));
         rowData.add(3,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Features:"));
         item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
         rowData.add(4,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Features:"));
         item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
         rowData.add(5,item);
         item = new Hashtable();
         item.put(new Long(0),new String("Features:"));
         item.put(new Long(1),new String("SYSTEM COOLING & HEATING 12 mbh 230/208 v POWER AIRE SYSTEM1234 COOLING & HEATING 12 mbh 230/208 v POWER AIRE "));
         rowData.add(6,item);
         /*item.put(new Long(0),new String("Family Sequence"));
         item.put(new Long(1),new String("8.00"));
         rowData.add(5,item);
         item.put(new Long(0),new String("Family Sequence"));
         item.put(new Long(1),new String("8.00"));
         rowData.add(6,item);
         item.put(new Long(0),new String("Family Sequence"));
         item.put(new Long(1),new String("8.00"));
         rowData.add(7,item);
         return rowData;
    public String[] getColData()
         String[] colData = new String[]{"Attribute","Value"};
         return colData;
    public ArrayList getRowData1()throws MalformedURLException{
         ArrayList rowData = new ArrayList();
         Hashtable item = new Hashtable();
         String str = new String("http://biis:8080/assets/PRIMPRIM/Adj_BeacM_Small.jpg");
         URL url = new URL(str);
         ImageIcon ic = new ImageIcon(url);
         ImageIcon scaledImage = new ImageIcon(ic.getImage().getScaledInstance(getImageHeight(), -1,Image.SCALE_SMOOTH));
         item.put(new Long(0), scaledImage);
         rowData.add(0,item);
         String str1 = new String("http://biis:8080/assets/PRIMPRIM/Adj_BeacM_Small.jpg");
         URL url1 = new URL(str1);
         ImageIcon ic1 = new ImageIcon(url1);
         ImageIcon scaledImage1 = new ImageIcon(ic1.getImage().getScaledInstance(120, -1,Image.SCALE_DEFAULT));
         item.put(new Long(0),scaledImage1);
         rowData.add(1,item);
         return rowData;
    public String[] getColumns1(){
         String[] colData = new String[]{"Image"}; 
         return colData;
    public int getImageHeight(){
         ImageIcon ic = new ImageIcon("c:\\image\\ImageNotFound.gif");
         return ic.getIconHeight();
    class TextAreaCellRenderer extends JTextArea implements TableCellRenderer
         public TextAreaCellRenderer() {
              setEditable(false);
              setLineWrap(true);
              setWrapStyleWord(true);
         public Component getTableCellRendererComponent(JTable table,
              Object value, boolean isSelected, boolean hasFocus,
              int nRow, int nCol)
              if (value instanceof String)
                   setText((String)value);
              // Adjust row's height
              int width = table.getColumnModel().getColumn(nCol).getWidth();
              setSize(width, 1000);
              int rowHeight = getPreferredSize().height;
              if (table.getRowHeight(nRow) != rowHeight)
                   table.setRowHeight(nRow, rowHeight);
              this.setBackground(Color.WHITE);
              return this;

    I think Problem is between these code only
    for(int k=0;k<columnCount;k++)
                   TableCellRenderer renderer = null;
                   TableCellEditor editor = null;
                   renderer = new TextAreaCellRenderer();
                                                                itemTable.getColumnModel().getColumn(k).setCellRenderer(renderer);or in this renderer
    class TextAreaCellRenderer extends JTextArea implements TableCellRenderer
         public TextAreaCellRenderer() {
              setEditable(false);
              setLineWrap(true);
              setWrapStyleWord(true);
         public Component getTableCellRendererComponent(JTable table,
              Object value, boolean isSelected, boolean hasFocus,
              int nRow, int nCol)
              if (value instanceof String)
                   setText((String)value);
              // Adjust row's height
              int width = table.getColumnModel().getColumn(nCol).getWidth();
              setSize(width, 1000);
              int rowHeight = getPreferredSize().height;
              if (table.getRowHeight(nRow) != rowHeight)
                   table.setRowHeight(nRow, rowHeight);
              this.setBackground(Color.WHITE);
              return this;
    }

  • Colum Resizing problem in JTable

    HI All,
    I am facing a problem with JTable while resizing the colum. when user clicks and drags to resize a column, the column width increases continuously till the mouse button is released. I am sure this sounds like a vague description,
    (eg)
    when I click on a column boundary and drag, the column width is getting increase beyond where the cursor of the mouse is. In a normal table, when I click and drag, the column resizes to the size that I have the mouse position at, and gets set to the width when I release the mouse. But right now, when I click the mouse and drag to say a width of 50 from 10, it is still increasing beyond 50 and stops when I release the mouse at about 100 or higher. I hope this is a clearer explanation.
    In Java 1.2, it works fine. but in java 1.4...
    If Anyone knows, please let me know
    Advance thanks for any comments and suggestion..
    Best Regards,
    Muthu

    I solved this problem... Problem is getPreferredSize() method. I override this method
    Thank u for ur suggestion..
    Best Regards,
    Muthu

  • Problem of JTable's column setPreferredWidth.

    Hi All,
    I have a problem about JTable,I want to set the preferredwidth for every column when the table is first established,but it is always failed.
    Could someone tell me the root?Thanks!
    import java.awt.*;
    import javax.swing.*;
    public class MixerTest2 extends JFrame {
    public MixerTest2() {
    super("Customer Editor Test");
    setSize(600,160);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    JTable typeTable=new JTable();
    typeTable=new JTable(new String [][] {
    {"312fs", "33232", "32", "32"},
    {"3212fsdfa12", "3322", "32", "32"},
    {"3212fa12", "321212", "321212", "321212"},
    {"3212gsds12", "321212", "321212", "321212"}
    new String [] {
    "Title 1", "Title 2", "Title 3", "Title 4"
    typeTable.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
    typeTable.getColumnModel().getColumn(0).setPreferredWidth(10);
    typeTable.getColumnModel().getColumn(1).setPreferredWidth(30);
    JScrollPane typeTableScrollPane=new JScrollPane(typeTable);
    getContentPane().add(typeTableScrollPane);
    public static void main(String args[]) {
    MixerTest2 mt = new MixerTest2();
    mt.setVisible(true);
    -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.
    The problem is that the size of the frame is greater than the size of the table so the widths of all the columns get adjusted after you specify the original default size.
    Your code should be something like:
    typeTable.setPreferredScrollableViewportSize(typeTable.getPreferredSize());
    JScrollPane typeTableScrollPane=new JScrollPane(typeTable);
    mt.pack();
    mt.setVisible(true);Or you might be able to use my [Table Column Adjuster|http://www.camick.com/java/blog.html?name=table-column-adjuster] which will resize the columns automatically.

  • Hi!!! A Problem in JTable

    HI,
    I have a problem in JTable.I have a Jtable and a button named validate.My JTable first displays a set of rows and colums.if we name the colns as a,b and c. when i click the validate button i will take the values of a1 and b1 and do some validations. If it is in correct position then the row remains as it is else i will change the value of b1 to a1 position and vice versa. This happens in a loop till the end and the data vector of the table gets changed accordingly.Now the problem is suppose if there are 10 rows and the value changes in row 1,5,7 thn i need that rows alone to be colored while the button ends its action.Finally the JTable should be viewed as row 1,5,7 colored and others in their default color....
    Please help me...
    Message was edited by:
    tis-is-hari

    You will have to create your own Renderer or use a table like JXTable from swing labs that allows highlighting.

  • 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

  • JCheckBox clicking problem in JTable

    Hi,
    I have a column of JCheckBox in a JTable. The JTable is only used to layout the controls(for lagecy reason). The JCheckBox has an item change listener attached. The problem is that OCCASIONALLY when the JCheckBox[i] was clicked, the debug in itemStateChanged show the source object was NOT JChechBox, it was JCheckBox[i+1] or JCheckBox[i-1]. In other word, it was the check box in the previous or next row changed state.
    Has anybody experienced similar problems? Is it a problem of JTable dispatching mouse click event?
    How to solve the problem?
    Thanks

    I'm not sure why you get the results you do, but instead of adding a change listener to the JCheckBox you could add a TableModelListener to the TableModel. This will fire an event whenever any data is changed. This thread shows a simple example:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=425540

  • Cell Editor Problem in JTable

    I have a problem using JTable. I have a requirement like each specified cell will have different editors like JtextField or Jcombobox as per some condition. I am building the rows at run time. Number of rows may vary as per condition.
    can anyone guide me what to do?
    thanks

    Override the getCellEditor(...) method to return the appropriate editor.

  • 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
    }

  • 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.

Maybe you are looking for

  • ITunes Music Files Corrupted by Genius and/or iPod Touch?

    After installing an iPod Touch for the first time, and also running Genius for the first time, on my large (199.61 GB) music library (located on a WD MyBook 500 GB external hard drive), all of my music has disappeared according to iTunes. This is bec

  • Low quality export for stop motion animation stills from Canon 5D Mark ii

    Thank you very much beforehand to anyone who is willing to look through this issue, it's been a long and frustrating process so far... I am attempting to put together a stop motion animation in Final Cut Express but my exports are always either low q

  • Best practice to change SAP BW login parameters after Universe migration

    Hello All, I am working with SAP BW and BOBJ XI 3.1. And we are using "Use specified username and password" Authentication mode when we are establishing the connection to SAP BW. At present after migrating the Universe let's say from Dev to Test, We

  • Intercompany billing with thirdparty customer order document flow

    Hi all . I have recieved a problem in our Intercompanyprocess Heres the scenario 1. Create customer order with at least 1 itemcategory TAS 2. Creates an PO from the requisition 3. recieve and register invoice from vendor via MIRO 4. Create customer i

  • Query about SAP ABAP programming?

    I am not good at programming but wanted to make a career in SAP. SAP counselor said that being a fresher it is extremely difficult to find a job in other modules and ABAP is the only option for me, but she said that programming is not that hard in AB