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

时间:2014-01-15 18:38:13

标签: java swing jpanel thread-sleep mouse-listeners

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

我的代码基本上由一个JFrame包含一个JPanels网格和一个相应大小的2d布尔数组,其中每个JPanel特别是一个扩展JPanel的类的实例

这堂课: 初始化JPAnel到一个设置的大小,使其不透明,设置其背景颜色(这一切都有效)并添加一个mouseListener,它在切换值之前根据相应位置的2d布尔数组的值更改JPanel的颜色数组。

我还将boolean数组作为参考传递,这样每个tile都携带相同的布尔数组,并且它们都可以翻转它的值。

由于某种原因,JPanel保留的唯一背景颜色是我在初始化期间设置的背景颜色。之后,尽管mouseListener注册了它已被按下,JPanel也没有改变它的背景颜色,而且尽管成功调用了repaint()方法。有人可以解释一下究竟发生了什么吗?我没有任何东西需要调试,因为一切似乎都是正确的。

(个人康威瓷砖)

package conweezy;


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

public class TheTile extends JPanel implements MouseListener
{
    boolean[][] thearray;
    int xindex;
    int yindex;
    public TheTile(double width, double height, int xloc, int yloc, boolean[][] inputworld, int i, int j)
    {
        super();
        setSize((int)width, (int)height); setLocation(xloc, yloc); 
        thearray = inputworld; xindex = i; yindex = j; setLayout(null); 
        setOpaque(true);
        if(!thearray[xindex][yindex])
        {               
            setBackground(Color.BLACK);
        }
        if(thearray[xindex][yindex])
        {                
            setBackground(Color.WHITE);
        }
        setVisible(true);
        //addMouseListener(this);       
    }        

    public void mousePressed(MouseEvent e)
    {
        if(!thearray[xindex][yindex])
        {                
            setBackground(Color.WHITE);
            System.out.println(xindex + " " + yindex);
            repaint();                
        }
        if(!thearray[xindex][yindex])
        {
            setBackground(Color.BLACK);
            repaint();                
        }
        thearray[xindex][yindex] = !thearray[xindex][yindex];
        repaint();            
    }

    public void mouseClicked(MouseEvent e)
    {            
    }

    public void mouseReleased(MouseEvent e)
    {            
    }

    public void mouseEntered(MouseEvent e)
    {            
    }
    public void mouseExited(MouseEvent e)
    {            
    }
}

(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);
    }

}

1 个答案:

答案 0 :(得分:2)

这是您的示例的工作变体,可在单击时切换像素的背景颜色。注意,

  • 使用invokeLater()在EDT上投放。

  • 请记住pack()封闭框架。

  • 致电setVisible()一次。

  • 覆盖getPreferredSize()以确定图块的大小。

image

经测试:

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);
                }
            });
        }
    }
}