【问题标题】:Changing JTextArea to JScrollPane Causes it to not be visible将 JTextArea 更改为 JScrollPane 导致它不可见
【发布时间】:2012-11-07 16:17:58
【问题描述】:

我在使用 JScrollPanes 和 JTextArea 对象并让它们一起工作时遇到问题。

如果我只是将 JTextArea 添加到我的 JPanel,它可以正常工作并显示在我告诉它的位置。但是,如果我将 contentPane.add(textArea) 更改为 contentPane.add(new JScrollPane(textArea)),则 textArea 不再可见,并且也没有 textarea 的迹象。

这是我的代码:

public docToolGUI() {

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 611, 487);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        textField = new JTextField();
        textField.setBounds(253, 323, 86, 20);
        contentPane.add(textField);
        textField.setColumns(10);

        JLabel lblEnterRootDirectory = new JLabel("Enter Root Directory");
        lblEnterRootDirectory.setBounds(253, 293, 127, 20);
        contentPane.add(lblEnterRootDirectory);

        JButton btnGo = new JButton("Go");
        btnGo.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent arg0) {
                new ToolWorker().execute();
            }
        });
        btnGo.setBounds(253, 361, 89, 23);
        contentPane.add(btnGo);

        textArea = new JTextArea();
        textArea.setWrapStyleWord(true);
        textArea.setEditable(false);
        textArea.setBounds(25, 11, 560, 276);
        contentPane.add(new JScrollPane(textArea));




    }

【问题讨论】:

  • 另外,忽略 newToolWorker().execute(),它用于程序的不同部分。
  • 永远不要手动调整尺寸/定位,而是使用合适的 LayoutManager

标签: java swing jframe


【解决方案1】:

尝试使用 JTextArea 的构造函数,它使用 2 个 int 值:

textArea = new JTextArea(rows, columns);

tutorial:

JTextArea 构造函数的两个参数是关于 文本区域应分别具有的行数和列数 展示。包含文本区域的滚动窗格注意 在确定滚动窗格的大小时这些提示。

编辑:上面的示例是对 LayoutManager 的提示,但我只是注意到您没有使用它。除非您有充分的理由不这样做,否则您应该这样做。

【讨论】:

    【解决方案2】:

    这是因为您必须设置 JScrollPane 的边界,并且必须使滚动窗格而不是文本区域可见。

    textArea = new JTextArea();
    textArea.setWrapStyleWord(true);
    textArea.setEditable(false);
    
    JScrollPane scrollPane = new JScrollPane(textArea);
    scrollPane.setBounds(25, 11, 560, 276);
    scrollPane.setVisible(true);
    
    contentPane.add(scrollPane);
    

    【讨论】:

    • do.not.do.any.manual.sizing.positioning。曾经。另外不需要setVisible(组件默认可见)
    • 这有什么问题?这也是为了适合原始帖子而编写的。但是感谢您阻止我以后这样做。
    猜你喜欢
    • 1970-01-01
    • 2017-10-14
    • 2015-04-08
    • 2011-08-26
    • 2012-09-22
    • 2011-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多