Hi,
I have a class which extends the frame and has "JTabbedPane" and "JTable" added to it. Look at the following code:
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
JTabbedPane jtp = new JTabbedPane();
jtp.addTab("Songs", new SongsPanel());
contentPane.add(jtp, BorderLayout.NORTH);
DefaultTableModel dtm = new DefaultTableModel();
table = new JTable();
table.setModel(dtm);
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane
jsp = new JScrollPane(table, v, h);
contentPane.add(jsp, BorderLayout.CENTER);
pack();
In the JTabbedPane I have two buttons. When I click on one button it has to show the "JTable". But it is not showing. The action is performing only when I resize the window manually. And if I resize it manually some how my BorderLayout is changing to FlowLayout. Here is the code for the JTabbedPane
JTable table = new JTable();
public SongsPanel() {
super();
JButton b1 = new JButton("View Songs");
b1.setActionCommand("view");
b1.addActionListener(this);
JButton b2 = new JButton("All Songs");
b2.setActionCommand("all");
b2.addActionListener(this);
add(b1);
add(b2);
}
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("view")) {
DefaultTableModel d1 = (DefaultTableModel) table.getModel();
for(int i=0;i<d1.getRowCount();i++) {>
d1.removeRow(i);
}
final
String[] colLabel = {"Name", "Artist"};
final String[][] data = {
{"Come on", "Madonna"},
{"Quit Playing games", "Back Street Boys"}
};
DefaultTableModel dataModel = new DefaultTableModel(data, colLabel);
table.setModel(dataModel);
table.setShowGrid(false);
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(table, v, h);
add(jsp, BorderLayout.CENTER);
} else if(e.getActionCommand().equals("all")) {
DefaultTableModel d1 = (DefaultTableModel) table.getModel();
for(int i=0;i<d1.getRowCount();i++) {>
d1.removeRow(i);
}
System.out.println(e.getActionCommand());
final String[] colLabel = {"Name", "Artist"};
final String[][] data = {
{"Come on ALL", "ALL Madonna"},
{"ALL Quit Playing games", "ALL Back Street Boys"}
};
DefaultTableModel dataModel = new DefaultTableModel(data,colLabel);
table.setModel(dataModel);
table.setShowGrid(false);
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(table, v, h);
add(jsp, BorderLayout.CENTER);
}
table.revalidate();
table.repaint();
}
}
Please let me know if I am making any mistakes. I am new to swing API and any suggestions regarding the use of swing components are welcome.
Thanks in advance.