当前位置: 首页 > 面试题库 >

Click事件-从另一个类访问布尔变量[关闭]

郜琦
2023-03-14
问题内容

关闭。 这个问题需要调试细节。它当前不接受答案。

想改善这个问题吗? 更新问题,使其成为Stack Overflow 的主题。

去年关闭。

改善这个问题

陷入需要boolean从另一个类中获取变量的问题。

我有以下for-loopboolean和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事件

 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个面板,则该面板的颜色在被按下时将是青色而不是黑色,但是它无法访问布尔变量?我在哪里错了?


问题答案:

您的问题涉及不同类的对象之间的通信,并且有几种方法可以实现此目的,但是最基本的方法是将一个类中的对象的方法调用到另一个类中。

首先让我们设置问题,…我创建了名为MyPanel2和Checkers2的类,以区分它们与您的类。

假设在MyPanel2中,我们有一个Checkers2字段和一个名为selected的布尔值字段,并将其设置为false:

private Checkers2 checkers;
private boolean selected = false;

以及适当的布尔型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);
    }
}

但是 BEST 选项是将所有逻辑放在一个或多个单独的模型类中,并使GUI尽可能哑。



 类似资料:
  • 我是java新手,我不知道如何从另一个类访问变量 我正在尝试编写一个代码来发送带有未存储在本地的附件的邮件。我想访问SendMail类中ExcelFile类中编写的变量 如何在另一个类中访问excelFileAsByte并发送邮件而不将其存储在本地。我可以使用addBodyPart和ByteArrayResource将文件添加为附件吗。

  • 我知道这个话题在这里的100篇帖子中都有涉及,但我在这个特定的例子中遇到了很多麻烦,无法理解。 基本上,我正在使用Spritebuilder将精灵/节点导入我的游戏。我在类的正文中导入了某个特定类的精灵,但我希望能够在我的精灵类中定义一个变量,然后从类中编辑它。例如,如果我的精灵在GameScene中收集了一枚硬币,我想在精灵类中的方法中更改我的精灵的速度。 下面是我的代码,但不幸的是它不起作用。

  • 问题内容: 是否有可能在另一个文件内部使用一个文件中的变量? 包含一个名为的变量。 问题答案: 正如Fermin所说,声明后,所有加载的脚本都应可以访问全局范围内的变量。您也可以使用或的属性(在全局范围内)获得相同的效果。 …在另一个文件中… …在您的html文件中…

  • 问题内容: 我有以下内容: 我如何从另一个ViewController 访问? 我需要访问此功能: 问题答案: 默认情况下,swift中的所有内容都是公开的,因此,如果您声明以下内容: 只要拥有它的实例,就可以访问它: