从Panel中向JPanel添加jTextArea

时间:2014-10-27 17:22:30

标签: java swing jtextarea

所以,我正在创建一个新的Canvas (JPanel)类:Canvas canvas = new Canvas();,然后我在该类上调用一个方法:canvas.addTextBox();

现在,在这个Canvas类中,我想向Canvas添加一个新的jTextArea。我尝试使用下面的代码,但它没有显示出来。不确定我做错了什么。谢谢!

class Canvas extends JPanel {

    public Canvas() {
        this.setOpaque(true);
        //this.setBackground(Color.WHITE);
    }

    public void addTextBox() {
        final JTextArea commentTextArea = new JTextArea(10, 10);
        commentTextArea.setLineWrap(true);
        commentTextArea.setLineWrap(true);
        commentTextArea.setWrapStyleWord(true);
        commentTextArea.setVisible(true);
    }

}

完整代码

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextArea;

public class UMLEditor {

    public static void main(String[] args) {
        JFrame frame = new UMLWindow();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(30, 30, 1000, 700);
        frame.getContentPane().setBackground(Color.white);
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}
class UMLWindow extends JFrame {
    Canvas canvas = new Canvas();

    private static final long serialVersionUID = 1L;

    public UMLWindow() {
        addMenus();
    }
    public void addMenus() {

        getContentPane().add(canvas);

        JMenuBar menubar = new JMenuBar();

        JMenuItem newTextBox = new JMenuItem("New Text Box");
        newTextBox.setMnemonic(KeyEvent.VK_E);
        newTextBox.setToolTipText("Exit application");
        newTextBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                canvas.addTextBox();
            }
        });

        menubar.add(newTextBox);

        setJMenuBar(menubar);

        setSize(300, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
}

class Canvas extends JPanel {

    public Canvas() {
        this.setOpaque(true);
        //this.setBackground(Color.WHITE);
    }

    public void addTextBox() {
        final JTextArea commentTextArea = new JTextArea(10, 10);
        commentTextArea.setLineWrap(true);
        commentTextArea.setLineWrap(true);
        commentTextArea.setWrapStyleWord(true);
        commentTextArea.setVisible(true);
    }

}

1 个答案:

答案 0 :(得分:3)

addTextBox方法仅创建JTextArea。它永远不会将其添加到JPanel

您需要将以下行添加到addTextBox方法:

add( commentTextArea );

如果在调用JFrame方法时屏幕上已显示包含组件的addTextBox,则还需要使容器无效。只需添加

revalidate();
repaint();