JScrollPane滚动可见但不起作用

时间:2014-02-22 23:25:10

标签: java swing scroll

你能告诉我为什么滚动不起作用。它是可见的,但它不起作用, 在这里你可以查看那段代码。可能缺少的部分是什么?

// GUI elements
private JTextField textSend = new JTextField(20);
private JTextArea textArea = new JTextArea(5, 20);

private JScrollPane scroll = new JScrollPane(textArea);

private JButton buttonConnect = new JButton("Connect");
private JButton buttonSend = new JButton("Send");
private JButton buttonDisconnect = new JButton("Disconnect");
private JButton buttonQuit = new JButton("Quit");

private JPanel leftPanel = new JPanel();
private JPanel rightPanel = new JPanel();

private JLabel empty = new JLabel("");

ChessHeroChatClient() {
    setTitle("ChessHero Chat Client");
    setLocationRelativeTo(null);
    setSize(500, 500);
    setResizable(false);

    leftPanel.setLayout(new BorderLayout());
    rightPanel.setLayout(new GridLayout(6, 1));

    scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

    leftPanel.add(textSend, BorderLayout.NORTH);
    leftPanel.add(textArea, BorderLayout.WEST);
    leftPanel.add(scroll, BorderLayout.EAST);

    add(leftPanel, BorderLayout.CENTER);
    add(rightPanel, BorderLayout.EAST);

    textArea.setEditable(false);

1 个答案:

答案 0 :(得分:4)

private JTextArea textArea = new JTextArea(5, 20);
private JScrollPane scroll = new JScrollPane(textArea);

使用textArea创建scrollPane,这是好的。

//leftPanel.add(textArea, BorderLayout.WEST); // this is wrong
leftPanel.add(scroll, BorderLayout.EAST);

但是你将textArea添加到WEST并滚动到EAST,这是错误的。 Swing组件只能有一个父组件,因此只需单独保留textArea并将scrollPane添加到EAST或WEST。