简体   繁体   English

如何使用菜单栏添加 jTextArea

[英]How Do i add a jTextArea using menu bar

I am creating a word processor for my own use.I want to add a JTextArea to the frame after i click "NEW" in the menu bar.我正在创建一个文字处理器供我自己使用。我想在单击菜单栏中的“新建”后将 JTextArea 添加到框架中。 I am using GUI programing in netbeans.我在 netbeans 中使用 GUI 编程。

It'll be hard to answer your question without your source code but here is a working solution (Assuming that by menu bar button you mean a JMenuBar with a JMenuItem):如果没有源代码,很难回答您的问题,但这里有一个可行的解决方案(假设菜单栏按钮是指带有 JMenuItem 的 JMenuBar):

import java.awt.event.*;
import javax.swing.*;


class WordProcessor extends JFrame implements ActionListener{
    JMenuBar menuBar;
    JMenu file;
    JMenuItem newFile;
    JTextArea textArea; //The text area object
    public WordProcessor(){
        super("WordProcessor");
        setSize(400, 400);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
        menuBar = new JMenuBar();
        file = new JMenu("File");
        newFile = new JMenuItem("new");
        file.add(newFile);
        menuBar.add(file);
        setJMenuBar(menuBar);
        textArea = new JTextArea(5, 37); //Instantiate text area object
        newFile.addActionListener(this); //listen for events on the 'new' item of the 'file' menu
    }
    public void actionPerformed(ActionEvent event){
        if(event.getSource() == newFile){
            add(textArea); //Add the text area to the JFrame if the 'new' item is clicked
        }
    }
    public static void main(String[] args){
        WordProcessor window = new WordProcessor();
    }
}

This answers your request however I wouldn't add a JTextArea object to the window every time you click the new file menu item, instead I would add the JTextArea on load up and just clear the text area every time they click the new file menu item:这会回答您的请求,但是每次单击新文件菜单项我都不会向窗口添加 JTextArea 对象,而是在加载时添加 JTextArea 并在每次单击新文件菜单项时清除文本区域:

if(event.getSource() == newFile){
    textArea.setText(" ");
}

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

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