Question

If so someone could explain how to get this to paint and why it isn't painting that would be awesome!!!

public class Main extends JPanel implements Runnable {

    public void run() {

        System.out.println("g");
        repaint();
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawRect(50, 50, 200, 200);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Physics!");
        frame.setSize(500, 500);
        frame.setBackground(Color.BLUE);
        frame.setVisible(true);

        Main physics = new Main();
        Thread t = new Thread(physics);
        t.start();
    }

}
Was it helpful?

Solution

You never add physics to the JFrame

Main physics = new Main();
JFrame frame = new JFrame("Physics!");
frame.add(physics);

Side Note

  • When painting on JPanel override getPreferredSize() so the panel has a preferred size, then you can just pack() the frame, as you should be doing, instead of setting it's size

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(500, 500);
    }
    ...
    frame.pack();
    // frame.setSize(500, 500);
    
  • Also, paintComponent should be protected not public

  • Also see Initial Threads for running Swing apps on the Event Dispatch Thread

OTHER TIPS

You have to add the JPanel to the JFrame:

    JFrame frame = new JFrame("Physics!");
    Main physics = new Main();
    Thread t = new Thread(physics);
    t.start();
    frame.setContentPane(physics); // Add it like this
    frame.setSize(500, 500);
    frame.setBackground(Color.BLUE);
    frame.setVisible(true);

Try putting t.join() in the main method after t.start() .. Your main method should wait for the thread to finish.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top