gpt4 book ai didi

java - 更改网格布局中某个 Pane 的颜色

转载 作者:行者123 更新时间:2023-12-01 12:07:09 30 4
gpt4 key购买 nike

所以,我想要发生的事情是每个框都是白色的,但是当用户单击网格中的其中一个框时,它将更改为随机生成的颜色。我知道如何为随机生成的颜色编写代码,但我不确定如何编写以便程序选择正确的面板来更改其颜色。这是我到目前为止所拥有的:

客户端

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

关于java - 更改网格布局中某个 Pane 的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27511786/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com