在Mac上无法绘图 [英] Swing not drawing on Mac
问题描述
我正在尝试使用Java中的swing绘制令人难以置信的基本形状,但是由于某些原因,它似乎无法正常工作.这是我从讲师那里下载的代码,他在一次演讲中向我们展示了该代码,但是当我运行该代码时,窗口会打开,但什么都没画,我也不知道为什么.
I am trying to draw an incredibly basic shape using swing in Java, however for some reason it does not seem to be working. 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());
}
}
我正在使用Eclipse IDE.
I am using the Eclipse IDE.
推荐答案
尊敬的user1821475的讲师:
Dear user1821475's lecturer:
-
仅在"具有UI委托的Swing组件的子类(相对于
JComponent
的直接子类)应调用"Subclasses of Swing components which have a UI delegate (vs. direct subclasses of
JComponent
), should invokesuper.paintComponent()
within theirpaintComponent
override."为方便起见,
add
及其变体将remove
和setLayout
覆盖为"As a convenience
add
and its variants,remove
andsetLayout
have been overridden to forward to thecontentPane
as necessary."在调用
pack()
和其他影响几何的方法之后,最外面的Container
应该仅是 .The outermost
Container
should besetVisible()
only after invokingpack()
and other methods affecting geometry.这篇关于在Mac上无法绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!