3

I have here a very simple demo program and sorry for the not so short version of code but its the shortest I can do. Anyway, I have here a jtable with editable cell for column 2. I want the numpad on the right side to append to the selected cell of the jtable but the .setValueAt() does not do that. Is there any way that the numpad on the right side to append to the selected cell? Or I should

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.EventObject;

import javax.swing.*;
import javax.swing.border.BevelBorder;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.event.CellEditorListener;
import javax.swing.table.*;

public  class Jtabledemo {

    private static class JTabledemo {

        JTable table;
        JFrame Card = new JFrame();
        JTabbedPane card_tab = new JTabbedPane(); // FOR TAB
        JPanel buttonpanel = new JPanel(); // FOR BUTTON BELOW
        FlowLayout flow = new FlowLayout(FlowLayout.LEFT);

        public JTabledemo() {      
            Card.setVisible(true);
            Card.setSize(821,340);
            Card.setTitle("");
            Card.setResizable(false);

            final Toolkit toolkit = Toolkit.getDefaultToolkit();
            Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();      
            int x=(int)((dimension.getWidth() - Card.getWidth())/2);
            int y=(int)((dimension.getHeight() - Card.getHeight())/2);

            Card.setLocation(x, y);
            Card.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

            JPanel bodypanel = new JPanel();
            bodypanel.setLayout(new BorderLayout());

            JPanel container = new JPanel();
            container.setLayout(new BorderLayout());

            JPanel jp1 = new JPanel();
            jp1.setBackground(Color.lightGray);
            jp1.setPreferredSize(new Dimension(510,260));
            jp1.setLayout(new BorderLayout());

            table = new JTable(new ExampleTableModel());
            JScrollPane scrollPane = new JScrollPane(table);
            table.setFillsViewportHeight(true);

            JTableHeader header = table.getTableHeader();
            table.setRowHeight(20);
            jp1.add(scrollPane);

            JPanel buttonpanel = new JPanel();
            buttonpanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
            buttonpanel.setBorder(new EmptyBorder(0,0,0,0));

            JButton btnOk = new JButton("Ok");
            btnOk.setPreferredSize(new Dimension(90, 40));
            buttonpanel.add(btnOk);

            final JButton btnCancel = new JButton("Cancel");
            btnCancel.setPreferredSize(new Dimension(90, 40));
            buttonpanel.add(btnCancel);

            JPanel container2 = new JPanel();
            container2.setLayout(new BorderLayout());
            container2.setPreferredSize(new Dimension(344,0));

            JPanel numberpanel = new JPanel();
            numberpanel.setPreferredSize(new Dimension(235,0));
            numberpanel.setBorder(new EmptyBorder(25,0,0,0));
            numberpanel.setBorder(BorderFactory.createEtchedBorder(Color.white,Color.gray));
            numberpanel.setLayout(flow);

            JButton button_7 = new JButton("7");
            button_7.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    table.setValueAt("7", table.getSelectedRow(), table.getSelectedColumn());
                }
            });
            button_7.setPreferredSize(new Dimension(70, 70));
            numberpanel.add(button_7);

            JButton button_8 = new JButton("8");
            button_8.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    table.setValueAt("8", table.getSelectedRow(), table.getSelectedColumn());
                }   
            });
            button_8.setPreferredSize(new Dimension(70, 70));
            numberpanel.add(button_8);

            JButton button_9 = new JButton("9");
            button_9.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    table.setValueAt("9", table.getSelectedRow(), table.getSelectedColumn());
                }   
            });
            button_9.setPreferredSize(new Dimension(70, 70));
            numberpanel.add(button_9);

            Card.add(bodypanel);
            bodypanel.add(container, BorderLayout.WEST);
            container.add(jp1,BorderLayout.NORTH);
            container.add(buttonpanel,BorderLayout.SOUTH);
            bodypanel.add(container2, BorderLayout.EAST);
            container2.add(numberpanel, BorderLayout.EAST);
        }

        public static class ExampleTableModel extends DefaultTableModel {
            public ExampleTableModel() {
                super(new Object[]{"Tank", "Current", "Dip"}, 0);
                for (int index = 0; index < 4; index++) {
                    addRow(new Object[]{index, "Text for " + index, "Na na", index});
                }
            }

            @Override
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return columnIndex == 2;
            }
        }
    }

    public static void main(String[] args){
    //Use the event dispatch thread for Swing components
        EventQueue.invokeLater(new Runnable() {
            @Override
            @SuppressWarnings("ResultOfObjectAllocationIgnored")
            public void run() {
                new JTabledemo();         
            }
        });
    }
}

EDIT

When I click the numpad it should append to the selected cell like if you click on the numpad only 1 number is inserted. I want those numbers to append in the selected cell.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
user3771102
  • 558
  • 2
  • 8
  • 27

2 Answers2

6

I want those numbers to append in the selected cell.

Then append the number to the existing value.

For example the code for the "7" button could be something like:

int row = table.getSelectedRow();
int column = table.getSelectedColumn();
String value = table.getValueAt(row, column) + "7";
table.setValueAt(value, row, column);

Of course a better solution is to use a common ActionListener, then you can make the code more generic:

int row = table.getSelectedRow();
int column = table.getSelectedColumn();
String value = table.getValueAt(row, column) + e.getActionCommand();
table.setValueAt(value, row, column);

The action command simply defaults to the string of the button.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • Yes. That's the one! Thank you!! I'll give a check in your answer later. :) – user3771102 Jul 23 '14 at 16:44
  • I want my code to be generic but I don't know how to use an `actionCommand`. – user3771102 Jul 24 '14 at 04:19
  • @user3771102: You will create an `ActionListener` as shown in this [example](http://stackoverflow.com/a/9824555/1057230), and inside the `actionPerformed(...)`, simply write the four lines provided in the answer from __camickr__. And then replace all `button.addActionListener(new ActionListener()...)` with `button.addActionListener(updateListener)`. That is it. – nIcE cOw Jul 24 '14 at 05:05
  • @nIcEcOw Yes I already figure it out. Thank you. It's already in Hovercraft's answer :) – user3771102 Jul 24 '14 at 08:36
3

Don't forget to check if columns and rows have been selected (selected row and column index is not -1):

public void actionPerformed(ActionEvent e) {
   int selectedRow = table.getSelectedRow();
   int selectedColumn = table.getSelectedColumn();

   // **** better first check that user has selected something
   if (selectedRow < 0 || selectedColumn < 0) {
      return;
   }

   // **** next make sure cell is editable
   if (table.isCellEditable(selectedRow, selectedColumn)) {

      // get current value
      String value = table.getValueAt(selectedRow, selectedColumn).toString();

      // append new value
      value += "7";  // or actionCommand as per camickr -- 1+ to his answer.
      table.setValueAt(value, selectedRow, selectedColumn);
   }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373