簡體   English   中英

在gridlayout中更改特定窗格的顏色

[英]Change the color of a certain pane in gridlayout

因此,我想讓每個框都變成白色,但是當用戶單擊網格中的一個框時,它將變為隨機生成的顏色。 我知道如何為隨機生成的顏色編寫代碼,但是我不確定如何進行編寫,以便程序選擇正確的面板來更改其顏色。 這是我到目前為止所擁有的:

客戶

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

關於如何使用鼠標事件來確保右側面板從白色更改為隨機顏色的任何想法?

您需要一個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);
   }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM