从另一个类更改JLabel上的文本[英] Changing text on a JLabel from another class

问题描述

所以,我一直在尝试解决这个问题,但不知道该怎么做.我想要另一个类中的一个按钮来更改 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 访问权限的 getter,以便您的第二个类可以访问该字段.类似的,

public JLabel getError() {
     return error;
}

或者(如评论中建议的@MadProgrammer,一个变异器)喜欢

public void setError(String txt) {
     error.setText(txt);
}

然后修改你的第二个类,并在构造函数中将 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");
    }
}

本文地址:https://www.itbaoku.cn/post/978451.html