0

I have problem with cursor in JTable. I've tried to find answer in the forum but can't find the answer I expected. Here is my runnable Java:

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;
import javax.swing.table.AbstractTableModel;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.JTable;

public class Fpos extends JFrame {

        public static void main(String[] args) {
                EventQueue.invokeLater(new Runnable() {
                        public void run() {
                                try {
                                    Fpos frame = new Fpos();
                                    frame.setVisible(true);
                                    frame.setLocationRelativeTo(null);  //make frame center of screen                   
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                        }
                });
        }


        public Fpos() {
                //create Jpanel
                setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                setBounds(10, 10, 1300, 700);
                JPanel contentPane = new JPanel();
                contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
                setContentPane(contentPane);
                contentPane.setLayout(null);
                //create label TOTAL
                JLabel lblTotal = new JLabel("TOTAL : Rp.");
                lblTotal.setFont(new Font("Wide Latin", Font.PLAIN, 30));
                lblTotal.setBounds(33, 25, 312, 31);
                contentPane.add(lblTotal);
                //create label Total Amount
                JLabel lblNewLabel = new JLabel("123,456,789");
                lblNewLabel.setHorizontalAlignment(SwingConstants.RIGHT);
                lblNewLabel.setFont(new Font("Wide Latin", Font.PLAIN, 60));
                lblNewLabel.setBounds(571, 6, 659, 61);
                contentPane.add(lblNewLabel);
                //create jtable in scrollpane
                 JTable table = new JTable(new MyTableModel());                 
                 JScrollPane sp=new JScrollPane(table);
                 sp.setBounds(20,76,1240,572);
                 contentPane.add(sp);            
        }

    //tablemodel
    class MyTableModel extends AbstractTableModel {
            private String[] columnNames = {"PLU", "NAME", "UOM", "QTY", "PRICE","AMOUNT"};
            private Object[][] data = {{"", "", "", new Double(0), new Integer(0), new Integer(0)}};    
            public int getColumnCount() {return columnNames.length;}
            public int getRowCount() {return data.length;}
//          public String getColumnName(int col) {return columnNames[col];}
            public Object getValueAt(int row, int col) {return data[row][col];}
            //auto formating table: string=left alignment, numeric=right alignment, checkbox=check box not true/false
            public Class getColumnClass(int c) {return getValueAt(0, c).getClass();}
            //make table editable only for just first column        
            public boolean isCellEditable(int row, int col) {if (col == 0) {return true;} else{return false;}}
            //make table can change value         
            public void setValueAt(Object value, int row, int col) {
                    data[row][col] = value;
                    fireTableCellUpdated(row, col);
            }
    }

}

The output is just fine but the table is not ready to be input. I have to double click column PLU first row to be ready for input. What I want is as soon as I run it, cursor is blinking at column PLU first row, ready for input without double clicking it.

Any suggestion on how to achieve this?

Ansharja
  • 1,237
  • 1
  • 14
  • 37
Hendra
  • 43
  • 9
  • 2
    Take a look at [`JTable#editCellAt`](https://docs.oracle.com/javase/8/docs/api/javax/swing/JTable.html#editCellAt-int-int-) – MadProgrammer Nov 18 '17 at 05:27
  • Thanks MadProgrammer, i've found the solution. I've posted new question here https://stackoverflow.com/questions/47447780/key-binding-in-jtable-editor. its keybinding bound to the table editor not the table. Hoping you can help too. – Hendra Nov 23 '17 at 08:35

2 Answers2

2

The basics would be:

table.changeSelection(0, 0, false, false);

if (table.editCellAt(0, 0))
{
    Component editor = table.getEditorComponent();
    editor.requestFocusInWindow();
    //((JTextComponent)editor).selectAll();
}

The changeSelection(...) is like clicking on the row (so the entire row gets highlighted), then the editCellAt(...) places the cell in edit mode.

Then you need to places focus on the editor and optionally select all the text so it can be replaced as you type.

Edit:

The cursor is still not blinking

Wrap the code in a SwingUtilities.invokeLater(...) to make sure the code is executed after the frame is visible:

SwingUtilities.invokeLater(new Runnable()
{
    public void run()
    {
        table.changeSelection(0, 1, false, false);

        if (table.editCellAt(0, 1))
        {
            Component editor = table.getEditorComponent();
            editor.requestFocusInWindow();
            //((JTextComponent)editor).selectAll();
        }
    }
});
camickr
  • 321,443
  • 19
  • 166
  • 288
  • Thank you Camickr for your quick reply. I've tried your solution n its ready for input (without double click) now as soon as I run it. Tho cursor is still not blinking on row 0 col 0 but I think its ok for now. My goal is developing a new software like POS software that cashier uses in supermarket, their table is always ready for input with cursor blinking on col 0. Is it possible for that Mr/Mrs/Ms Camickr? – Hendra Nov 20 '17 at 05:13
  • @Hendra, don't forget to "accept" the answer by clicking on the checkmark so people know the problem has been solved. – camickr Nov 23 '17 at 05:00
  • I'm sorry Camickr, this is my first time posting a question. I can't find the checkmark in this page. May I ask where is the checkmark? – Hendra Nov 23 '17 at 05:08
  • I think I found where the checkmark is. There is up button on your answer (comment=the answer is useful). I've clicked it 4 times. It says thanks for the feedback etc. I hope it works – Hendra Nov 23 '17 at 05:31
  • Not up bottom but check button under down bottom. I've checked your answer. Thanks Camickr. – Hendra Nov 23 '17 at 05:39
  • Hi Camickr, I've posted new question hoping you can help too, thanks. https://stackoverflow.com/questions/47447780/key-binding-in-jtable-editor – Hendra Nov 23 '17 at 08:30
0

Yes, that added code make cursor blinking on selected cell n making it ready for input.

Thank you very much Camickr.

I put the runnable code below just in case someone may happen to meet same case.

import java.awt.Component;

import java.awt.EventQueue;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.JScrollPane;

import javax.swing.border.EmptyBorder;

import javax.swing.table.AbstractTableModel;

import javax.swing.JLabel;

import java.awt.Font;

import javax.swing.SwingConstants;

import javax.swing.SwingUtilities;

import javax.swing.JTable;

public class test extends JFrame {

    public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                    public void run() {
                            try {
                                test frame = new test();
                                frame.setVisible(true);
                                frame.setLocationRelativeTo(null);      //make frame center of screen                   
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                    }
            });
    }


