多状态按钮该如何实现

confusing 2009-03-06 10:44:56
点击的按钮有多个状态,类似 JToggleButton有两个状态一样,例如我点击一个按钮第一次点击后按钮的状态是a,第二次点击按钮的状态是b,第三次点击按钮状态是c
...全文
121 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
快乐的2 2009-03-16
  • 打赏
  • 举报
回复
看看JAVA设计模式里面的状态模式或许能有些帮助,我之前看过但是现在忘记了.....
wunan320 2009-03-12
  • 打赏
  • 举报
回复
实现功能不难,重要的是用JButton表现多种状态好不好。
如果类型不是太多的话,用JRadioButton是不是直观一点?
类似下面的布局
| text |
|*int| |*str| |*double|

如果类型多的话,JButton变来变去的,用户很晕的。
confusing 2009-03-10
  • 打赏
  • 举报
回复
不单是图标和文字
例如一个jtextfiled&一个button
jtextfiled中输入的是字符串,button显示状态a
输入int,显示状态b
输入double,显示状态c
zhanglongnihao同学给出的代码能满足上述需求,不过我想要的情况是:
单jtextfiled输入int后,button显示状态b,然后我点击button,显示状态c时输入的int转换成double,显示状态a时int转换成string
wunan320 2009-03-09
  • 打赏
  • 举报
回复
如果楼主要求的多态是换Icon和文字,可以用楼上的方法。

我没用过button表现多态,
如果多种状态一般用JRadioButton或者JComboBox这样的(只是说我自己这样用)。
只用过JToggleButton这样两种状态的。
zhanglongnihao 2009-03-08
  • 打赏
  • 举报
回复
写一个简单的代码,应该是楼主要的吧

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();
}
}
bind888 2009-03-07
  • 打赏
  • 举报
回复
不懂,up
weizhaozhe 2009-03-07
  • 打赏
  • 举报
回复
可以设置其风格不?
dawn023 2009-03-06
  • 打赏
  • 举报
回复
哪有那么简单的,每种状态的外观是不一样的。可能需要ui改变的。
阳二快跑 2009-03-06
  • 打赏
  • 举报
回复
加个flag就行了,每点一下,flag按一定规律变换,然后根据flag调用不同的方法
dawn023 2009-03-06
  • 打赏
  • 举报
回复
有什么使用的案例吗?没有见识过。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