Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/367.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用MouseListener在JPanel上设置背景色_Java_Swing_Jpanel_Thread Sleep_Mouse Listeners - Fatal编程技术网

Java 使用MouseListener在JPanel上设置背景色

Java 使用MouseListener在JPanel上设置背景色,java,swing,jpanel,thread-sleep,mouse-listeners,Java,Swing,Jpanel,Thread Sleep,Mouse Listeners,我正在尝试创建一个生活模拟游戏: 我的代码基本上由一个JFrame和一个相应大小的2d布尔数组组成,其中每个JPanel都是扩展JPanel的类的实例 这一类: 将JPAnel初始化为设置的大小,使其不透明,设置其背景色(这一切都有效),并向其添加鼠标侦听器,在切换数组的值之前,该鼠标侦听器根据相应位置的2d布尔数组的值更改JPAnel的颜色 我还将布尔数组作为引用传递,这样每个图块都携带相同的布尔数组,并且它们都可以翻转其值 出于某种原因,JPanel保存的唯一背景色是我在初始化期间设置的背景

我正在尝试创建一个生活模拟游戏:

我的代码基本上由一个JFrame和一个相应大小的2d布尔数组组成,其中每个JPanel都是扩展JPanel的类的实例

这一类: 将JPAnel初始化为设置的大小,使其不透明,设置其背景色(这一切都有效),并向其添加鼠标侦听器,在切换数组的值之前,该鼠标侦听器根据相应位置的2d布尔数组的值更改JPAnel的颜色

我还将布尔数组作为引用传递,这样每个图块都携带相同的布尔数组,并且它们都可以翻转其值

出于某种原因,JPanel保存的唯一背景色是我在初始化期间设置的背景色。此后,JPanel不会更改其背景色,尽管mouseListener记录它已被按下,而且尽管成功调用了repaint()方法。有人能解释一下到底发生了什么事吗?我没有任何东西去调试,因为一切似乎都在正确的地方

(单个康威瓷砖)


下面是示例的一个工作变体,它在单击时切换像素的背景色。注意

  • 用于在EDT上运行

  • 请记住将()打包封闭框架

  • 调用
    setVisible()
    一次

  • 覆盖
    getPreferredSize()
    以确定磁贴的大小

经测试:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JPanel;

