[英]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.