2
我正在製作一個在JFrame上畫一個圓的程序。我想用屏幕中心的圓來啓動程序,這樣即使我改變了JFrame窗口的大小,它仍然居中。我會怎麼做?我看了很多,但沒有找到任何適合我的東西。代碼在下面。提前致謝!如何在JFrame中居中繪製的對象?
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ImageFrame extends JFrame {
private static final long serialVersionUID = 1L;
int width = 40;
int height = 40;
int x = 160;
int y = 70;
JPanel panel = new JPanel() {
private static final long serialVersionUID = 1L;
public void paintComponent(Graphics g) {
super.paintComponents(g);
g.drawOval(x, y, width, height);
}
};
public ImageFrame() {
add(panel);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(400, 300);
setLocationRelativeTo(null);
setVisible(true);
}
}
如何獲取容器寬度和高度?對不起,如果這是非常簡單的。 – LAD
'getWidth()'和'getHeight()'分別爲...... :) – Reimeus
...在[javadoc]中找到(https://docs.oracle.com/javase/8/docs/api /javax/swing/JPanel.html)... – Reimeus