JTable 不会显示列标题

我有下面的代码来实例化一个 JTable: 该表提供了正确的行和列数,但是没有标题位于列顶部的迹象。

public Panel1()
{
int  nmbrRows;


setLayout(null);
setBackground(Color.magenta);
Vector colHdrs;


//create column headers


colHdrs = new Vector(10);
colHdrs.addElement(new String("Ticker"));


// more statements like the above to establish all col. titles


nmbrRows = 25;
DefaultTableModel tblModel = new DefaultTableModel(nmbrRows, colHdrs.size());
tblModel.setColumnIdentifiers(colHdrs);


scrTbl = new JTable(tblModel);
scrTbl.setBounds(25, 50, 950, 600);
scrTbl.setBackground(Color.gray);
scrTbl.setRowHeight(23);
add(scrTbl);


//rest of constructor
...


}

与其他表制作代码相比,我没有看到任何遗漏的步骤,但是肯定缺少了一些东西。

124822 次浏览

Put your JTable inside a JScrollPane. Try this:

add(new JScrollPane(scrTbl));

The main difference between this answer and the accepted answer is the use of ABC0 instead of add().

How to put JTable in JScrollPane using Eclipse IDE:

  1. Create JScrollPane container via Design tab.
  2. Stretch JScrollPane to desired size (applies to Absolute Layout).
  3. Drag and drop JTable component on top of JScrollPane (Viewport area).

In Structure > Components, table should be a child of scrollPane. enter image description here

The generated code would be something like this:

JScrollPane scrollPane = new JScrollPane();
...


JTable table = new JTable();
scrollPane.setViewportView(table);

As said in previous answers the 'normal' way is to add it to a JScrollPane, but sometimes you don't want it to scroll (don't ask me when:)). Then you can add the TableHeader yourself. Like this:

JPanel tablePanel = new JPanel(new BorderLayout());
JTable table = new JTable();
tablePanel.add(table, BorderLayout.CENTER);
tablePanel.add(table.getTableHeader(), BorderLayout.NORTH);
    public table2() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 485, 218);
setTitle("jtable");
getContentPane().setLayout(null);


String data[][] = { { "Row1/1", "Row1/2", "Row1/3" },
{ "Row2/1", "Row2/2", "Row2/3" },
{ "Row3/1", "Row3/2", "Row3/3" },
{ "Row4/1", "Row4/2", "Row4/3" }, };


String header[] = { "Column 1", "Column 2", "Column 3" };


// Table
JTable table = new JTable(data,header);




// ScrollPane
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBounds(36, 37, 407, 79);
getContentPane().add(scrollPane);


}

}

try this!!