简体   繁体   English

如何在 Java Swing 中将 ScrollBar 添加到 JTextArea?

[英]How can I add ScrollBar to JTextArea in Java Swing?

Anyone help me how to add a scroll bar to a JTextArea with Swing in Java?任何人都可以帮助我如何在 Java 中使用 Swing 向JTextArea添加滚动条?

The JTextArea just disappear when I add the scroll bar on it.当我在其上添加滚动条时, JTextArea消失。

Hope somebody get me add a vertical scrollbar on it.希望有人让我在上面添加一个垂直滚动条。

Additional explanation will be very thankful额外的解释将非常感谢

public class Practice extends JFrame {
    JFrame frame = new JFrame("AAA");

    JTextArea textarea = new JTextArea();
    JScrollPane scroll = new JScrollPane(textarea);
    JPanel panelForScroll = new JPanel(null);

    public Practice(){
        frame.setLayout(null);
        frame.setBounds(100,100,400,710);
        frame.setResizable(false);
        frame.setVisible(true);

        textarea.setEditable(false);
        textarea.setFont(new Font("arian", Font.BOLD, 16));
        textarea.setBounds(20, 280, 340, 70);

        panelForScroll.add(scroll);
        frame.add(panelForScroll); //can't find text area....
    }

    public static void main(String[] args) {
        new Practice();
    }
}

There are several errors in your code:您的代码中有几个错误:

  1. You're using a null layout, this is discouraged as it produces more problems than solutions, specially when you try to use JScrollPanes , since they take the preferredSize of the Component to decide whether to add the scroll bars or not.您使用的是null布局,这是不鼓励的,因为它会产生比解决方案更多的问题,特别是当您尝试使用JScrollPanes ,因为它们采用ComponentpreferredSize来决定是否添加滚动条。 See Why is it frowned upon to use a null layout in Swing?请参阅为什么不赞成在 Swing 中使用空布局? for more information about this.有关这方面的更多信息。 To fix this, remove this line:要解决此问题,请删除此行:

     frame.setLayout(null);

    And instead use a layout manager or combinations of them along with borders for extra spacing between components.而是使用布局管理器或它们的组合以及边框来增加组件之间的间距

    While null layouts might seem like the best, easiest and faster way to design complex GUIs for Swing newbies, the more you progress in it, the more problems related to the use of them you'll find (as it's the case)虽然null布局似乎是为 Swing 新手设计复杂 GUI 的最佳、最简单和更快的方法,但您在其中取得的进展越多,您会发现与使用它们相关的问题越多(实际情况就是如此)

  2. You're extending your class from JFrame and you're creating an instance of JFrame in it too, please use one or the other.您正在从JFrame扩展您的类,并且您也在其中创建JFrame一个实例,请使用其中一个。 When you extend JFrame you're saying your class is a JFrame and thus it cannot be placed inside another Container because JFrame is a rigid container.当您扩展JFrame您是说您的类是一个JFrame ,因此它不能放置在另一个Container因为JFrame是一个刚性容器。 I recommend to forget the extends JFrame part, since anyway you're not using the JFrame that is generated by this action and stay with the object you created.我建议忘记extends JFrame部分,因为无论如何您都没有使用此操作生成的JFrame并保留您创建的对象。 See https://stackoverflow.com/questions/41252329/java-swing-using-extends-jframe-vs-calling-it-inside-of-class for a more detailed answer about this problem.有关此问题的更详细答案,请参阅https://stackoverflow.com/questions/41252329/java-swing-using-extends-jframe-vs-calling-it-inside-of-class

  3. You're making your GUI visible before you have added all the elements, this could cause your GUI to not display all the elements until you hover over them, this line:您在添加所有元素之前使 GUI 可见,这可能会导致您的 GUI 不显示所有元素,直到您将鼠标悬停在它们上面,这一行:

     frame.setVisible(true);

    Should be one of the last lines in your program应该是程序中的最后一行之一

  4. You're not placing your program on the Event Dispatch Thread (EDT) which makes your application to not be thread safe, you can fix it by writing this on your main method.您没有将程序放在事件调度线程 (EDT) 上,这会使您的应用程序不是线程安全的,您可以通过在main方法上编写它来修复它。

     SwingUtilities.invokeLater(new Runnable() { @Override public void run() { //Place your constructor here } });
  5. You're setting bounds for the textArea but not for the scrollPane , but you should really not be setting the bounds manually (see point #1 again).您正在为textArea而不是为scrollPane设置边界,但您真的不应该手动设置边界(再次参见第 1 点)。


Now, you can make a simple GUI with a JTextArea with a JScrollPane as follows:现在,您可以使用JTextAreaJScrollPane制作一个简单的 GUI,如下所示:

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class ScrollPaneToTextArea {

    private JTextArea textArea;
    private JFrame frame;
    private JScrollPane scroll;
    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new ScrollPaneToTextArea().createAndShowGui();
            }
        });
    }
    
    public void createAndShowGui() {
        frame = new JFrame("ScrollPane to TextArea");
        textArea = new JTextArea(10, 20); //Rows and cols to be displayed
        scroll = new JScrollPane(textArea);
//      scroll = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        
        frame.add(scroll); //We add the scroll, since the scroll already contains the textArea
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

Which produces this output and the scroll bars are added when needed (ie when text goes further than the rows it can handle in the view)产生此输出并在需要时添加滚动条(即当文本比它可以在视图中处理的行更远时)

在此处输入图片说明 在此处输入图片说明

If you want the vertical scroll bars to appear always you can uncomment the line:如果您希望始终显示垂直滚动条,您可以取消注释该行:

scroll = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

Which will produce the following outputs:这将产生以下输出:

在此处输入图片说明 在此处输入图片说明

You can read more about JScrollPane in the docs and JTextArea also in their own docs .您可以在文档中阅读更多关于JScrollPaneJTextArea也可以在他们自己的文档中阅读JTextArea

 JPanel panelForScroll = new JPanel(null);

This sets the NULL Layout to this JPanel.这将NULL 布局设置为此 JPanel。 This would require more configuration (just as you did for the frame object).这将需要更多配置(就像您对框架对象所做的那样)。

Just remove the null (also from frame.setLayout(null) !)只需删除null (也从frame.setLayout(null) !)

You have to use Jtextpane to get the scroll bar on textarea.您必须使用 Jtextpane 来获取 textarea 上的滚动条。

JTextArea ta = new JTextArea();
JScrollPane sp = new JScrollPane(ta); 
JFrame f = new JFrame();
f.getContentPane().add(sp);

you are setting the panel's layout to null,then you didn't specify the scroll bar bounds.您将面板的布局设置为 null,然后您没有指定滚动条边界。 Since you only have one component in your panel which is the scroll bar I recommend using FlowLayout由于您的面板中只有一个组件,即滚动条,我建议您使用 FlowLayout

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM