问题描述
所以,我一直试图弄清楚这一点,但无法弄清楚如何做到这一点。我想在另一个类中使用我的一个按钮来更改GUI类中JLabel的文本。
So, I have been trying to figure this out for a little bit and cannot figure out how to do it. I want one of my buttons in another class to change the text of a JLabel in the GUI class.
以下是GUI类的代码:`import java.awt.Container;
Here is the code from GUI class:`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错误:
`
And here the code from the button trying to change the JLabel "error":`
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
访问添加一个getter,这样你的第二个类就可以访问该字段了。类似的东西,
First, add a getter with public
access so your second class can access the field. Something like,
public JLabel getError() {
return error;
}
或(作为在评论中建议,一个mutator)喜欢
Or (as @MadProgrammer suggested in the comments, a mutator) like
public void setError(String txt) {
error.setText(txt);
}
然后修改你的第二个类,并传递 GUI 在构造函数中。比如,
Then modify your second class, and pass the instance of GUI
to it in the constructor. Like,
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");
}
}
这篇关于从另一个类更改JLabel上的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!