1

The class

 class MyComponent extends JComponent {
       public void paint(Graphics g) {

               g.fillRect(30, 30, 100, 100);

       }

    }

Jbutton is performed action on this

jButton2.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {

         jPanel4.add(new MyComponent());
         addComponent(new MyComponent());
      }
    });
 jButton1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {

         jPanel4.add(new MyComponent1());
         addComponent(new MyComponent1());
      }
    });

I have some other Jbutton action as well . Now I want to detect the shape when it is in the panel. Then I want to perform some action on the panel current shape.

jButton5.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        if(e.getSource()==jButton1)
        {
            jPanel4.removeAll();
            jPanel4.updateUI();
            jPanel4.add(new MyComponent11());
             addComponent(new MyComponent11());
        }


      }
    });

But This code is not detecting the shape. Any solution for this please

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Jahidul Islam
  • 29
  • 2
  • 7
  • `.. extends JComponent { public void paint(Graphics g) { ..` **should** be `.. extends JComponent { public void paintComponent(Graphics g) { super.paintComponent(g); ..` – Andrew Thompson Nov 19 '14 at 16:16
  • Don't use the updateUI() method, since you have NOT changed the UI. If you add/remove components on a visible GUI then use revalidate() and repaint(). – camickr Nov 19 '14 at 16:49

1 Answers1

0

I wrote a general implementation of this using Area, which you can find here. Specifically, the main method in AreaManager is informative as to how it all works together.

If you're just looking to detect mouse clicks in the bounds (30,30,100,100) you can implement that more easily in a regular MouseListener / Adapter. But it sounds like you're interested in the full solution, or?

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80