使用Java Swing将滚动条添加到JTextArea中

时间:2016-02-27 01:14:21

标签: java swing scrollbar jscrollpane jtextarea

我已经看过几个关于这个主题的帖子,但我无法用那里提供的信息解决问题。我尝试使用以下代码将滚动条(垂直和水平)添加到JTextArea中,如下所示:

public FPrincipale() {

        JFrame wframe = new JFrame();

        JPanel wpanel = new JPanel(new BorderLayout());
        JPanel tpanel = new JPanel();
        JPanel bpanel = new JPanel(new FlowLayout(FlowLayout.CENTER));

        textzone = new JTextArea(" ",20, 50);
        textzone.setLineWrap(true);
        textzone.setWrapStyleWord(true);

        //Here I try to add the scroll bar
        JScrollPane wscroll = new JScrollPane(textzone, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        wscroll.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
        wscroll.setBorder(BorderFactory.createLineBorder(Color.black));
        wframe.add(wscroll);
        wframe.setVisible(true);

        JButton b1 = new JButton("B1");
        JButton b2 = new JButton("B2");
        JButton b3 = new JButton("Close");      

        bpanel.add(b1);
        bpanel.add(b2);     
        bpanel.add(b3);     
        bpanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));

        tpanel.add(textzone);
        tpanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
        tpanel.add(wscroll, BorderLayout.CENTER);

        wpanel.add(bpanel, BorderLayout.SOUTH);
        wpanel.add(tpanel, BorderLayout.CENTER);

        wframe.setLocation(150, 100);
        wframe.setPreferredSize(new Dimension(640, 480));

        b1.addActionListener(new b1Listener());
        b2.addActionListener(new b2Listener());
        b3.addActionListener(new b3Listener());

        this.getContentPane().setPreferredSize(new Dimension(500,500));     

        wframe.add(wpanel);
        wframe.setVisible(true);
        wframe.setSize(640, 640);
        wframe.setDefaultCloseOperation(EXIT_ON_CLOSE);
        wframe.setTitle("Main Window");
        pack();

    }

然而,当创建窗口时,即使我缩小窗口的大小,滚动条也不起作用:

正常窗口:

enter image description here

缩小尺寸:

enter image description here

如何解决此问题?

1 个答案:

答案 0 :(得分:1)

首先将课程移除到setPreferredSize,这会让你感到困惑。在您的代码中稍后,您正在调用tpanel.add(textzone);,即从JTextArea移除JScrollPane并将其添加到tpanel(然后添加JScrollPane它很好,这就是为什么你旁边有一个小方块。)

首先将BorderLayout应用于tpanel

JPanel tpanel = new JPanel(new BorderLayout());

删除将滚动窗格添加到框架中的行...

//wFrame.add(wscroll);

然后只将JScrollPane添加到tpanel

//tpanel.add(textzone);
tpanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
tpanel.add(wscroll, BorderLayout.CENTER);