Hakoo Desai
Hakoo Desai

Reputation: 341

How to draw rectangle in JPanel from button click event

I am relatively new to Java Graphics. I want to draw 20 x 80 rectangle at (X,Y) coordinates in JPanel when user clicks a JButton. (where 'X' and 'Y' are coming from 2 JTextFields) .

I have read many questions and tutorial, but could not solve a problem. In some cases, I can draw rectangle but cannot draw new rectangle without emptying JPanel.

enter image description here

Here is my code :

public class CustomPanel extends JPanel {
      @Override
      public void paintComponent(Graphics g) {
        super.paintComponent(g); // first draw a clear/empty panel
        g.draw3DRect(Integer.parseInt(x.getText()),Integer.parseInt(y.getText()), 20, 80, true);
        // then draw using your custom logic.
      }
    }

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
   //Code for frame 
   //Code for JTextfields x and y   

    JButton btnDraw = new JButton("Draw");
    btnDraw.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
                panel= new CustomPanel();


                panel.setBounds(406, 59, 407, 297);
                frame.getContentPane().add(panel);
                frame.revalidate();
        }
    });
    btnDraw.setBounds(286, 339, 89, 23);
    frame.getContentPane().add(btnDraw);



}

Upvotes: 0

Views: 1395

Answers (1)

camickr
camickr

Reputation: 324197

You ActionListener code is wrong. You don't want to create a new panel, you want to add a Rectangle to the existing panel.

When you create the GUI you should add two panels to the GUI:

  1. The first panel will be an empty panel that will do your custom painting. You would generally add this to the CENTER of the frame
  2. The second panel will contain the "Draw" button. You would generally add this panel to the PAGE_END. Then when you click the Draw button you invoke a method like addRectangle(...) in your custom painting panel so the panel can paint the Rectangle.

Check out Custom Painting Approaches for the two common ways to do custom painting:

  1. Keep a List of Object to paint and then in the paintComponent() method you iterate the LIst an paint each object.
  2. Create a BufferedImage and then just paint the Rectangle onto the BufferedImage, then you can just paint the BufferedImage either in a JLabel or in your paintComponent() method.

Upvotes: 1

Related Questions