public class Conweezy {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                TheUniverseFrame theGame = new TheUniverseFrame(500, 500, 20, 20);
            }
        });
    }

    private static class TheUniverseFrame extends JFrame {

        public static boolean[][] universalframe;
        public TheTile[][] universaltiles;
        boolean threadstate = false;

        TheUniverseFrame(double xsize, double ysize, int tilexcount, int tileycount) {
            //set constants
            setTitle("Welcome to the Game of Life: Datatronic Existence");
            universalframe = new boolean[tilexcount][tileycount];
            universaltiles = new TheTile[tilexcount][tileycount];
            setLayout(new GridLayout(tilexcount, tileycount));
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            //initialize tiles and boolean array
            int i = 0;
            int j;
            while (i < tilexcount) {
                j = 0;
                while (j < tileycount) {
                    universalframe[i][j] = false;
                    universaltiles[i][j] = new TheTile(xsize / ((double) tilexcount), //tile width
                        ysize / ((double) tileycount), //tile height
                        (int) (xsize / ((double) tilexcount)) * i, //tile x position
                        (int) (ysize / ((double) tileycount)) * j, //tile y position
                        universalframe, //boolean array
                        i, j); //tile position on array
                    add(universaltiles[i][j]);
                    j++;
                }
                i++;
            }
            pack();
            setVisible(true);
        }
    }

    private static class TheTile extends JPanel {

        boolean[][] thearray;
        int xindex;
        int yindex;

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(25, 25);
        }

        public TheTile(double width, double height, int xloc, int yloc, boolean[][] inputworld, int i, int j) {
            thearray = inputworld;
            xindex = i;
            yindex = j;
            setOpaque(true);
            setBackground(Color.BLACK);
            addMouseListener(new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    thearray[xindex][yindex] = !thearray[xindex][yindex];
                    if (thearray[xindex][yindex]) {
                        setBackground(Color.WHITE);
                    } else {
                        setBackground(Color.BLACK);
                    }
                    repaint();
                    System.out.println(xindex + " " + yindex);
                }
            });
        }
    }
}
导入java.awt.Color;
导入java.awt.Dimension;
导入java.awt.EventQueue;
导入java.awt.GridLayout;
导入java.awt.event.MouseAdapter;
导入java.awt.event.MouseEvent;
导入javax.swing.JFrame;
在关闭时导入静态javax.swing.JFrame.EXIT_;
导入javax.swing.JPanel;
公共类康威齐{
公共静态void main(字符串[]args){
invokeLater(新的Runnable(){
@凌驾
公开募捐{
TheUniverseFrame theGame=新建UniverseFrame(500,500,20,20);
}
});
}
私有静态类TheUniverseFrame扩展了JFrame{
公共静态布尔[][]通用框架;
公共文件[][]universaltiles;
布尔threadstate=false;
UniverseFrame(双xsize、双ysize、int tilexcount、int tileycount){
//设置常数
setTitle(“欢迎来到生命游戏:数据电子的存在”);
universalframe=新布尔值[TileCount][TileCount];
universaltiles=新文件[TileCount][TileCount];
setLayout(新网格布局(TileCount、TileCount));
setDefaultCloseOperation(关闭时退出);
//初始化平铺和布尔数组
int i=0;
int j;
而(i
删除多余的
xsize
ysize
参数,作为重新分解的练习。
(The Conway Grid):


package conweezy;
import java.awt.Event.*;
import java.awt.event.*;
import javax.swing.*;
public class TheUniverseFrame extends JFrame implements ActionListener
{
    public static boolean[][] universalframe;
    public TheTile[][] universaltiles;
    boolean threadstate = false;
    TheUniverseFrame(double xsize, double ysize, int tilexcount, int tileycount)
    {
        //set constants
        setTitle("Welcome to the Game of Life: Datatronic Existence");
        universalframe = new boolean[tilexcount][tileycount];
        universaltiles = new TheTile[tilexcount][tileycount];
        setSize((int)xsize+100, (int)ysize);
        setLayout(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);            
        //initialize tiles and boolean array
        int i = 0;
        int j;
        setVisible(true);
        while(i < tilexcount)
        {
            j = 0;
            while(j < tileycount)
            {
                universalframe[i][j] = false;
                universaltiles[i][j] = new TheTile(xsize/((double)tilexcount), //tile width
                                                   ysize/((double)tileycount), //tile height
                                                   (int)(xsize/((double)tilexcount))*i, //tile x position
                                                    (int)(ysize/((double)tileycount))*j, //tile y position
                                                    universalframe, //boolean array
                                                     i, j); //tile position on array
                try
                {
                    Thread.sleep(0);
                }
                catch(InterruptedException e)
                {

                }
                //universaltiles[i][j].addMouseListener(universaltiles[i][j]);

                add(universaltiles[i][j]);
                repaint();
                j++;
            }
            i++;
        }            
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e)
    {

    }
}
package conweezy;


public class Conweezy 
{


    public static void main(String[] args) 
    {
        TheUniverseFrame theGame = new TheUniverseFrame(500,500,20,20);
    }

}
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JPanel;

public class Conweezy {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                TheUniverseFrame theGame = new TheUniverseFrame(500, 500, 20, 20);
            }
        });
    }

    private static class TheUniverseFrame extends JFrame {

        public static boolean[][] universalframe;
        public TheTile[][] universaltiles;
        boolean threadstate = false;

        TheUniverseFrame(double xsize, double ysize, int tilexcount, int tileycount) {
            //set constants
            setTitle("Welcome to the Game of Life: Datatronic Existence");
            universalframe = new boolean[tilexcount][tileycount];
            universaltiles = new TheTile[tilexcount][tileycount];
            setLayout(new GridLayout(tilexcount, tileycount));
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            //initialize tiles and boolean array
            int i = 0;
            int j;
            while (i < tilexcount) {
                j = 0;
                while (j < tileycount) {
                    universalframe[i][j] = false;
                    universaltiles[i][j] = new TheTile(xsize / ((double) tilexcount), //tile width
                        ysize / ((double) tileycount), //tile height
                        (int) (xsize / ((double) tilexcount)) * i, //tile x position
                        (int) (ysize / ((double) tileycount)) * j, //tile y position
                        universalframe, //boolean array
                        i, j); //tile position on array
                    add(universaltiles[i][j]);
                    j++;
                }
                i++;
            }
            pack();
            setVisible(true);
        }
    }

    private static class TheTile extends JPanel {

        boolean[][] thearray;
        int xindex;
        int yindex;

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(25, 25);
        }

        public TheTile(double width, double height, int xloc, int yloc, boolean[][] inputworld, int i, int j) {
            thearray = inputworld;
            xindex = i;
            yindex = j;
            setOpaque(true);
            setBackground(Color.BLACK);
            addMouseListener(new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    thearray[xindex][yindex] = !thearray[xindex][yindex];
                    if (thearray[xindex][yindex]) {
                        setBackground(Color.WHITE);
                    } else {
                        setBackground(Color.BLACK);
                    }
                    repaint();
                    System.out.println(xindex + " " + yindex);
                }
            });
        }
    }
}