我的问题是,当我将 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) 方法的按钮,但结果相同
试试这段代码
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面板的对齐方式