zcarciu
zcarciu

Reputation: 33

How to make JFrame paint only after I click button?

When I run the application the whole frame is painted black.

How can I make it so that it starts out clear then it gets painted when I press the button?

package card;

import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class BdayCard extends JFrame {

JButton button1, button2;
JPanel panel;

BdayCard()
{
    panel = new JPanel();
    button1 = new JButton();

    button1.addActionListener( new ActionListener() 
    {
        public void actionPerformed(ActionEvent e)
            {
                repaint();
            }
    });

    panel.add(button1);

    this.add(panel);
    this.setTitle("It's Your Birthday!");
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setSize(600, 450);
    this.setLocationRelativeTo(null);
    this.setVisible(true);
}

public void paint(Graphics g){
    g.fillRect(0, 0, 600, 450);
}

public static void main(String[] args){
    new BdayCard();
}
}

Upvotes: 0

Views: 2490

Answers (1)

cassandra
cassandra

Reputation: 46

your problem with your blackscreen is because you paint at:

g.fillRect(0, 0, 600, 450);

you are using the default colour which is black I tried your code and used this:

g.setColor(Color.WHITE);

this clears your screen and then use a boolean and set it true when your button is pressed:

public void actionPerformed(ActionEvent e)
{
    button=true;
    repaint();
}

then finally use:

if(button){/*do stuff here*/}

in the paint method

Upvotes: 1

Related Questions