目的是實作在一個面板上面放置一個按鈕,一個圓形,點擊按鈕,圓形里的顏色就會變。
但是我加入了implement之后,在監聽到點擊之后呼叫的函式:actionPerformed()會顯示frame被標紅了,connot resolve symbol frame,請問怎么修改呢?
代碼:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class MyDrawPanel extends JPanel {
public void paintComponent(Graphics g) {
Graphics2D graphics2D = (Graphics2D) g;
int red = (int) (Math.random()*255);
int green = (int) (Math.random()*255);
int blue = (int) (Math.random()*255);
Color startColor = new Color(red,green,blue);
red = (int) (Math.random()*255);
green = (int) (Math.random()*255);
blue = (int) (Math.random()*255);
Color endColor = new Color(red,green,blue);
GradientPaint gradientPaint = new GradientPaint(70,70,startColor,150,150,endColor);
graphics2D.setPaint(gradientPaint); //將虛擬的筆刷畫成漸層
graphics2D.fillOval(70,70,100,100); //用目前的筆刷來填滿橢圓形區域
}
}
public class SimpleGUI implements ActionListener {
public static void main(String[] args){
SimpleGUI gui = new SimpleGUI();
gui.go();
}
public void actionPerformed(ActionEvent event){
frame.repaint();
}
//重寫JPanel,加入我們需要的樣式
public void go(){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //設定關閉即停止
JButton button = new JButton("do not click") ;
button.addActionListener(this);
MyDrawPanel mypanel = new MyDrawPanel(); //創建我們的myPanel物件
frame.add(BorderLayout.CENTER,mypanel); //add進frame框架中
frame.add(BorderLayout.SOUTH,button);
frame.setSize(300,300);
frame.setVisible(true); //設定框架為可見
}
}
不用介面的運行結果:

書上的實體

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/262706.html
標籤:Java相關
上一篇:Java 下拉選單邊框去不掉?
