【发布时间】: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)应该可以解决问题。 -
好的,非常感谢您的建议和解决方案。我会在另一个线程中询问布局。