我正在尝试将JTable添加到框架中,但没有用,我曾尝试过:
public Jtablee()
{
setSize(400,400);
String[] columnsNames = {"firstName", "LastName", "sport", "# ofYear", "vegetarian"};
Object[][] data = {{"Katty", "Smith", "SnowBoard", new Integer(5), new Boolean(false)}, {"Jhon", "Doe", "Rowing", new Integer(3), new Boolean(true)},
{"Sue", "Black", "Knitting", new Integer(2), new Boolean(false)},{"Jane", "White", "Speed ride", new Integer(20), new Boolean(true)}};
JTable t = new JTable(data, columnsNames);
add(t.getTableHeader(), BorderLayout.PAGE_START);
add(t, BorderLayout.CENTER);
setLayout(new BorderLayout());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
只显示空白框,没有JTable
注意:我不想将它添加到scrollPane中,我想直接添加它。
答案 0 :(得分:1)
由于内容窗格setLayout(new BorderLayout())
已具有该布局,因此您无需致电Container
。在添加组件后调用会使它们消失。
您也无需致电setSize()
上的JFrame
。相反,你应该调用pack()
,它会自动调整大小以适应其内容(表格)
最后你不应该在这里使用new Integer()
和new Boolean()
因为它是不必要的装箱,而是使用原语。
所以你的代码应该是这样的:
import javax.swing.*;
import java.awt.*;
public class Test extends JFrame {
public Test() {
String[] columnsNames = {"firstName", "LastName", "sport", "# ofYear", "vegetarian"};
Object[][] data = {
{"Katty", "Smith", "SnowBoard", 5, false},
{"Jhon", "Doe", "Rowing", 3, true},
{"Sue", "Black", "Knitting", 2, false},
{"Jane", "White", "Speed ride", 20, true}
};
JTable table = new JTable(data, columnsNames);
add(table.getTableHeader(), BorderLayout.PAGE_START);
add(table, BorderLayout.CENTER);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new Test();
}
}
答案 1 :(得分:0)
只有让你看到你的JTable才能做的事情就是删除导致你的代码冲突的"setLayout(BorderLayout.CENTER)",
因素(它正在重写之前创建的BorderLayout)。
答案 2 :(得分:0)
我想在这里展示我的示例以添加一个简单的 使用JScrollPane将表插入JFrame,并且用户无法对表头进行重新排序。
import java.awt.*;
import javax.swing.*;
public class addTable extends JFrame{
JTable table;
public addTable(){
setLayout(new FlowLayout());
String [] columnNames = {
"First name", "Last name", "Header"};
Object [][] data = { "Bill", "George", "Male"},
{"Marry", "Anna", "Female"}, {"Rick",
"Bernard", "Male"};
table = new JTable(data, columnNames);
table.setPreferredScrollableViewportSize(
new Dimonsions(650, 75) );
table.setFillsViewportHeight(true);
JScrollPane scrollPane = new
JScrollPane(table);
add(scrollPane);
}
public static void main(String args[]){
addTable t = new addTable();
t.setDefaultCloseOperation(JFrame.EXIT_ON
_CLOSE);
t.setSize(800, 400);
t.setTitle("My Table");
t.getTableHeader().
setReorderingAllowed(false);
t.setLocationRelativeTo(null);
t.setVisible(true);
}
}