    public test() {
            //create Jpanel
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setBounds(10, 10, 1300, 700);
            JPanel contentPane = new JPanel();
            contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
            setContentPane(contentPane);
            contentPane.setLayout(null);
            //create label TOTAL
            JLabel lblTotal = new JLabel("TOTAL : Rp.");
            lblTotal.setFont(new Font("Wide Latin", Font.PLAIN, 30));
            lblTotal.setBounds(33, 25, 312, 31);
            contentPane.add(lblTotal);
            //create label Total Amount
            JLabel lblNewLabel = new JLabel("123,456,789");
            lblNewLabel.setHorizontalAlignment(SwingConstants.RIGHT);
            lblNewLabel.setFont(new Font("Wide Latin", Font.PLAIN, 60));
            lblNewLabel.setBounds(571, 6, 659, 61);
            contentPane.add(lblNewLabel);
            //create jtable in scrollpane
             JTable table = new JTable(new MyTableModel());                 
             JScrollPane sp=new JScrollPane(table);
             sp.setBounds(20,76,1240,572);
             contentPane.add(sp);
            //make cursor blinking on selected cell
             SwingUtilities.invokeLater(new Runnable(){
                    public void run() {
                          table.changeSelection(0, 0, false, false);
                          if (table.editCellAt(0, 0)){
                              Component editor = table.getEditorComponent();
                              editor.requestFocusInWindow();
                              //((JTextComponent)editor).selectAll();
                          }
                    }
            });

    }

//tablemodel
class MyTableModel extends AbstractTableModel {
        private String[] columnNames = {"PLU", "NAME", "UOM", "QTY", "PRICE","AMOUNT"};
        private Object[][] data = {{"", "", "", new Double(0), new Integer(0), new Integer(0)}};    
        public int getColumnCount() {return columnNames.length;}
        public int getRowCount() {return data.length;}
//          public String getColumnName(int col) {return columnNames[col];}
        public Object getValueAt(int row, int col) {return data[row][col];}
        //auto formating table: string=left alignment, numeric=right alignment, checkbox=check box not true/false
        public Class getColumnClass(int c) {return getValueAt(0, c).getClass();}
        //make table editable only for just first column        
        public boolean isCellEditable(int row, int col) {if (col == 0) {return true;} else{return false;}}
        //make table can change value         
        public void setValueAt(Object value, int row, int col) {
                data[row][col] = value;
                fireTableCellUpdated(row, col);
        }
}

}

Jamshaid
  • 370
  • 2
  • 11
  • 40
Hendra
  • 43
  • 9