Updating Data in a JTable
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";
}
}
}
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);
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.
精彩评论