【发布时间】:2016-12-13 19:22:24
【问题描述】:
我正在尝试正确调整 JPanel 的大小,使其完全适合渲染的 8 x 8 棋盘格。当我使用绘图程序放大时,我注意到在宽度和高度上都添加了两个额外的像素......
这还不错,但是当我将这个 CENTER 面板与其他 JPanel(使用 BorderLayout 在 JFrame 中的北、南、东、西)包围时,白色间隙很明显。
我通过在对setPreferredSize 的调用中将宽度和高度都减去 2 个像素来解决此问题,但如果此异常是由图形驱动程序错误引起的,那么这不是一个好的解决方案。
想知道是否有更清洁的解决方案。下面提供的代码使用 JDK 7 64-BIT Windows 7 ...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class JavaExample {
private static final Color DARK_SQUARE_COLOR = new Color(205, 133, 63);
private static final Color LIGHT_SQUARE_COLOR = new Color(245, 222, 179);
private static final int SQUARE_WIDTH = 16;
private static final int SQUARE_HEIGHT = 16;
public JavaExample() {
JFrame frame = new JFrame();
frame.add( new JPanel() {
private static final long serialVersionUID = 1L;
{
setPreferredSize(new Dimension(SQUARE_WIDTH * 8, SQUARE_HEIGHT * 8));
}
protected void paintComponent( Graphics g ) {
super.paintComponent(g);
for(int row = 0; row < 8; row++) {
for(int col = 0; col < 8; col++) {
g.setColor(getSquareColor(row, col));
g.fillRect(col * SQUARE_WIDTH, row * SQUARE_HEIGHT, SQUARE_WIDTH, SQUARE_HEIGHT);
}
}
}
private Color getSquareColor(int row, int col) {
return (row + col) % 2 == 0 ? LIGHT_SQUARE_COLOR : DARK_SQUARE_COLOR;
}
});
frame.pack();
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible( true );
}
public static void main(String [] args) {
new JavaExample();
}
}
【问题讨论】:
-
我还在paintComponent中添加了一个打印语句,它错误地将宽度和高度显示为130 x 130而不是128 x 128