我的名字是加布。
我正在制作一个程序,通过单击按钮即可使一页消失为另一页。问题是,我无法从我的两个类(class)传递适当的数据。这听起来可能很奇怪,但这是我的代码:
我的第一个类(class1):
import javax.swing.*;
import java.awt.*;
import java.util.Scanner;
public class class1 {
public static void main(String[] args) {
JPanel panel = new JPanel();
JFrame frame = new JFrame();
GridBagLayout gridBag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
contenu.setLayout(gridBag);
boolean start = false;
JLabel label1 = new JLabel(
"<html><p><span style = 'font-size: 18px; font-color: blue'>The Number's Genius </span>(version 1.4)</p></html>");
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.gridheight = 1;
c.gridwidth = 4;
c.ipadx = 500;
panel.add(label1, c);
JLabel xxx = new JLabel("");
c.gridx = 0;
c.gridy = 4;
c.gridwidth = 3;
c.fill = GridBagConstraints.HORIZONTAL;
c.ipadx = 550;
panel.add(xxx, c);
JButton start = new JButton("<html><p><b>Start</b></p></html>");
c.gridx = 3;
c.gridy = 4;
c.gridwidth = 1;
c.ipadx = 1;
c.anchor = GridBagConstraints.LINE_END;
panel.add(start, c);
JLabel msg1 = new JLabel(
"<html><p style = 'background-color: white; font-size: 10px'>Click on Start to begin.</p></html>");
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 1;
c.gridheight = 3;
c.gridwidth = 4;
panel.add(msg1, c);
JLabel msg2 = new JLabel(
"<html><p style = 'background-color: white; font-size: 10px'>Ok, let's begin.</p><p style = 'background-color: white; font-size: 10px'>First question: Is your number even?</html>");
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 1;
c.gridheight = 3;
c.gridwidth = 4;
panel.add(msg1, c);
Moteur moteur = new Moteur();
start.addActionListener(moteur);
frame.setContentPane(contenu);
frame.setSize(700, 300);
frame.setVisible(true);
frame.setResizable(false);
}
}
您可能会注意到第二节课有一些法语文本,但不用担心,这并不重要。这是我的第二堂课:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Moteur implements ActionListener {
public void actionPerformed(ActionEvent e) {
msg1.setVisible(false);
msg2.setVisible(true);
}
}
事实上,我希望程序使 'msg1' 可见性为 false
和 'msg2' 可见性为 true
,但我无法使程序工作,因为第二类不知道什么是“msg1”和“msg2”。请帮助我!
问候,-Gab
最佳答案
为了使方法能够使用对象,它需要对此对象的引用。您正在创建一个 Moteur 实例,但没有将任何对象传递给此 Moteur 实例,因此它没有对除自身之外的任何对象的引用。
为了让 Moteur 类能够调用 msg1 和 msg2 的方法,您需要将对这两个对象的引用传递给 Moteur:
public class Moteur implements ActionListener {
private JLabel messageToHide;
private JLabel messageToShow;
public Moteur(JLabel messageToHide, JLabel messageToShow) {
this.messageToHide = messageToHide;
this.messageToShow = messageToShow;
}
public void actionPerformed(ActionEvent e) {
messageToHide.setVisible(false);
messageToShow.setVisible(true);
}
}
然后,当您创建 Moteur 时,您给它们两个要隐藏和显示的标签:
Moteur moteur = new Moteur(msg1, msg2);
关于java - 无法从另一个类访问数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25711088/