Updating Data in a JTable

偶尔善良 提交于 2020-01-15 07:53:40

问题


Lets say I have a table. One of the cells holds a JLabel. If I change the text of the JLabel how do I get the JTable to show the change? Look at the following code, what should I change to make it show the changes to the JLabel?

public class ActivTimerFrame extends JFrame implements ActionListener{
    //Data for table and Combo Box
    String timePlay =  "1 Hour";
    String timeDev = "2 Hours";
    String[] comboChoices = {"Play Time", "Dev Time"};
    String[] columnNames = {"Activity", "Time Allowed", "Time Left"};
    Object[][] data = {{"Play Time", "1 Hour", timePlay }, {"Dev Time", "2 Hours", timeDev }};
    //This is where the UI stuff is...
    JTable table = new JTable(data, columnNames);
    JScrollPane scrollPane = new JScrollPane(table);
    JPanel mainPanel = new JPanel();
    JComboBox comboBox = new JComboBox(comboChoices);
    JButton start = new JButton("Start");
    JButton stop = new JButton("Stop");



    public ActivTimerFrame() {
        super("Activity Timer");
        setSize(655, 255);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        setResizable(false);
        GridLayout layout = new GridLayout(2,1);
        setLayout(layout);
        add(scrollPane);
        stop.setEnabled(false);
        start.addActionListener(this);
        mainPanel.add(comboBox);
        mainPanel.add(start);
        mainPanel.add(stop);

        add(mainPanel);
    }



    @Override
    public void actionPerformed(ActionEvent evt) {
        Object source = evt.getSource();
        if(source == start) {
            timePlay ="It Works";


        }

    }



}

回答1:


You can do

table.getModel().setValueAt(cellValueObject, rowIndex, colIndex);

to set a particular cell.

in you case for what you are trying, you can do

        timePlay ="It Works";
        table.getModel().setValueAt(timePlay, 0, 1);



回答2:


You need to have your JTable use a TableModel such as an AbstractTableModel or DefaultTableModel and then change the data in the table model when desired. This will then be reflected as changes in the data displayed in the JTable if you also fire the appropriate listener notification method (which is done automatically for you if you use the DefaultTableModel). The Swing tutorial on JTables explains all of this, and if you haven't gone through it, you owe it to yourself to do so.



来源:https://stackoverflow.com/questions/5918727/updating-data-in-a-jtable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!