我昨天问了一个类似的问题,但是在对我希望完成的事情进行了进一步研究之后,我有理由相信所回答的问题是不充分的,并且本身值得一个新问题,因为昨天的问题将解决一个不同的问题并帮助其他人,但不是我的特定问题问题。在此处链接到上一个问题。
我想要完成的是将 JFrame 的 contentPane 设置为 的大小200,200
,但是在绘制两个不同的矩形后,您会注意到明显的差异。请参阅随附的 SSCCE 和随附的图片。
Canvas.getWidth()/getHeight
简单地说,我想getContentPane.getWidth()/Height
返回我指定的尺寸200,200
。
参考图片
SSCCE 示例
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
@SuppressWarnings("serial")
public class SSCCE extends Canvas implements Runnable {
private JFrame frame;
private BufferStrategy bufferStrategy;
private Graphics2D graphics;
private boolean running = false;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
SSCCE game = new SSCCE();
game.setPreferredSize(new Dimension(200,200));
game.setFocusable(true);
game.setIgnoreRepaint(true);
game.frame = new JFrame("SSCCE");
game.frame.setLayout(new BorderLayout());
game.frame.getContentPane().setPreferredSize(new Dimension(200,200));
game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.frame.add(game, BorderLayout.CENTER);
game.frame.pack();
game.frame.setIgnoreRepaint(true);
game.frame.setResizable(false);
game.frame.setLocationRelativeTo(null);
game.frame.setVisible(true);
game.start();
}
});
}
public synchronized void start() {
this.createBufferStrategy(2);
bufferStrategy = this.getBufferStrategy();
graphics = (Graphics2D) bufferStrategy.getDrawGraphics();
Thread thread = new Thread(this, "main");
thread.start();
running = true;
}
@Override
public void run() {
while (running) {
graphics = (Graphics2D) bufferStrategy.getDrawGraphics();
graphics.setColor(Color.RED);
graphics.fillRect(0, 0, 210, 210);
graphics.setColor(Color.GREEN);
graphics.fillRect(0, 0, 200, 200);
graphics.setColor(Color.BLACK);
graphics.drawString("Specified Width: 200", 0, 10);
graphics.drawString("Specified Height: 200", 0, 20);
graphics.drawString("Canvas Width: " + getWidth(), 0, 30);
graphics.drawString("Canvas Height: " + getHeight(), 0, 40);
graphics.drawString("Content Pane Width: " + frame.getContentPane().getWidth(), 0, 50);
graphics.drawString("Content Pane Width: " + frame.getContentPane().getHeight(), 0, 60);
graphics.drawString("Red Rectangle = 210,200", 0, 70);
graphics.drawString("Green Retangle = 200,200", 0, 80);
graphics.dispose();
bufferStrategy.show();
}
}
}