[英]Swing not drawing on Mac
我正在嘗試使用Java中的swing繪制令人難以置信的基本形狀,但是由於某種原因,它似乎無法正常工作。 這是我從講師那里下載的代碼,他在一次演講中向我們展示了該代碼,但是當我運行該代碼時,窗口會打開,但是什么都沒畫,我也不知道為什么。
package graphicsEx;
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class Lecture1Example extends JPanel{
// This is where the JPanel gets (re-)painted when the screen is refreshed.
public void paintComponent(Graphics g) {
// Cast to Graphics2D for more features.
Graphics2D g2D = (Graphics2D) g;
Rectangle2D rect = new Rectangle2D.Double(20,30,40,50);
g2D.setColor(Color.red);
g2D.draw(rect);
g2D.fill(rect);
}
public static void main(String args[]) {
JFrame frame = new JFrame("Playing with Graphics");
frame.setSize(500, 400);
frame.setVisible(true);
frame.setContentPane(new Lecture1Example());
}
}
我正在使用Eclipse IDE。
尊敬的user1821475的講師:
只能在事件分發線程上構造和操作Swing GUI對象。
“具有UI委托(相對於JComponent
直接子類)的Swing組件的子類應在其paintComponent
覆蓋范圍內調用super.paintComponent()
。
“為方便起見, add
和其變體已將remove
和setLayout
覆蓋為必要時轉發到contentPane
。”
僅在調用pack()
和其他影響幾何的方法之后,才應將最外面的Container
為setVisible()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.