How to make JFrame paint only after I click button?

 ̄綄美尐妖づ 提交于 2019-12-25 01:51:30

问题


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();
}
}

回答1:


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



来源:https://stackoverflow.com/questions/23752636/how-to-make-jframe-paint-only-after-i-click-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!