JScrollPane增加了它的大小

时间:2013-07-29 19:27:47

标签: java swing jscrollpane boxlayout

我有一个面板,由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毫米并且不改变其高度。仍然不完美,但看起来我在正确的轨道上。

谢谢大家的帮助!

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:0)

要纠正的两个步骤:

  1. 设置JTextArea的大小:JTextArea text = new JTextArea(row, col);
  2. 仍然向左移动垂直条的大小:
  3. 添加ChangeListener以调整JScrollPane

    的大小
    scroll.getViewport().addChangeListener(new ChangeListener() {
                @Override
                public void stateChanged(ChangeEvent e) {
                    if (scroll.getVerticalScrollBar().isVisible())
                          scroll.setPreferredSize(480, 200);
                    }
                }
    });
    

    或添加scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

相关问题