我的名字是加布。
我制作的程序会通过单击按钮使另一页消失。问题是,我无法从我的两个班级传递适当的数据。这可能听起来很奇怪,但这是我的代码:
我的第一堂课(第一课):
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' visibility to false
和'msg2' visibility to true
,但我无法让该计划有效,因为第二堂课并不知道什么是&#39 ; MSG1&#39;和&#39; msg2&#39;。拜托,帮助我!
问候,-Gab
答案 0 :(得分:2)
对于能够使用对象的方法,它需要对此对象的引用。您正在创建一个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);
答案 1 :(得分:0)
使用msg&#39>的getter和setter。