我试图在 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 对象应该仅在 event dispatch thread 上构造和操作.
“具有 UI 委托(delegate)的 Swing 组件的子类(相对于
JComponent
的直接子类),应该在它们的paintComponent
覆盖中调用super.paintComponent()
。“为方便起见,
add
及其变体、remove
和setLayout
已被重写为 forward 到contentPane
根据需要。”最外层的
Container
应该是setVisible()
after 调用pack()
和其他影响几何的方法。
关于java - Swing 不在 Mac 上绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14265183/