JLabel从另一个类更新

时间:2019-03-14 12:37:59

标签: java panel jlabel increment

我目前遇到一个与MouseListener事件一起增加点数计数器的问题。这是我到目前为止的最新进展(已删除了一些不相关的代码)

import java.awt.*;
import javax.swing.*;
import java.awt.Color.*;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.util.Random;

public class Checkers extends JFrame
{
    Random random = new Random();
    private final int ROWS = 2;
    private final int COLS = 5;
    private final int GAP = 2;
    private final int NUM = ROWS * COLS;
    private int x;
    public static int score;
    private JPanel pane = new JPanel(new GridLayout(ROWS,COLS, GAP,GAP));
public  JLabel lbl1 = new JLabel ("score: " + score);

    private MyPanel [] panel = new MyPanel[NUM];
    private Color col1 = Color.RED;
    private Color col2 = Color.WHITE;
    private Color tempColor;

    public Checkers()
    {
        super("Checkers");
        setSize(600,600);
        setVisible(true);
        setBackground(Color.BLACK);
        setBoard();
    }

    //pane background colour and the size of this pane.
    pane.setBackground(Color.BLACK);
    pane.setPreferredSize(new Dimension(300,300));


    //pane background colour and size of this pane.
    pane2.setBackground(Color.white);
    pane2.setPreferredSize(new Dimension(300,300));

    //directions on the board where these panes appear.
    add(pane, BorderLayout.WEST);
    add(pane2, BorderLayout.EAST);
    pane2.add(lbl1);



    pane2.setLayout(new BoxLayout(pane2, BoxLayout.PAGE_AXIS));

还有MyPanel类

import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JPanel;

public class MyPanel extends JPanel implements MouseListener {

    public MyPanel() {
        addMouseListener(this);
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        setBackground(Color.BLACK);
        Checkers.score++;

    }

    @Override
    public void mousePressed(MouseEvent e) {
    }

    @Override
    public void mouseReleased(MouseEvent e) {   
    }

    @Override
    public void mouseEntered(MouseEvent e) {    
    }

    @Override
    public void mouseExited(MouseEvent e) { 
    }
}

预期结果-单击第一个窗格中的一个较小的面板后,窗格2中的score计数器将增加1,并且一直持续到全部被单击为止并且score无法再增加。

当前结果-score确实会增加,但不会以应有的方式增加,而是将点转移到下一个GUI实例(例如,如果3个面板是在第一个实例中单击,点在该第一个实例中仍将保持为0,但是一旦创建了新的GUI,则点计数器将为3),这不是我要的。

欢迎任何帮助/指导。

0 个答案:

没有答案