1
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圖形用戶界面沒有繪製在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和我有一些代碼,應制定一個隨機顏色的圓圈每次按下按鈕時。
但此刻的drawpanel始終保持灰色,像這樣http://i.imgur.com/Kz84rKR.png
有什麼明顯的是,在停止從工作像它預期的代碼?
現在這個圓圈總是黑色的,並且永遠不會變成隨機的顏色。
我已經將我的代碼更新爲您所說的內容,但圓圈始終保持黑色,並且不會更改爲隨機顏色。 –
@JohnSumner:請參閱編輯回答。 –
耶謝謝所有的幫助抱歉不知道編輯原始帖子到目前的情況是壞的 –