正在创建 Java GUI,但事件未触发任何内容 [英] Java GUI is being created, but event is not triggering anything

查看:25
本文介绍了正在创建 Java GUI,但事件未触发任何内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建这个简单的 GUI,其中单击次数显示在按钮上并在每次单击后递增,因此每次单击后,每个按钮的颜色都会向右旋转一个值.目前,GUI 已创建,但背景未设置,单击任何内容时什么也没有发生.我在这里似乎找不到问题.任何人都可以看到吗?

I am trying to create this simple GUI where the number of clicks is displayed on the button and incremented after each click, and so that after each click, the colours of each button are rotated one value to the right. At the moment, the GUI is created, but the background is not set and nothing happens when you click on anything. I can't seem to find a problem here. Can anyone see any ?

非常感谢您的帮助:)

Thanks a lot for your help with this :)

 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();

Simple mistake - you're not creating your custom button class, you're using JButton.
Change the following line:
buttons[i] = new JButton("Pick Me");
To:
buttons[i] = new ButtonJava();

这篇关于正在创建 Java GUI,但事件未触发任何内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