我一直在寻找一种在屏幕上绘制黑白阵列的方法.这是一个简单的阵列,只有20x20.我打算用鼠标在数组上绘制,以便每个像素从黑色切换到白色并在单击时返回,然后将数组作为一组布尔(或整数)传递给另一个函数.目前我正在使用Swing.我记得在画布上使用Swing绘图,但我仍然无法找到实际用法.我应该使用画布,还是依靠JToggleButtons?
您可以简单地使用JFrame(或其他Swing组件)并覆盖该paint(Graphics)方法来绘制布尔矩阵的表示(请注意,在轻量级组件的情况下,JPanel您应该覆盖paintComponent(Graphics).这将为您提供单击并拖动功能你需要(使用单个Swing组件的网格很难实现).
正如其他人评论的那样,AWT Canvas并没有为你提供任何Swing组件所没有的功能,你会在下面的例子中看到我已经使用了createBufferStrategy同样存在的方法JFrame来确保显示非闪烁.

请注意,我的示例非常简单,因为它会切换您拖动的每个像素,而不是点击操作,确定您是处于"绘画"模式还是"擦除"模式,然后在拖动持续时间内专门应用黑色或白色像素.
public class Grid extends JFrame {
private static final int SCALE = 10; // 1 boolean value == 10 x 10 pixels.
private static final int SIZE = 20;
private boolean[][] matrix = new boolean[SIZE][SIZE];
private boolean painting;
private int lastX = -1;
private int lastY = -1;
public Grid() throws HeadlessException {
setPreferredSize(new Dimension(SIZE * SCALE, SIZE * SCALE));
setResizable(false);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setBackground(Color.WHITE);
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
painting = true;
tryAdjustValue(e.getPoint());
}
public void mouseReleased(MouseEvent e) {
painting = false;
lastX = -1;
lastY = -1;
}
});
addMouseMotionListener(new MouseMotionListener() {
public void mouseDragged(MouseEvent e) {
tryAdjustValue(e.getPoint());
}
public void mouseMoved(MouseEvent e) {
tryAdjustValue(e.getPoint());
}
});
}
private void tryAdjustValue(Point pt) {
int newX = pt.x / SCALE;
int newY = pt.y / SCALE;
if (painting && isInRange(newX) && isInRange(newY) && (newX != lastX || newY != lastY)) {
// Only invert "pixel" if we're currently in painting mode, both array indices are valid
// and we're not attempting to adjust the same "pixel" as before (important for drag operations).
matrix[newX][newY] = !matrix[newX][newY];
lastX = newX;
lastY = newY;
repaint();
}
}
private boolean isInRange(int val) {
return val >= 0 && val < SIZE;
}
public void paint(Graphics g) {
super.paint(g);
for (int x=0; x<SIZE; ++x) {
for (int y=0; y<SIZE; ++y) {
if (matrix[x][y]) {
g.fillRect(x * SCALE, y * SCALE, SCALE, SCALE);
}
}
}
}
public static void main(String[] args) {
Grid grid = new Grid();
grid.pack();
grid.setLocationRelativeTo(null);
grid.createBufferStrategy(2);
grid.setVisible(true);
}
}
Run Code Online (Sandbox Code Playgroud)