从另一个类

时间:2015-10-10 03:33:09

标签: java swing jlabel

所以,我一直试图弄清楚这一点,但无法弄清楚如何做到这一点。我想在另一个类中使用我的一个按钮来更改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");

    }

}

1 个答案:

答案 0 :(得分:2)

首先,添加一个具有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");
    }
}