【发布时间】:2013-07-29 19:27:46
【问题描述】:
我有一个面板,它被BoxLayout.X_AXIS 分为两部分:
public TabsPanel() {
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
add(createLeftPanel());
add(createRightPanel());
}
每个左右面板的结构如下:一个外面板有BorderLayout,一个内面板在外面板的BorderLayout.CENTER中,而内面板又是BoxLayout.Y_AXIS和从上到下的几个组件。右侧面板具有 JTextArea 和 JScrollPane 作为其组件之一:
protected JPanel createRightPanel() {
JPanel pane = new JPanel();
pane.setLayout(new BorderLayout());
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
JTextArea label = createLabel();
JScrollPane scroll = new JScrollPane(label);
scroll.setMaximumSize(new Dimension(500, 200));
panel.add(Box.createRigidArea(new Dimension(0,106)));
panel.add(scroll);
JPanel panel_buttons = new JPanel();
panel_buttons.setLayout(new BoxLayout(panel_buttons, BoxLayout.LINE_AXIS));
panel_buttons.setAlignmentX(Component.CENTER_ALIGNMENT);
Font font_text = new Font("Georgia", Font.PLAIN, 20);
JButton[] buttons = new JButton[2];
buttons[0] = new JButton("Clear");
buttons[1] = new JButton("Exit");
for (int i = 0; i < buttons.length; i++) {
buttons[i].setMaximumSize(new Dimension(120, 40));
buttons[i].setFont(font_text);
panel_buttons.add(buttons[i]);
if (i == 0)
panel_buttons.add(Box.createRigidArea(new Dimension(40, 0)));
buttons[i].addActionListener(new TextActionListener(label));
}
panel.add(Box.createRigidArea(new Dimension(0,20)));
panel.add(panel_buttons);
pane.add(panel, BorderLayout.CENTER);
return pane;
}
当文本超出边界时,会出现滚动条,我可以移动它们并阅读文本。看起来一切正常,但是当我单击滚动窗格外的任何位置甚至只是移动指针时,滚动窗格会向左移动并向下增长。它不会改变它的宽度,但它会向左移动,因为它和右面板边界之间的区域增加了。因此,左侧面板的尺寸缩小。当我清除文本区域并再次单击或移动指针时,它会恢复到正常大小。
它的高度增加,左右边距增加的原因是什么?我做错了什么?
更新。我发现了问题。问题是我没有正确创建JTextArea。我在没有参数的情况下初始化了它:
JTextArea text = new JTextArea("Some initial text");
现在我重写了:
JTextArea text = new JTextArea(5,10);
现在它向左移动了大约 5 毫米,并且不改变其高度。仍然不完美,但看起来我在正确的轨道上。
感谢大家的帮助!
【问题讨论】:
-
在将文本添加到 JTextArea 后调用 pack()/layout() 时,我遇到了同样的问题。你也这样做吗?
标签: java swing jscrollpane boxlayout