I'm practicing with JTables and I'm looking at the documentation as well for JTables at Oracle's J 7's library. What I'm working on is getting user input and display it in a JTable, simple.
My code currently is:
public class tablePractice {
JFrame frame=new JFrame("Table Test");
JPanel panel=new JPanel(new FlowLayout(FlowLayout.CENTER));
JLabel username=new JLabel("Username: ");
JTextField nameField=new JTextField(10);
JButton add=new JButton("Add");
JTable table=new JTable();
JScrollPane scrollPane=new JScrollPane();
DefaultTableModel model=new DefaultTableModel();
ArrayList<String> list=new ArrayList<String>();
public void setInterface() {
frame.setSize(300,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(panel);
panel.add(username);
panel.add(nameField);
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource()==add) {
list.add(nameField.getText());
model.addRow(list.toArray());
System.out.println(list);
}
}
});
panel.add(add);
table.setModel(model);
table.add(scrollPane);
panel.add(table);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
public static void main(String[] args) {
tablePractice run=new tablePractice();
run.setInterface();
}
}
And the list is printed on the console but I have no JTable present. Am I missing something?
CodePudding user response:
The JTable
needs to be contained within the scrollpane
scrollPane.setViewportView(table);
// table.add(scrollPane); don't do this
panel.add(scrollPane);
Also you need to define the columns for your model. E.g.
model.addColumn("Name");
then add a row
// model.addRow(list.toArray()); varible-length row - don't do this
model.addRow(new Object[] { nameField.getText() });
CodePudding user response:
You want to display it? Then you just need to create a new Label with your input text and add this label to your panel.
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource()==add) {
model.addRow(list.toArray());
JLabel text = new JLabel(nameField.getText());
panel.add(text);
}
}
});```