Java 如何通过单击按钮添加具有行和列的新JTable?

Java 如何通过单击按钮添加具有行和列的新JTable?,java,swing,jtable,Java,Swing,Jtable,我是Java初学者,需要帮助 单击按钮时,我想在JFrame或JPanel中添加具有行和列的表。如何通过单击按钮添加包含行和列的新表 首先,您必须将JButton添加到框架中 然后在按钮中添加ActionListener 而不是像这样按下按钮时列出一个列表 JButton b = new JButton("Click Me"); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent

我是Java初学者,需要帮助

单击按钮时,我想在
JFrame
JPanel
中添加具有行和列的表。如何通过单击按钮添加包含行和列的新表

  • 首先,您必须将
    JButton
    添加到框架中
  • 然后在按钮中添加
    ActionListener
  • 而不是像这样按下按钮时列出一个列表

    JButton b = new JButton("Click Me");
    b.addActionListener(new ActionListener() {
    
    public void actionPerformed(ActionEvent e) {
    
    String[] columnNames = {"First Name",
                "Last Name",
                "Sport",
                "# of Years",
                "Vegetarian"};
    
    Object[][] data = {
                {"Kathy", "Smith",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"John", "Doe",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Sue", "Black",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Jane", "White",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Joe", "Brown",
                 "Pool", new Integer(10), new Boolean(false)}
            };
    
        JTable table = new JTable(data, columnNames);
        add(table);
    
    }
    });
    

  • 有关&.

    到目前为止您做了什么的更多信息..共享您的代码在构建主GUI时(在单击按钮之前),添加空表是一种更常见(且更不容易出错)的方法。单击按钮时,要么将数据添加到
    表格模型
    ,要么创建一个新的表格模型(添加数据)并将其设置到表格中。我“认为”他们希望能够更改表格的内容或动态添加内容