2
我試圖實現一個簡單的GUI應用程序,有一個類擴展JPanel,然後將其添加到框架並添加一個按鈕,但沒有任何反應,當我點擊按鈕。什麼是錯的?錯誤的輸出與下面的代碼
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class dup extends JPanel {
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.green);
g2d.fillRect(0, 0, this.WIDTH, this.HEIGHT);
System.out.println("inside paint component class");
}
}
public class drawing implements ActionListener {
JFrame frame;
dup d1;
public static void main(String args[]) {
drawing d2 = new drawing();
d2.go();
}
public void go() {
frame = new JFrame();
JButton button = new JButton("click me");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
d1 = new dup();
button.addActionListener(this);
frame.getContentPane().add(BorderLayout.WEST, button);
frame.getContentPane().add(BorderLayout.CENTER, d1);
frame.setSize(300, 300);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
frame.repaint();
}
}
這是什麼問題?
您是否看到調試信息「inside paint component」? – Tarik
請爲班級學習常見的[Java命名約定](http://java.sun.com/docs/books/jls/second_edition/html/names.doc.html#73307)(具體用於名稱的情況)方法和屬性名稱並一致使用它們。但是發佈SSCCE +1。 :) –
此外,在你的'actionPerformed()'方法中,如果你可能會嘗試修改'dup(JPanel)'的值以使它在它上面作出迴應,那麼我想你需要使用'd1.repaint() '而不是'frame.repaint()' –