[英]Jframe with a rectangle filled in color blue
這段代碼只運行窗口框架,但是我無法顯示藍色的填充小矩形。 這是為什么? 該代碼對我來說看起來合乎邏輯。
我正在嘗試創建2個JFrame窗口,每個窗口都帶有一個藍色矩形。
public class ColoredRectangle {
// attributes of the rectangle
int width = 40;
int height =20;
int x = 80;
int y = 90;
JFrame window = new JFrame("Box Run");
Color color = Color.BLUE;
// the construtor of the window
public ColoredRectangle() {
window.setSize(200,200);
window.setVisible(true);
}
//the actual rectangle
public void paint () {
Graphics g = window.getGraphics();
g.setColor(color);
g.fillRect(x, y, width, height);
}
public static void main(String[] args) throws IOException {
// creating 2 windows
ColoredRectangle r1 = new ColoredRectangle();
ColoredRectangle r2 = new ColoredRectangle();
//drawing a blue rectangle in each window
r1.paint();
r2.paint();
}
}
根據評論:
paintComponent
不畫 paintComponent
應該受到保護,而不是公共的。 Runnable
傳遞到SwingUtilities.invokeLater(...)
方法中,應在事件線程上創建Swing GUI。 getGraphics()
獲得的Graphics對象(有一些例外)。 以這種方式獲得的對象將不會持久存在或保持穩定,有可能會丟失圖像,甚至會出現NullPointerException。 相反,Swing圖形通常通過在繪畫方法中進行繪制來被動完成,並允許JVM在需要的時間和位置調用此方法。 繪制動畫時,這將需要進行范式轉換。 例如:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.*;
@SuppressWarnings("serial")
public class DrawRectPanel extends JPanel {
private static final int PREF_W = 200;
private static final int PREF_H = PREF_W;
private Color RECT_COLOR = Color.BLUE;
private static final int RECT_X = 80;
private static final int RECT_Y = 90;
private static final int RECT_W = 40;
private static final int RECT_H = 20;
public DrawRectPanel() {
setPreferredSize(new Dimension(PREF_W, PREF_H));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(RECT_COLOR);
g.fillRect(RECT_X, RECT_Y, RECT_W, RECT_H);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("DrawRectPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new DrawRectPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
編輯:創建2個JFrame,如下更改GUI:
private static void createAndShowGui() {
JFrame frame = new JFrame("DrawRectPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new DrawRectPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGui();
createAndShowGui();
});
}
通過“按平台”設置JFrame的位置,盡管我也必須打印指向此相關StackOverflow鏈接的鏈接,但操作系統仍應將其放置在它認為合適的位置: 使用多個JFrame:好的還是不好的做法?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.