gpt4 book ai didi

java - 单击事件 - 从另一个类访问 boolean 变量

转载 作者:行者123 更新时间:2023-11-30 05:43:48 25 4
gpt4 key购买 nike

遇到一个问题,需要获取 boolean来自另一个类的变量。

我有以下for-loop , boolea n 和 if-else声明

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 i;
private int score;
private JPanel pane = new JPanel(new GridLayout(ROWS,COLS, GAP,GAP));
private JPanel pane2 = new JPanel();
private JPanel pane3 = new JPanel();

private JButton btn1 = new JButton("Play A Game");
private JButton btn2 = new JButton("Exit");

private JButton btn3 = new JButton("Easy");
private JButton btn4 = new JButton("Intermediate");
private JButton btn5 = new JButton("Difficult");
private JLabel lbl1 = new JLabel ("score: " + score);
private JLabel gameLost = new JLabel("You lose! You got: " + score + " points");

private JButton btnRestart = new JButton("Restart");

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

//Starts the checkers GUI, calling the constructor below this.

public static void main(String[] args){
new Checkers();
}

//Sets the dimensions of the GUI, visibility, background color and
//contents via the setBoard();

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

//Makes the grid, contains a conditional boolean, adds the panels to grid based on i value.
//sets Colours accordingly

public void setBoard()


{

boolean isPanelDisabled = false;
for (int i = 0; i < panel.length; i++) {
panel[i] = new MyPanel(this);
pane.add(panel[i]);

if (i % COLS == 0) {
tempColor = col1;
}
if (i == 9 || i <8) {
panel[i].setBackground(col1);

}
if(i == 8){
isPanelDisabled = true;
panel[i].setBackground(col3);
}

}

//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.add(btnRestart);
btnRestart.addActionListener( e -> restartBoard());
pane2.setLayout(new BoxLayout(pane2, BoxLayout.PAGE_AXIS));

}

//increments the score for the user based on current points.

public void incrementScore(){
if (score != 5){

score++;
lbl1.setText("Score: " + Integer.toString(score));
}
else if(score == 5){

lbl1.setText("Congratulations!, you've won!, your score is:" + score);
}

}
}

还有这个mouseClicked Activity

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


public class MyPanel extends JPanel implements MouseListener, ActionListener {
private final Checkers checkers;
private boolean isPanelDisabled;

//MyPanel Constructor that initiates a instance of checkers.

public MyPanel(Checkers checkers) {
this.checkers = checkers;
addMouseListener(this);

}

@Override
public void actionPerformed(ActionEvent e){

}
// Sets the panel colours according to their int number and the boolean condiiton.
@Override
public void mouseClicked(MouseEvent e) {
if (isPanelDisabled == true){

setBackground(Color.CYAN);
}
else{
setBackground(Color.BLACK);
checkers.incrementScore();
}

}

我的预期结果应该是,如果用户单击该网格中的第 8 个面板,那么该面板的颜色在按下时将为青色而不是黑色,但它无法访问 boolean 变量?我哪里出错了?

最佳答案

您的问题涉及不同类的对象之间的通信,有多种方法可以做到这一点,但最基本的是调用一个类中的对象的方法到另一个类。

首先让我们解决问题,...我创建了名为 MyPanel2 和 Checkers2 的类,以将它们与您的区别开来。

假设在 MyPanel2 中我们有一个 Checkers2 字段和一个名为 selected 且设置为 false 的 boolean 字段:

private Checkers2 checkers;
private boolean selected = false;

以及适当的 boolean getter 和 setter:

public void setSelected(boolean selected) {
this.selected = selected;
}

public boolean isSelected() {
return selected;
}

假设在 Checkers2 类中,您在一个数组中保存了 10 个 MyPanel2 实例,并且您希望用户能够“选择”该类的实例,但只允许选择其中 7 个实例,并假设如果您想要使用当前正在使用的设置,您可以为主类提供一个方法 public boolean isPanelDisabled(),并让 MyPanel2 类调用此方法来确定是否选择被允许。因此,在 MyPanel2 中,您可以拥有一个 MouseListener,其中包含以下内容:

@Override
public void mousePressed(MouseEvent e) {
if (selected) {
return;
}

// call the Checkers2 boolean method to check
if (checkers.isPanelDisabled()) {
setBackground(DISABLED_COLOR);
} else {
setBackground(SELECTED_COLOR);
setSelected(true);
}
}

在 Checkers2 .isPanelDisabled() 方法中,您可以迭代 MyPanel2 实例数组以查看已选择了多少个实例,如下所示:

public boolean isPanelDisabled() {
int count = 0;
for (MyPanel2 panel2 : myPanels) {
if (panel2.isSelected()) {
count++;
}
}
return count >= MAX_COUNT;
}

整个 MCVE 可测试代码可能如下所示:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class Checkers2 extends JFrame {
private static final int MAX_COUNT = 7;
private final int ROWS = 2;
private final int COLS = 5;
private final int GAP = 2;
private final int NUM = ROWS * COLS;
private MyPanel2[] myPanels = new MyPanel2[NUM];

public Checkers2() {
super("Checkers");
setDefaultCloseOperation(EXIT_ON_CLOSE);

JPanel gridPanel = new JPanel(new GridLayout(ROWS, COLS, 1, 1));
gridPanel.setBackground(Color.BLACK);
gridPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
for (int i = 0; i < myPanels.length; i++) {
MyPanel2 myPanel = new MyPanel2(this);
gridPanel.add(myPanel);
myPanels[i] = myPanel;
}

JButton resetButton = new JButton("Reset");
resetButton.setMnemonic(KeyEvent.VK_R);
resetButton.addActionListener(evt -> {
for (MyPanel2 myPanel2 : myPanels) {
myPanel2.reset();
}
});
JButton exitButton = new JButton("Exit");
exitButton.setMnemonic(KeyEvent.VK_X);
exitButton.addActionListener(evt -> System.exit(0));

JPanel buttonPanel = new JPanel();
buttonPanel.add(resetButton);

add(gridPanel);
add(buttonPanel, BorderLayout.PAGE_END);

pack();
setLocationRelativeTo(null);
}

public boolean isPanelDisabled() {
int count = 0;
for (MyPanel2 panel2 : myPanels) {
if (panel2.isSelected()) {
count++;
}
}
return count >= MAX_COUNT;
}


public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new Checkers2().setVisible(true);
});
}

}

