我在Java中遇到了一些可能非常简单的问题。我写了下面的程序,它显示一个10×10的彩色矩阵,其颜色是随机生成的,并且在窗口中被用户点击后随机改变。但是,如果我想将这些正方形更改为矩形或其他任何形状,我该怎么做呢?鉴于我现有的代码,甚至有可能吗?非常感谢您的帮助 - 对于糟糕的代码缩进感到抱歉!
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 java.util.Random;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ColorGrid extends JLabel {
private static final int n = 10;
private static final Random random = new Random();
public ColorGrid() {
this.setOpaque(true);
this.setBackground(new Color(random.nextInt()));
this.setPreferredSize(new Dimension(50, 50));
}
private void GridOutput() {
JFrame f = new JFrame("ColorGrid Display Window");
f.setLayout(new GridLayout(n, n));
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
for (int i = 0; i < n * n; i++) {
final ColorGrid label = new ColorGrid();
label.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
label.setBackground(new Color(random.nextInt()));
}
});
f.add(label);
}
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new ColorGrid().GridOutput();
}
});
}
}