【问题标题】:How to make JFrame paint only after I click button?如何仅在单击按钮后才使 JFrame 绘制?
【发布时间】:2014-05-20 06:41:29
【问题描述】:

当我运行应用程序时,整个框架被涂成黑色。

我怎样才能使它开始清晰然后在我按下按钮时被绘制?

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

【问题讨论】:

  • 作为一般提示,最好在JPanel 或其他JComponent 中进行自定义绘制,然后将其添加到顶级容器,例如JFrame。对于JComponent中的自定义绘制,覆盖paintComponent(Graphics)而不是paint(Graphics)并立即调用super方法绘制BG和边框等。
  • 对于问题 1:使用布尔标志 if (shouldDraw) { g.fill... }。更新按钮按下时的标志。再说一次,对于这种特殊情况,您也可以只使用 setBackground() ;-)
  • @peeskillet 我认为这完全可以在没有自定义绘画的情况下实现。在动作监听器中调用mainPanel.setBackground(color) 应该可以解决问题。
  • 好的,非常感谢您的建议和解决方案。我会在另一个线程中询问布局。

标签: java swing jframe paint


【解决方案1】:

您的黑屏问题是因为您在以下位置绘画:

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

您使用的是黑色的默认颜色 我试过你的代码并使用了这个:

g.setColor(Color.WHITE);

这会清除您的屏幕,然后使用布尔值并在您按下按钮时将其设置为 true:

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

然后最后使用:

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

在绘画方法中

【讨论】:

  • 感谢您的解释和解决方案
  • 如果它有助于解决问题,请accept回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多