繁体   English   中英

在更改JFrame的大小时,在GridLayout中添加ScrollPane不会在JPane中调整JTextarea的大小

[英]adding a ScrollPane in a GridLayout doesn't resizes the JTextarea in a JPane when changing size of JFrame

我想用一个填充的JTextArea组件向当前的GridLayout添加一个网格。 它工作正常,但正如标题中所提到的,JTextArea在更改框架大小后不会自行调整大小。

我已经对错误进行了本地化:

text.setLineWrap(true); //<--- here is the problem!!enter code here

在createGui方法中。

这是我的代码:

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
class GridLayoutExample {

    private JFrame frame = new JFrame();
    private JPanel panel = new JPanel();
    private JScrollPane pane;
    final JTextArea text = new JTextArea("Click me!\nClick me!\nClick me!\nClick me!\nClick me!");

    GridLayoutExample() { createGui(); } //constrcutor

    private JPanel createGui () {
        panel.setLayout(new GridLayout(0, 2,0,0));          
        panel.add( new JLabel("Hello"));        
        //set style of first row, second column
        text.setLineWrap(true); //<--- here is the problem!!
        text.setEditable(true);
        //enable mouse listening and allow mouse action 
        doMouseActions();
        panel.add(text);
        return panel;
    }

    void addNewRow() {
        panel.add(new JLabel("Test1"));
        panel.add(new JTextField("Test"));
    }//addNewRow

    void showFrame() {
        pane = new JScrollPane(panel);
        frame.add(pane);
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }//showframe

    void doMouseActions() {
        text.addMouseListener(new MouseListener() {

            @Override
            public void mouseClicked(MouseEvent arg0) {
                addNewRow();
            }

            @Override
            public void mouseEntered(MouseEvent arg0) {
                text.setBackground(Color.YELLOW);               
            }

            @Override
            public void mouseExited(MouseEvent arg0) {
                text.setBackground(Color.WHITE);                
            }

            @Override
            public void mousePressed(MouseEvent arg0) {}

            @Override
            public void mouseReleased(MouseEvent arg0) {}           
        });
    } // end of mouse action    

    public static void main(String[] args) {
        GridLayoutExample test = new GridLayoutExample();
        test.showFrame();
    }// end of main
}// class GridLayoutExampleenter code here

一方面当我禁用换行时它工作正常,另一方面我需要它来换行。

那么有什么建议可以做得更好吗?

提前谢谢了!

您正在运行时添加组件。 在这种情况下,您需要确保容器重新生效:

void addNewRow() {
    panel.add(new JLabel("Test1"));
    panel.add(new JTextField("Test"));
    panel.revalidate();
    panel.repaint();
}//addNewRow

此外,您应该仅在事件派发线程中创建和访问swing组件。 请看这里了解更多。

暂无
暂无

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

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