【发布时间】:2015-04-22 05:41:15
【问题描述】:
我正在使用 java awt 来渲染一个简单的矩形。我还有一个矩形用作窗口的背景。问题是,即使背景矩形设置为窗口的宽度和高度,它仍然不适合整个事物。我试过用谷歌搜索,但发现结果与我的需求无关。这是什么原因造成的?
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.image.BufferStrategy;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Game implements Runnable{
final int WIDTH = 640;
final int HEIGHT = 480;
JFrame frame;
Canvas canvas;
BufferStrategy bufferStrategy;
boolean running = false;
public Game(){
frame = new JFrame("Prototyping");
JPanel panel = (JPanel) frame.getContentPane();
panel.setPreferredSize(new Dimension(WIDTH, HEIGHT));
panel.setLayout(null);
canvas = new Canvas();
canvas.setBounds(0, 0, WIDTH, HEIGHT);
canvas.setIgnoreRepaint(true);
panel.add(canvas);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
canvas.createBufferStrategy(2);
bufferStrategy = canvas.getBufferStrategy();
canvas.requestFocus();
}
public void run(){
running = true;
while(running)
render();
}
private void render() {
Graphics2D g = (Graphics2D) bufferStrategy.getDrawGraphics();
g.clearRect(0, 0, WIDTH, HEIGHT);
render(g);
g.dispose();
bufferStrategy.show();
}
protected void update(){
}
protected void render(Graphics2D g){
g.setColor(Color.GRAY);
g.fillRect(0, 0, WIDTH, HEIGHT);
g.setColor(Color.BLUE);
g.fillRect(100, 0, 200, 200);
}
public static void main(String [] args){
Game game = new Game();
new Thread(game).start();
}
}
【问题讨论】:
-
"..即使背景矩形设置为窗口的宽度和高度,它仍然不适合整个东西。" 等等..什么?灰色矩形填充 UI(此处)。蓝色矩形刻意画得比 UI 小。顺便说一句:Java GUI 必须在不同的操作系统、屏幕尺寸、屏幕分辨率等上工作。因此,它们不利于像素完美布局。而是使用布局管理器,或 combinations of them 以及 white space 的布局填充和边框。
-
@AndrewThompson 感谢这些链接。虽然我看到的问题是侧面的空白:i.imgur.com/fcn7Ggx.gif。我认为这与 null 布局有关?
-
哦,我的错……我想我可能在查看结果之前添加了一个布局。把
panel.setLayout(null);改成panel.setLayout(new GridLayout());看看好不好.. -
@AndrewThompson 也没有这样做。