有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为JTable向数组添加项

我有一个表,只有字段名,没有数据, 我想输入用户输入的数据,我该怎么做

我的实际程序太长了,所以 这是我写在这里发布的一个小程序

我想添加到表中的示例如下: {“男装”、“5 RM”,输入,总计}

输入来自第一个按钮,总计来自实际程序中的setter-getter文件

我想使用列表,但它似乎与我的对象[]顺序不兼容

我想要实现的是在用户从按钮中选择项目后生成订单列表

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;

    class test implements ActionListener
    {
private Object[][]order={   };  // I need to add data here in order to put 
                                         //in the JTable

private JFrame f;               // for 1st frame with the buttons
private JTable table;
private JScrollPane pane;
private JButton button1;    
private JFrame f2;              //pop up window after button2 
private JButton button2;
private String input;           //input when press button1

    public test()
    {

    button1=new JButton("press here first");
    button2=new JButton("press here after above");

    //first frame config

    f=new JFrame();
    f.setSize(500,500);
    f.setVisible(true);
    f.setLayout(new GridLayout(2,0));
    f.add(button1);
    f.add(button2);


    button1.addActionListener(this);
    button2.addActionListener(this);
     }

    public static void main(String args[])
{
test lo=new test(); 
}


public void actionPerformed(ActionEvent e)
    {

  if(e.getSource()==button1)    // for the first button
        {
    input=JOptionPane.showInputDialog(null,"how many do you want?");
            //user input on the quantity
        }

  if(e.getSource()==button2)
     {
    window2();
     }

    } 


public JFrame window2()         //second window config
     {
    String[] title={"item","Price","Qty","total"};
    table=new JTable(order,title);
    pane=new JScrollPane(table);

    f2=new JFrame();
    f2.setSize(500,500);
    f2.setVisible(true);
    f2.setLayout(new FlowLayout());
    f2.add(pane);
    f2.pack();

    return f2;
     }

    }

共 (1) 个答案

  1. # 1 楼答案

    您应该按如下方式创建表:

    DefaultTableModel model = new DefaultTableModel(title, 0);
    JTable table = new JTable( model );
    

    这将创建一个只包含标题和0行数据的表

    然后,当您想要添加一行新数据时,您将使用:

    model.addRow(...);
    

    可以将数据作为向量或数组添加到DefaultTableModel

    如果要使用列表,则需要使用自定义表格模型。你可以查看List Table Model