0
所以我想要做的是按下按鈕時更新JTable。我使用DefaultTableModel作爲源。 表類:從DefaultTableModel更新JTable
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import java.awt.Dimension;
public class TableDemo extends JPanel {
String[] columnNames = {"Tipo","Cantidad"};
DefaultTableModel dtm = new DefaultTableModel(null,columnNames);
final JTable table = new JTable(dtm);
public TableDemo() {
table.setPreferredScrollableViewportSize(new Dimension(500, 700));
table.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
}
public void addRow(Object [] row)
{
dtm.addRow(row);
}
}
窗體類:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
public class MyForm extends JFrame {
JPanel panel;
JLabel label;
JTextField txtName;
JTextField txtSurname;
JButton btnAccept;
TableDemo tb = new TableDemo();
public MyForm(){
initControls();
}
private void initControls() {
setTitle("Form Example");
setSize(600, 400);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
panel = new JPanel();
panel.setLayout(null);
label = new JLabel("Welcome to Swing");
label.setBounds(50, 10, 200, 30);
txtName = new JTextField();
txtName.setBounds(50, 50, 200, 30);
txtSurname = new JTextField();
txtSurname.setBounds(270, 50, 200, 30);
btnAccept = new JButton("Add");
btnAccept.setBounds(120, 100, 150, 30);
onAcceptClick();
TableDemo tablePanel = new TableDemo();
panel.add(label);
panel.add(txtName);
panel.add(txtSurname);
panel.add(btnAccept);
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
tablePanel,panel);
splitPane.setDividerLocation(205);
splitPane.setEnabled(false);
getContentPane().add(splitPane);
}
private void onAcceptClick() {
btnAccept.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
tb.addRow(new Object[]{"taza",txtName.getText()});
}
});
public static void main(String[] args) {
//Initilizer init = new Initilizer();
Runnable init = new Runnable() {
@Override
public void run() {
MyForm form = new MyForm();
form.setVisible(true);
}
};
SwingUtilities.invokeLater(init);
}
}
正如你可以看到我所說的addRow功能,但從來沒有在JTable更新,我失去了什麼? Thnx