Reputation: 379
I have a table which has only field names and no data, I want to enter data from inputs by the user, how do I do that?
My actual program is too long, so this is a mini program i wrote to post here.
Example of things i want to add into the table is this: {"men's clothings","RM 5",input,total}
input is from the first button, total is from my setter getter file in my actual program
I wanted to use a List but it seems that it is uncompatible with my Object[][] order.
What i want to achieve is generating an order list after user choosing the items from the buttons.
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;
}
}
Upvotes: 0
Views: 2258
Reputation: 324197
You should be creating your table as follows:
DefaultTableModel model = new DefaultTableModel(title, 0);
JTable table = new JTable( model );
This will create a table with just the heading and 0 rows of data.
Then when you want to add a new row of data you would use:
model.addRow(...);
You can add data to the DefaultTableModel as a Vector or an Array.
If you want to use a List then you need to use a custom TableModel model. You can check out the List Table Model.
Upvotes: 3