0

So, I made a program that draws a rectangle whenever a button is clicked. But the rectangle only shows up sometime.. Here is the code for JFrame

        JFrame jf; // This is declared as a static member
        JPanel panel = new JPanel();
        panel.setBounds(200,0,200,400);
        jf = new JFrame("Try");
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.setLocationRelativeTo(null);
        jf.setSize(400,400);       
        jf.setVisible(true);

        JButton jb = new JButton("Click");
        jb.setBounds(10,10,100,60);
        panel.add(jb);
        jf.add(panel);

        Handler handle = new Handler();
        jb.addActionListener(handle);

For ActionListener :

 public void actionPerformed(ActionEvent ae)
    {
    Mainting maint = new Mainting();    
    jf.add(maint);
    maint.draw(true);

And the drawing class: Boolean checker =false;

public void draw(Boolean b)
{
    checker = b;
    repaint();
}

@Override  
public void paintComponent(Graphics g)
         {
  if(checker){
  super.paintComponent(g);
  g.fillRect(0,0,100,80);

The problem is : If I first maximize the window and then click on the button, nothing appears. If I just click the button, nothing appears. But if I click the button and maximize the window, a rectangle appears. Why this is happening ?

John Doe
  • 1
  • 2
  • You're not using layout managers correctly for one. Get rid of `setBounds(...)` and learn to use the layouts as intended. Secondly, you should get the `super.paintComponent` call **out** of the if block and before it. It **must** be called regardless of checker's state. If this doesn't help, then please create and post a proper [mcve] with code that we can compile and run. – Hovercraft Full Of Eels Dec 02 '17 at 15:10
  • Oh, I see the problem, -- you're adding the component within the ActionListener. Don't do that. Add it on program creation, and then simply change its checker state within the action listener. – Hovercraft Full Of Eels Dec 02 '17 at 15:11
  • In other words, add the Mainting JPanel to the GUI where you create the GUI and use a Mainting instance field to do this. Then call true/false on a setter method of this instance within the ActionListener. – Hovercraft Full Of Eels Dec 02 '17 at 15:13
  • Thank you. Now the code works when I maximize the window and run. Can you please explain why the code I wrote didn't work ? @HovercraftFullOfEels – John Doe Dec 02 '17 at 16:15
  • The duplicate will explain why the original code doesn't work. You never call `revalidate()` and `repaint()` on the container after changing visible components. – Hovercraft Full Of Eels Dec 02 '17 at 16:21

0 Answers0