user2070502
user2070502

Reputation: 683

JPanel won't get painted with paintComponent

It won't paint at all, any ideas? Nothing is displayed on the back panel, how do I get to paint with the mouseDragged event?

I can't even display a single line with that... Here's the source code.. I added the Jbutton just to see if the Panel was actually being displayed

public class pinta extends JFrame {

HandlerClass handler=new HandlerClass();
    JPanel back=new JPanel();
    public pinta(){
        setSize(500,500);
        setResizable(true);
        getContentPane().setLayout(new BorderLayout());
        back.setBackground(Color.white);
        back.setSize(500,500);
        this.add(back);
        back.add(new JButton("test"));
        back.addMouseMotionListener(handler);
        back.setOpaque(true);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }    

    public void paintComponent(Graphics g){
        super.paintComponents(g);
        g.setColor(Color.black);

        Graphics2D g2d = (Graphics2D)g;
        g2d.fillOval(100, 100, 20, 10);
        g2d.setPaintMode();
        g2d.setStroke(new BasicStroke(1));

    }

    public class HandlerClass implements MouseMotionListener{
        int x, y;

        public int getX() {
            return x;
        }
        public void setX(int x) {
            this.x = x;
        }
        public int getY() {
            return y;
        }
        public void setY(int y) {
            this.y = y;
        }
        public void mouseDragged(MouseEvent e) {
            x=e.getX();
            y=e.getY(); 
        }
        public void mouseEntered(MouseEvent e){ 
        }

        public void mouseMoved(MouseEvent e) {
        }
    }
}

Upvotes: 0

Views: 164

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347334

JFrame does not have a method call paintComponent. If you used the @Override annotation, the compiler would have failed.

Also note, you are calling super.paintComponents - Notice the "s" at the end, this should have being an interactor of problems

JComponent (or JPanel which extends JComponent) is what you're after.

Take a look at Performing Custom Painting for more details

I should also mention that back.setSize(500,500) is irrelevant, as the layout manager will decide what size it wants to make the component

Upvotes: 3

Related Questions