0

I have a JFrame. When I click in the frame, I want to add a Component (in this case an extension of a Canvas). I added a MouseListener to the frame as follows:

    frame.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            frame.add(canvas);
            frame.repaint();
        }
    });

However, the component is not added when the mouse is clicked on the frame. I have no problem adding the component in my main method. Adding a print statement in the mouse listener prints correctly, as does removing components from the frame.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
park618
  • 27
  • 6

2 Answers2

0

Like @sprinter9 said, add frame.pack() before repainting. Try below

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class Frame {
    public static void main(String[] args){
        final JFrame frame = new JFrame("Add Component");
        final Canvas canvas = new Canvas();
        canvas.setBackground(Color.BLACK);

        frame.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                System.out.println("Clicked");
                frame.add(canvas);
                frame.pack();
                frame.repaint();
            }
        });


        frame.setMinimumSize(new Dimension(320,240));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

Demo, http://kurungkurawal.com/gifs/frame-add-component.gif

Lee
  • 3,259
  • 4
  • 21
  • 27
0

You are adding the component directly to the JFrame. You should use it's contentPane instead:

    frame.getContentPane().add(canvas);