我试图从另一个类的ActionListener访问另一个类中的方法,但是,ActionListener中的nameWelcome出现语法错误消息,要求我为其创建变量。我已经创建了一个对象并将其引用到我要访问的类。我不知道我在哪里犯错:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class mathMulti extends JFrame {
JButton nextButton;
TextField nameField;
JLabel fullName;
JFrame frameOne;
JPanel panelOne;
public mathMulti() {
frameStart();
}
public void frameStart() {
frameOne = new JFrame();
frameOne.setSize(500, 500);
frameOne.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panelOne = new JPanel(new GridBagLayout());
panelOne.setBackground(Color.gray);
frameOne.add(panelOne);
GridBagConstraints g = new GridBagConstraints();
fullName = new JLabel("Full Name: ");
g.insets = new Insets(-390, -195, 0, 0);
g.gridx = 0;
g.gridy = 0;
panelOne.add(fullName, g);
nameField = new TextField(30);
g.insets = new Insets(10, 10, 10, 10);
g.gridx = 1;
g.gridy = 0;
g.weightx = 0;
g.weighty = 0;
g.ipady = 6;
panelOne.add(nameField, g);
nextButton = new JButton(" NEXT " + '\u25BA');
g.insets = new Insets(60, 5, 5, 5);
g.gridx = 2;
g.gridy = 5;
g.weightx = 0;
g.weighty = 0;
nextButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mathApo mathA = new mathApo();
mathA.frameNext();
nameWelcome.setText(nameField.getText());
frameOne.dispose();
}
});
panelOne.add(nextButton, g);
frameOne.setVisible(true);
}
public class mathApo extends JFrame {
JFrame frameTwo;
JPanel panelTwo;
JLabel nameWelcome;
public mathApo() {
frameNext();
}
public void frameNext() {
frameTwo = new JFrame();
frameTwo.setSize(500, 500);
frameTwo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panelTwo = new JPanel(new GridBagLayout());
panelTwo.setBackground(Color.gray);
frameTwo.add(panelTwo);
nameWelcome = new JLabel("Welcome, ");
panelTwo.add(nameWelcome);
frameTwo.setVisible(true);
}
}
}
答案 0 :(得分:0)
就像用户Worthless在评论中指出的那样,您正在调用变量nameWelcome
就像它是mathMulti
类中的一个字段,但实际上它是您的mathApo
类中的一个字段。
所以:
nameWelcome.setText(nameField.getText());
真的应该是:
mathA.nameWelcome.setText(nameField.getText());
此外,即使它不是非常重要,Java中的惯例也是将类名的首字母大写。因此,它将是mathApo
和mathMulti
,而不是MathApo
和MathMulti
。