1

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.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
user1821475
  • 61
  • 1
  • 2
  • 2
    Try calling super.paintComponent(g) – MadProgrammer Jan 10 '13 at 18:53
  • 3
    Make `frame.setVisible(true)` _last_. – trashgod Jan 10 '13 at 18:54
  • @MadProgrammer, can't believe it was something as simple as that, thank you so much – user1821475 Jan 10 '13 at 18:57
  • 2
    See trashgod's comment; also maybe you want to add your panel to the content pane, instead of replacing the content pane. – antlersoft Jan 10 '13 at 18:58
  • 1
    +1 mad and trashgod. also dont call `setSize` on `JFrame` rather override `getPreferredSize()` of `JPanel` and return Dimensions which fit the drawings and call `pack()` on `JFrame` before setting it visible. Also use [EDT](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html) to create and manipulate Swing components via `SwingUtilities.invokeXXX` block. – David Kroukamp Jan 10 '13 at 19:13

1 Answers1

7

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 their paintComponent override.

  • "As a convenience add and its variants, remove and setLayout have been overridden to forward to the contentPane as necessary."

  • The outermost Container should be setVisible() only after invoking pack() and other methods affecting geometry.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045