在gridlayout中更改某个窗格的颜色

时间:2014-12-16 18:47:10

标签: java mouseevent grid-layout

所以,我想要发生的是每个盒子都是白色的,但当用户点击网格中的一个盒子时,它将变为随机生成的颜色。我知道如何为随机生成的颜色编写代码,但我不知道如何编写代码以便程序选择正确的面板来改变颜色。以下是我到目前为止的情况:

客户端

import javax.swing.*;    
import java.awt.*;
import java.util.Random;       

public class Prog3
{
   public static void main(String[] args)
   {
       int rows=8;
       int cols=8;
       JFrame theGUI = new JFrame();
       theGUI.setTitle("GUI Example");
       theGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       Container pane = theGUI.getContentPane();
       pane.setLayout(new GridLayout(rows, cols,5,5));

       for (int i = 1; i < rows * cols; i++)
       {
           Color backColor = Color.white;
           Prog3_Server panel = new Prog3_Server(backColor,50,50);
           pane.add(panel);
       }
       theGUI.pack();
       theGUI.setVisible(true);
    }
}

服务器

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

public class Prog3_Server extends JPanel
{
    public static void main(String[] args)
    {
        JFrame theGUI = new JFrame();
        theGUI.setTitle("GUI Example");
        theGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Prog3_Server panel = new Prog3_Server(Color.white, 200, 200);
        Container pane = theGUI.getContentPane();
        pane.add(panel);
        theGUI.pack();
        theGUI.setVisible(true);
    }

   // Client provides color and preferred width and height
   public Prog3_Server(Color backColor, int width, int height){
      setBackground(backColor);
      setPreferredSize(new Dimension(width, height));
   }

   // Client provides color 
   // Preferred width and height are 0, 0 by default   
   public Prog3_Server(Color backColor){
      setBackground(backColor);
   }    
}

关于如何使用鼠标事件确保右侧面板从白色变为随机颜色的任何想法?

1 个答案:

答案 0 :(得分:1)

您需要MouseListener/MouseAdapter

MouseListener detectClick = new MouseAdapter() {
  public void mouseClicked(MouseEvent me) {
    me.getSource().setBackground(createRandomBackgroundColor());
  }
}

如果您将此MouseListener添加到所有子面板,则应获得所需的结果

您应该在您创建的位置添加MouseListener并将子面板添加到父面板,此处:

   //create MouseListener here
   for (int i = 1; i < rows * cols; i++)
   {
       Color backColor = Color.white;
       Prog3_Server panel = new Prog3_Server(backColor,50,50);
       //add mouse listener to the panel you've created here
       pane.add(panel);
   }