Swing: can't seem to get JTable to show properly
The following code shows a bug I'm trying to fix. I have two ways of 开发者_如何学运维displaying a table (hierarchy below):
JTable directly in a JOptionPane: shows the table fine.
JOptionPane JTable
JTable in a scrollpane in a JPanel in a JOptionPane: can't seem to show the table.
JOptionPane JPanel JScrollPane JTable
Since it's the same function to create the table, I'm fairly positive that I'm just doing something wrong w/r/t sizing/layout. Any suggestions?
import java.awt.Dimension;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
public class TableTest2 {
public static void testTable(JTable t) {
t.setModel(new AbstractTableModel() {
public String getColumnName(int col) { return "col"+Integer.toString(col); }
public int getRowCount() { return 4; }
public int getColumnCount() { return 4; }
public Object getValueAt(int row, int col) {
return Integer.toString(row*col);
}
public boolean isCellEditable(int row, int col) { return false; }
public void setValueAt(Object value, int row, int col) { }
});
}
public static void main(String[] args) {
doTest1();
doTest2(null, null);
doTest2(new Dimension(500,500), null);
doTest2(new Dimension(500,500), new Dimension(400,400));
}
private static void doTest1() {
JTable t = new JTable();
t.setPreferredSize(new Dimension(500,500));
TableTest2.testTable(t);
JOptionPane.showMessageDialog(null, t, "test1", JOptionPane.INFORMATION_MESSAGE);
}
private static void doTest2(Dimension d1, Dimension d2) {
JTable t = new JTable();
TableTest2.testTable(t);
JPanel panel = new JPanel();
JScrollPane sp = new JScrollPane();
sp.add(t);
if (d1 != null)
sp.setPreferredSize(d1);
panel.add(sp);
if (d2 != null)
panel.setPreferredSize(d2);
JOptionPane.showMessageDialog(null, panel, "test2", JOptionPane.INFORMATION_MESSAGE);
}
}
Try this:
JScrollPane sp = new JScrollPane(t);
providing the component for the scrollpane in the constructor.
You do not add components to the scrollpane. You can set a viewport lik ethis:
sp.getViewPort().setView(t);
rather than
sp.add(t);
精彩评论