问题
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());
}
}
I am using the Eclipse IDE.
回答1:
Dear user1821475's lecturer:
Swing GUI objects should be constructed and manipulated only on the event dispatch thread.
"Subclasses of Swing components which have a UI delegate (vs. direct subclasses of
JComponent
), should invoke super.paintComponent() within theirpaintComponent
override."As a convenience
add
and its variants,remove
andsetLayout
have been overridden to forward to thecontentPane
as necessary."The outermost
Container
should besetVisible()
only after invokingpack()
and other methods affecting geometry.
来源:https://stackoverflow.com/questions/14265183/swing-not-drawing-on-mac