我正在尝试将jtable组件添加到我的jPanel,但我无法看到它。我究竟做错了什么?。
table gui = new table(data,colum);
mainPanel.add(gui.table);
class table extends JFrame
{
public JTable table;
public table(Vector data, Vector colum)
{
setLayout(new FlowLayout());
table = new JTable(data,colum);
table.setPreferredScrollableViewportSize(new Dimension(900,10));
table.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
}
}
答案 0 :(得分:1)
扩展JFrame似乎很奇怪;您不使用任何顶级容器功能。这是一个扩展JPanel的示例,其中main()将面板放入JFrame。
- 已修改为接受现有的JPanel
public class TablePanel
{
public static void addTableToPanel(JPanel jPanel, Vector rowData, Vector columnNames)
{
JTable jTable = new JTable(rowData, columnNames);
jTable.setFillsViewportHeight(true);
JScrollPane jScrollPane = new JScrollPane(jTable);
jScrollPane.setPreferredSize(new Dimension(300, 50));
jPanel.add(jScrollPane);
}
public static void main(String[] args) throws Exception
{
SwingUtilities.invokeAndWait(new Runnable()
{
@Override
public void run()
{
Vector cols = new Vector();
Vector rows = new Vector();
Vector row1 = new Vector();
cols.add("A");
cols.add("B");
cols.add("C");
row1.add("1");
row1.add("2");
row1.add("3");
rows.add(row1);
rows.add(row1.clone());
rows.add(row1.clone());
rows.add(row1.clone());
JFrame frame = new JFrame("TableTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel jPanel = new JPanel();
jPanel.setLayout(new BorderLayout(0, 0));
TablePanel.addTableToPanel(jPanel, rows, cols);
frame.getContentPane().add(jPanel);
frame.pack();
frame.setVisible(true);
}
});
}
}