我看过并发现很多人没有将他们的表格放入 scrollPane 中。即使我将表格嵌套到 scrollPane 中,然后嵌套到框架中,它仍然无法显示标题。还有什么我想念的吗?谢谢
public class Gui extends JFrame {
AbstractTableModel model;
JTable table;
public void start(AbstractTableModel model) {
this.model = model;
table=new JTable(model){
@Override
public boolean isCellEditable(int arg0, int arg1) {
return false;
}
};
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
TableColumn column = null;
for (int i = 0; i < model.getColumnCount(); i++) {
column = table.getColumnModel().getColumn(i);
column.setPreferredWidth(120);
column.setMaxWidth(300);
column.setMinWidth(50);
}
JScrollPane pane = new JScrollPane(table);
pane.setPreferredSize(new Dimension(900,900));
add(pane);
setLayout(new FlowLayout());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
}
最佳答案
根据您的代码,然后必须添加缺少的功能,您的代码可以工作...
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
public class Gui extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
Gui frame = new Gui();
frame.start(new DefaultTableModel(new Object[]{"A", "B", "C"}, 10));
}
});
}
AbstractTableModel model;
JTable table;
public void start(AbstractTableModel model) {
this.model = model;
table = new JTable(model) {
@Override
public boolean isCellEditable(int arg0, int arg1) {
return false;
}
};
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
TableColumn column = null;
for (int i = 0; i < model.getColumnCount(); i++) {
column = table.getColumnModel().getColumn(i);
column.setPreferredWidth(120);
column.setMaxWidth(300);
column.setMinWidth(50);
}
JScrollPane pane = new JScrollPane(table);
pane.setPreferredSize(new Dimension(900, 900));
add(pane);
setLayout(new FlowLayout());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
}
}
然后这导致了两个广泛的假设......
- 您的
TableModel
没有任何列 - 您的
TableModel
没有任何列名...
例如,一个没有列名的 TableModel
...
个人...
- 我不会为此使用
FlowLayout
,BorderLayout
会给出更好的结果 在使其可见之前打包
框架- 在添加组件之前设置布局,因为有时候,事情会变得一团糟...
例如……
setLayout(new FlowLayout()); // But I'd use a `BorderLayout`
add(pane);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
关于java - JTable 标题仍未显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23945921/