Java GUI:在另一个类中更改Label

时间:2018-05-15 15:32:55

标签: java user-interface

大家好,我有这个模板程序,基本上我需要做的是:

按下更多砖块按钮时,将打开一个新窗口。当那个窗口中有一个按钮,当按下时,应该重置brick变量,并且应该重置标签,原始窗口中的标签需要重置为原始编号。我该怎么做呢?

这是第一堂课

import javax.swing.*;
import java.awt.event.*;

public class Brick {

    private JFrame firstbricks;

    int price = 0;
    int bricks = 20;

    public static void main(String[] args) {
        Brick window = new Brick();
        window.firstbricks.setVisible(true);
    }

    public Brick() {
        firstbricks = new JFrame();
        firstbricks.setBounds(0, 0, 272, 130);
        firstbricks.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        firstbricks.getContentPane().setLayout(null);

        JLabel lblBricks = new JLabel("20 remaining");
        lblBricks.setBounds(20, 54, 128, 23);
        firstbricks.getContentPane().add(lblBricks);

        JButton btnBricks = new JButton("Bricks");
        btnBricks.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                bricks--;

                if (bricks <= 20) {
                    lblBricks.setText(bricks + " remaining");
                    price += 4;
                }
            }
        });
        btnBricks.setBounds(10, 11, 104, 32);
        firstbricks.getContentPane().add(btnBricks);

        JButton btnExtra = new JButton("More Bricks");
        btnExtra.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                MoreBricks info = new MoreBricks();
            }
        });
        btnExtra.setBounds(131, 11, 115, 32);
        firstbricks.getContentPane().add(btnExtra);

    }
}

这是我希望更改标签的第二个窗口类:

import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class MoreBricks {

    private JFrame MoreBricks;

    public MoreBricks() {
        makeFrame();
    }

    private void makeFrame() {
        MoreBricks = new JFrame();
        MoreBricks.setBounds(100, 100, 156, 114);
        MoreBricks.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        MoreBricks.getContentPane().setLayout(null);
        MoreBricks.setVisible(true);

        JButton reset = new JButton("Reset");
        reset.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

            }
        });
        reset.setBounds(10, 11, 104, 34);
        MoreBricks.getContentPane().add(reset);




    }


}

1 个答案:

答案 0 :(得分:0)

简单的解决方案(但可能不是最好的),是MoreBricks构造函数将一个Brick实例作为构造函数:

public class MoreBricks {

    private JFrame MoreBricks;
    private Brick _brick;

    public MoreBricks(Brick b) {
        _brick = brick;
        makeFrame();
    }

然后您的重置按钮就会执行以下操作:

    reset.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            MoreBricks.this._bricks.ResetBrickCount();
        }

理想情况下,您有一个“模型”类,其中游戏的所有状态(例如砖块数)都封装在一个类中。然后,只要模型发生变化,所有相关的“视图”都会收到更改通知,并自行更新以反映屏幕上正确的值和状态。