簡體   English   中英

正在創建Java GUI,但事件未觸發任何東西

[英]Java GUI is being created, but event is not triggering anything

我正在嘗試創建一個簡單的GUI,其中單擊數顯示在按鈕上,並在每次單擊后增加,因此每次單擊后,每個按鈕的顏色都向右旋轉一個值。 目前,已經創建了GUI,但是沒有設置背景,並且當您單擊任何內容時都沒有任何反應。 我似乎在這里找不到問題。 有人看到嗎?

非常感謝您的幫助:)

 import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;


public class ButtonJava extends JButton implements ActionListener  {
  private static int currentColor=0;
  private int clicks;
  private static final Color[] COLORS = {
    Color.ORANGE,
    Color.WHITE,
    Color.GREEN };

  public ButtonJava( ){
    setBackground( Color.YELLOW );
    setText( "Pick ME" );
    this.addActionListener( this );
  }

  public static void main(String[] args) {
    JFrame frame = new JFrame ("JFrame");
    JPanel panel = new JPanel( );
    frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
    JButton buttons[] = new JButton[3];
    for(int i = 0;i<buttons.length ; i++){
      buttons[i] = new ButtonJava(); 
      panel.add(buttons[i]);
    }
    frame.getContentPane( ).add( panel );
    frame.setSize( 500, 500);
    frame.setVisible( true );
  }

  private void updateButton() {
    changeColors();
    clicks++;
    setText( "# of clicks = " + Integer.toString(clicks) );
  }

  private void changeColors( ) {
    for (int i=0;i<COLORS.length;i++){
      setBackground(COLORS[currentColor]);
      currentColor %=2;
    }
  }

  @Override
  public void actionPerformed( ActionEvent event ) {
    updateButton( );   
  }


}

一個簡單的錯誤-您沒有創建自定義按鈕類,而是使用JButton
更改以下行:
buttons[i] = new JButton("Pick Me");
至:
buttons[i] = new ButtonJava();

main ,您正在制作普通的JButton ,並將它們添加到您的UI中,因為我想您打算添加ButtonJava

不應該是:

ButtonJava buttons[] = new ButtonJava[3];
for(int i = 0;i<buttons.length ; i++){
    buttons[i] = new ButtonJava(); 
    panel.add(buttons[i]);
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM