import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SimpleGui3C implements ActionListener{
JFrame frame;
public static void main (String[] args){
SimpleGui3C gui = new SimpleGui3C();
gui.go();
}
public void go() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Change colours");
button.addActionListener(this);
MyDrawPanel drawPanel = new MyDrawPanel();
frame.getContentPane().add(BorderLayout.SOUTH, button);
frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
frame.setSize(300,300);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event ){
frame.repaint();
}
}
drawpanel
import java.awt.*;
import javax.swing.*;
public class MyDrawPanel extends JPanel{
protected void paintComponenet(Graphics g){
g.fillRect(0,0,this.getWidth(),this.getHeight())
Graphics2D g2d = (Graphics2D) g;
int red = (int) Math.random() * 256;
int green = (int) Math.random() * 256;
int blue = (int) Math.random() * 256;
Color startColour = new Color(red,green,blue);
red = (int) Math.random() * 256;
green = (int) Math.random() * 256;
blue = (int) Math.random() * 256;
Color endColour = new Color(red,green,blue);
GradientPaint gradient = new GradientPaint(70,70,startColour,150,150,endColour);
g2d.setPaint(gradient);
g2d.fillOval(70,70,100,100);
}
}
我正在尝试了解GUI,我有一些代码,每次按下按钮时都会画一个随机的彩色圆圈。
但目前,绘图板始终保持灰色,如此http://i.imgur.com/Kz84rKR.png
有什么明显的东西阻止代码像预期的那样工作吗?
现在圆圈总是黑色,永远不会变成随机颜色。
答案 0 :(得分:4)
你拼写paintComponent错了。此方法始终位于@Override
所以改变这个:
public void paintComponenet(Graphics g) {
g.fillRect(0, 0, this.getWidth(),this.getHeight());
到此:
@Override // add so the compiler will warn you if you spell it wrong
protected void paintComponent(Graphics g) { // should be protected, not public
super.paintComponent(g); // so that you erase old images
g.fillRect(0, 0, this.getWidth(),this.getHeight());
修改强>
您需要在括号中进行双重数学运算,因此正确的值将转换为int,因为:
red = (int) Math.random() * 256;
等同于此
red = ((int) (Math.random())) * 256;
等于:
red = 0 * 256;
相反,请执行此操作:
red = (int) (Math.random() * 256);
但更重要的是你需要学习调试。使用printlns打印出您的颜色值,或使用调试器尝试隔离您的错误。在来这里之前先做这件事。例如:
red = (int) Math.random() * 256;
green = (int) Math.random() * 256;
blue = (int) Math.random() * 256;
// this will show you what your values are
// and key you in to where you should look:
System.out.printf("Colors: [%d, %d, %d]%n", red, green, blue);
Color endColour = new Color(red,green,blue);