JAVA中的ActionEvent函数
我的程序的目标是让用户在文本字段中输入一些文本。按下按钮后,按钮ActionEvent应将文本大写,并将其打印在按钮下方的文本区域。我已经在下面发布了我的代码,但我不确定为什么它没有做到我所描述的。它给了我一个错误: 以及守则:JAVA中的ActionEvent函数,java,swing,jtextfield,jtextarea,actionevent,Java,Swing,Jtextfield,Jtextarea,Actionevent,我的程序的目标是让用户在文本字段中输入一些文本。按下按钮后,按钮ActionEvent应将文本大写,并将其打印在按钮下方的文本区域。我已经在下面发布了我的代码,但我不确定为什么它没有做到我所描述的。它给了我一个错误: 以及守则: import javax.swing.*; import java.awt.event.*; import java.awt.*; import java.io.*; public class SecondLab extends JFrame implem
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
public class SecondLab extends JFrame implements ActionListener{
public SecondLab() {
setLayout(new GridLayout(3, 1, 5, 5));
JTextField field1 = new JTextField();
JTextArea area1 = new JTextArea();
area1.setEditable(false);
JButton jbtSubmit = new JButton("Submit");
jbtSubmit.addActionListener(this);
add(field1);
add(jbtSubmit);
add(area1);
}
public void actionPerformed(ActionEvent a) {
String text = field1.getText();
String upper = text.toUpperCase();
area1.setText(upper);
}
public static void main(String[] args) {
SecondLab frame = new SecondLab();
frame.setTitle("Lab #2"); //Sets the window title
frame.setSize(500, 400); //Starts with a default size
frame.setLocationRelativeTo(null); //Starts in center of screen
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Tells the program to end after closing
frame.setVisible(true); //Tells the frame to show up
}
}
变量
field1
和area1
仅在SecondLab
构造函数的范围内定义。将它们声明为类实例变量
private JTextField field1;
private JTextArea area1;
通过actionPerformed
方法使它们可见。同时确保删除作业中的初始关键字
field1 = new JTextField();
area1 = new JTextArea();
Read:
我很难理解我到底需要如何修改我的代码才能完成你所描述的。私有变量应该放在第二个实验室构造器的外面吗?这很有帮助。非常感谢,我想出来了!考虑一下如果你发现它有用的话:field1 = new JTextField();
area1 = new JTextArea();