[英]Swing not drawing on Mac
I am trying to draw an incredibly basic shape using swing in Java, however for some reason it does not seem to be working. 我正在尝试使用Java中的swing绘制令人难以置信的基本形状,但是由于某种原因,它似乎无法正常工作。 This is code that I downloaded from my lecturer that he showed us in a lecture, but when I run it the window opens but nothing is drawn and I have no idea why.
这是我从讲师那里下载的代码,他在一次演讲中向我们展示了该代码,但是当我运行该代码时,窗口会打开,但是什么都没画,我也不知道为什么。
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());
}
}
I am using the Eclipse IDE. 我正在使用Eclipse IDE。
Dear user1821475's lecturer: 尊敬的user1821475的讲师:
Swing GUI objects should be constructed and manipulated only on the event dispatch thread . 只能在事件分发线程上构造和操作Swing GUI对象。
"Subclasses of Swing components which have a UI delegate (vs. direct subclasses of JComponent
), should invoke super.paintComponent()
within their paintComponent
override. “具有UI委托(相对于
JComponent
直接子类)的Swing组件的子类应在其paintComponent
覆盖范围内调用super.paintComponent()
。
"As a convenience add
and its variants, remove
and setLayout
have been overridden to forward to the contentPane
as necessary." “为方便起见,
add
和其变体已将remove
和setLayout
覆盖为必要时转发到contentPane
。”
The outermost Container
should be setVisible()
only after invoking pack()
and other methods affecting geometry. 仅在调用
pack()
和其他影响几何的方法之后,才应将最外面的Container
为setVisible()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.