我一直在寻找一种在屏幕上绘制黑白数组的方法。这是一个简单的数组,只有 20x20。我计划做的是用鼠标在数组上绘制,以便每个像素在单击时从黑色“切换”到白色并返回,然后将数组作为一组布尔值(或整数)传递给另一个函数。目前我正在使用 Swing。我确实记得用过Swing在画布上绘图,但我仍然找不到实际用法。我应该使用画布,还是依赖 JToggleButtons?
您可以简单地使用JFrame
(或其他 Swing 组件)并覆盖paint(Graphics)
绘制布尔矩阵表示的方法(请注意,对于轻量级组件,例如JPanel
你应该覆盖paintComponent(Graphics)
。这将为您提供所需的单击和拖动功能(使用单个 Swing 组件的网格很难实现这一点)。
正如其他人评论的那样,AWTCanvas
不会为您提供 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);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)