class MyPanel2 extends JPanel {
private static final int PREF_W = 200;
private static final int PREF_H = PREF_W;
private static final int GR = 240;
public static final Color BASE_COLOR = new Color(GR, GR, GR);
public static final Color DISABLED_COLOR = Color.CYAN;
public static final Color SELECTED_COLOR = Color.BLACK;
private Checkers2 checkers;
private boolean selected = false;

public MyPanel2(Checkers2 checkers) {
setBackground(BASE_COLOR);
this.checkers = checkers;
setPreferredSize(new Dimension(PREF_W, PREF_H));
addMouseListener(new MyMouse());
}

public void setSelected(boolean selected) {
this.selected = selected;
}

public boolean isSelected() {
return selected;
}

public void reset() {
setBackground(BASE_COLOR);
setSelected(false);
}

private class MyMouse extends MouseAdapter {
@Override
public void mousePressed(MouseEvent e) {
if (selected) {
return;
}
if (checkers.isPanelDisabled()) {
setBackground(DISABLED_COLOR);
} else {
setBackground(SELECTED_COLOR);
setSelected(true);
}
}
}
}
<小时/>

另一个选项是将 MyPanel 的所有逻辑取出并将其放入主程序中,例如:

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

@SuppressWarnings("serial")
public class Checkers3 extends JPanel {
private static final int MAX_COUNT = 7;
private final int ROWS = 2;
private final int COLS = 5;
private final int GAP = 2;
private final int NUM = ROWS * COLS;
private MyPanel3[] myPanels = new MyPanel3[NUM];

public Checkers3() {
JPanel gridPanel = new JPanel(new GridLayout(ROWS, COLS, 1, 1));
gridPanel.setBackground(Color.BLACK);
gridPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
MyMouse myMouse = new MyMouse();
for (int i = 0; i < myPanels.length; i++) {
MyPanel3 myPanel = new MyPanel3();
myPanel.addMouseListener(myMouse);
gridPanel.add(myPanel);
myPanels[i] = myPanel;
}

JButton resetButton = new JButton("Reset");
resetButton.setMnemonic(KeyEvent.VK_R);
resetButton.addActionListener(evt -> {
for (MyPanel3 myPanel : myPanels) {
myPanel.reset();
}
});
JButton exitButton = new JButton("Exit");
exitButton.setMnemonic(KeyEvent.VK_X);
exitButton.addActionListener(evt -> System.exit(0));

JPanel buttonPanel = new JPanel();
buttonPanel.add(resetButton);

setLayout(new BorderLayout());
add(gridPanel);
add(buttonPanel, BorderLayout.PAGE_END);
}

public boolean isPanelDisabled() {
int count = 0;
for (MyPanel3 panel : myPanels) {
if (panel.isSelected()) {
count++;
}
}
return count >= MAX_COUNT;
}

private class MyMouse extends MouseAdapter {
@Override
public void mousePressed(MouseEvent e) {
MyPanel3 myPanel = (MyPanel3) e.getSource();
if (myPanel.isSelected()) {
return; // it's already selected
} else if (isPanelDisabled()) {
myPanel.setSelected(false);
} else {
myPanel.setSelected(true);
}
}
}

private static void createAndShowGui() {
Checkers3 mainPanel = new Checkers3();

JFrame frame = new JFrame("Checkers");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}

@SuppressWarnings("serial")
class MyPanel3 extends JPanel {
private static final int PREF_W = 200;
private static final int PREF_H = PREF_W;
private static final int GR = 240;
public static final Color BASE_COLOR = new Color(GR, GR, GR);
public static final Color DISABLED_COLOR = Color.CYAN;
public static final Color SELECTED_COLOR = Color.BLACK;
private boolean selected = false;

public MyPanel3() {
setBackground(BASE_COLOR);
setPreferredSize(new Dimension(PREF_W, PREF_H));
}

public void setSelected(boolean selected) {
this.selected = selected;
Color background = selected ? SELECTED_COLOR : DISABLED_COLOR;
setBackground(background);
}

public boolean isSelected() {
return selected;
}

public void reset() {
setSelected(false);
setBackground(BASE_COLOR);
}
}

但是最佳选项是将所有逻辑放在一个单独的模型类(或多个类)中,并使 GUI 尽可能愚蠢。

关于java - 单击事件 - 从另一个类访问 boolean 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55188752/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com