-3
我正在为自己的用途创建一个文字处理器。我想在菜单栏中单击“新建”后添加一个JTextArea到框架。我在netbeans中使用GUI编程。如何使用菜单栏添加jTextArea
我正在为自己的用途创建一个文字处理器。我想在菜单栏中单击“新建”后添加一个JTextArea到框架。我在netbeans中使用GUI编程。如何使用菜单栏添加jTextArea
这将是很难回答你的问题,而不你的源代码但这里是(假设通过菜单栏按钮你的意思的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();
}
}
这个答案您的请求然而我不会在每次单击新文件菜单项时向窗口添加JTextArea对象,而是在加载时添加JTextArea,并且每次单击新文件菜单项时只清除文本区域:
if(event.getSource() == newFile){
textArea.setText(" ");
}
您可以使用字符串生成器来保存文本区域的内容。当您点击“新建”时,清空字符串生成器中的文本并更新文本区域。 – user3437460