更新JTable中的数据

And*_*llo 2 java swing jtable

可以说我有一张桌子.其中一个细胞拥有一个JLabel.如果我更改文本,JLabel我该如何JTable显示更改?看下面的代码,我应该更改什么才能让它显示更改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";


        }

    }



}
Run Code Online (Sandbox Code Playgroud)

Bal*_*a R 7

你可以做

table.getModel().setValueAt(cellValueObject, rowIndex, colIndex);
Run Code Online (Sandbox Code Playgroud)

设置特定的单元格.

在你的情况下你正在尝试,你可以做

        timePlay ="It Works";
        table.getModel().setValueAt(timePlay, 0, 1);
Run Code Online (Sandbox Code Playgroud)


Hov*_*els 5

您需要让 JTable 使用 TableModel(例如 AbstractTableModel 或 DefaultTableModel),然后在需要时更改表模型中的数据。如果您还触发了适当的侦听器通知方法(如果您使用 DefaultTableModel,则会自动完成),这将反映为 JTable 中显示的数据的更改。 JTables 上的 Swing 教程解释了所有这些内容,如果您还没有阅读过它,那么您应该自己阅读一下。