我的问题是,当我将JTable添加到面板时,所有其他组件都移动到右侧约20%的面板长度,代码为:
JFrame frame = new JFrame("my frame");
JPanel panel = new JPanel();
BoxLayout layout = new BoxLayout(panel, BoxLayout.PAGE_AXIS);
panel.setLayout(layout);
JButton but1 = new JButton("button1");
but1.setAligmentX(0);
panel.add(but1);
String[] columnNames = {"kolumna 1", "kol 2", "kol3"};
JTable itemTable = new JTable(new DefaultTableModel(columnNames, 10));
panel.add(new JScrollPane(itemTable));
JButton but2 = new JButton("button2");
but2.setAligmentX(0);
panel.add(but2);
frame.setContentPane(panel);
frame.setVisible(true);
,结果是
button1
TABLEEEEEEE
TABLEEEEEEE
TABLEEEEEEE
TABLEEEEEEE
button2
而不是
button1
TABLEEEEEE
TABLEEEEEE
TABLEEEEEE
TABLEEEEEE
button2
我做错了什么?
/编辑
我检查了JTextArea是否正常,但是JScrollPane和JTable导致了这个问题,使用带有.setAligment(0)方法的按钮但结果相同
答案 0 :(得分:1)
试试这段代码
JButton b1 = new JButton("button1");
String[] columnNames = { "kolumna 1", "kol 2", "kol3" };
JTable itemTable = new JTable(new DefaultTableModel(columnNames, 10));
JScrollPane scrollPane = new JScrollPane(itemTable);
JButton b2 = new JButton("button2");
b1.setAlignmentX(Component.LEFT_ALIGNMENT);
scrollPane.setAlignmentX(Component.LEFT_ALIGNMENT);
b2.setAlignmentX(Component.LEFT_ALIGNMENT);
JPanel panel = new JPanel();
BoxLayout layout = new BoxLayout(panel, BoxLayout.Y_AXIS);
panel.setLayout(layout);
panel.add(b1);
panel.add(scrollPane);
panel.add(b2);
此处有更多信息:java BoxLayout panel's alignment