[英]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.