因此,我一直在试图弄清楚这一点,却无法弄清楚如何做到这一点。我希望另一个类中的按钮之一可以更改GUI类中JLabel的文本。
这是来自GUI类的代码:`import java.awt.Container;
import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; public class GUI extends JFrame{ Container pane = getContentPane(); JButton guess = new JButton("Guess"); JButton gen = new JButton("Generate number"); JTextField userInput = new JTextField(); JLabel Numbers = new JLabel("Press generate to start."); JLabel guessedNum = new JLabel(""); JLabel error = new JLabel(""); public void CreateGUI(){ final int WIDTH = 325; final int HEIGHT = 200; final int centerWIDTH = WIDTH / 4; final int centerHEIGHT = HEIGHT / 4; guessHandler guessHandle; genHandler genHandle; pane.setLayout(null); guessHandle = new guessHandler(); guess.addActionListener(guessHandle); genHandle = new genHandler(); gen.addActionListener(genHandle); userInput.setBounds(centerWIDTH - 20, centerHEIGHT, 200, 20); guess.setBounds(userInput.getX() - 35, (userInput.getY() + 25), 105, 50); gen.setBounds((guess.getX() + 105), guess.getY(), 165, 50); error.setBounds(70, 125, 300, 20); Numbers.setBounds(90, 0, 300, 20); guessedNum.setBounds(20, 25, 300, 20); pane.add(userInput); pane.add(guess); pane.add(gen); pane.add(Numbers); pane.add(guessedNum); pane.add(error); setSize(WIDTH,HEIGHT); setTitle("Number Guesser"); setDefaultCloseOperation(EXIT_ON_CLOSE); setVisible(true); setResizable(false); setLocation(350, 150); } }
这里是尝试更改JLabel“错误”的按钮中的代码:
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JTextField; public class guessHandler implements ActionListener{ public void actionPerformed(ActionEvent e) { GUI gui = new GUI(); gui.changePOS(4, 50, 0, 300, 20); gui.error.setText("HI from guessHandler.java"); } }
首先,添加具有public访问权限的吸气剂,以便您的第二堂课可以访问该字段。就像是,
public
public JLabel getError() { return error; }
或(如@MadProgrammer在评论中建议的,是一个变种器),例如
public void setError(String txt) { error.setText(txt); }
然后修改第二个类,并GUI在构造函数中将其实例传递给它。喜欢,
GUI
public class guessHandler implements ActionListener{ private GUI gui; public guessHandler(GUI gui) { this.gui = gui; } public void actionPerformed(ActionEvent e) { gui.changePOS(4, 50, 0, 300, 20); gui.setError("HI from guessHandler.java"); } }