錯誤: 無法初始化主類 SimpleGUI
原因: java.lang.NoClassDefFoundError: myDrawPanel (wrong name: MyDrawPanel)
代碼目的:顯示一個面板,帶有一個隨機顏色的圓和一個按鈕,點擊按鈕,圓變顏色。
請問如何修改代碼?
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 {
JFrame frame;
public static void main(String[] args){
SimpleGUI gui = new SimpleGUI();
gui.go();
}
public void actionPerformed(ActionEvent event){
frame.repaint();
}
public void go(){
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //設定關閉即停止
JButton button = new JButton("do not click") ;
button.addActionListener(this);
MyDrawPanel drawPanel = new MyDrawPanel(); //創建我們的myPanel物件
frame.add(BorderLayout.CENTER,drawPanel); //add進frame框架中
frame.add(BorderLayout.SOUTH,button);
frame.setSize(300,300);
frame.setVisible(true); //設定框架為可見
}
}
uj5u.com熱心網友回復:
1.使用你的代碼 沒有出現例外 已經實作了你想要的功能2.可能是你的eclipse或者其他編譯工具版本太低導致的
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/262712.html
標籤:Java相關
