点击的按钮有多个状态,类似 JToggleButton有两个状态一样,例如我点击一个按钮第一次点击后按钮的状态是a,第二次点击按钮的状态是b,第三次点击按钮状态是c

解决方案 »

  1.   

    加个flag就行了,每点一下,flag按一定规律变换,然后根据flag调用不同的方法
      

  2.   

    写一个简单的代码,应该是楼主要的吧import java.awt.*
    import java.awt.event.*;
    import javax.swing.*;public class ButtonChange extends JFrame {
    private int flag; //设置状态标志
    private JButton button; //变化的按钮
    private Icon[] images; //用于按钮表面的图片显示

    public ButtonChange() {
    setFrame();
    flag = 0;
    button = new JButton("Click Me");
    images = new Icon[] {
    new ImageIcon(getClass().getResource("1.gif")),
    new ImageIcon(getClass().getResource("2.gif")),
    new ImageIcon(getClass().getResource("3.gif"))
    }
    button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    if(mad == 0)) {
    button.setIcon(images[0]);
    mad++;
    }
    if(mad == 1) {
    button.setIcon(images[1]);
    mad++;
    }
    if(mad == 2) {
    button.setIcon(images[2]);
    mad = 0;
    }
    }
    });
    }
    public void setFrame() {
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLayout(new FlowLayout());
    this.setSize(600, 480);
    this.setVisible(true);
    }

    public static void main(Strin[] args) {
    new ButtonChange();
    }
    }
      

  3.   

    如果楼主要求的多态是换Icon和文字,可以用楼上的方法。我没用过button表现多态,
    如果多种状态一般用JRadioButton或者JComboBox这样的(只是说我自己这样用)。
    只用过JToggleButton这样两种状态的。
      

  4.   

    不单是图标和文字
    例如一个jtextfiled&一个button
    jtextfiled中输入的是字符串,button显示状态a
    输入int,显示状态b
    输入double,显示状态c
    zhanglongnihao同学给出的代码能满足上述需求,不过我想要的情况是:
    单jtextfiled输入int后,button显示状态b,然后我点击button,显示状态c时输入的int转换成double,显示状态a时int转换成string
      

  5.   

    实现功能不难,重要的是用JButton表现多种状态好不好。
    如果类型不是太多的话,用JRadioButton是不是直观一点?
    类似下面的布局
    |         text        |
    |*int| |*str| |*double|如果类型多的话,JButton变来变去的,用户很晕的。
      

  6.   

    看看JAVA设计模式里面的状态模式或许能有些帮助,我之前看过但是现在忘记了.....