给一个JButton两个不同的动作

时间:2013-05-22 09:00:47

标签: java swing jbutton japplet

我是java的新手,并不知道我可以用来实现我想要做的方法。 我需要制作一个模拟灯光开关的程序。一个按钮可打开和关闭灯。我在事件被触发之前将背景颜色设置为深灰色,并且在触发之后将背景颜色设置为黄色。我遇到的问题是当背景为黄色时如何使用相同的按钮将其更改为深灰色?

我的代码:

import javax.swing.JApplet;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Question2 extends JApplet implements ActionListener {
    public void init() {
        Container contentPane = getContentPane();
        contentPane.setBackground(Color.DARK_GRAY);

        contentPane.setLayout(new FlowLayout());

        JButton OnOffSwitch = new JButton("On/Off");
        contentPane.add(OnOffSwitch);
        OnOffSwitch.addActionListener(this);    
    }

    public void actionPerformed(ActionEvent e) {
        Container contentPane = getContentPane();

        if (e.getActionCommand().equals("On/Off"))
            contentPane.setBackground(Color.YELLOW);
        else 
            contentPane.setBackground(Color.DARK_GRAY);
    }
}

2 个答案:

答案 0 :(得分:3)

E.G。 (使用this answer)中的图像。

JToggleButton with icons

import java.awt.*;
import javax.swing.*;
import javax.imageio.ImageIO;
import java.net.URL;

class ToggleButtons {

    public static void main(String[] args) throws Exception {
        URL offUrl = new URL("http://i.stack.imgur.com/gJmeJ.png");
        URL onUrl = new URL("http://i.stack.imgur.com/5v2TX.png");
        final Image offImg = ImageIO.read(offUrl);
        final Image onImg = ImageIO.read(onUrl);
        Runnable r = new Runnable() {

            @Override
            public void run() {
                int s = 5;
                JPanel gui = new JPanel(new GridLayout(s, s));
                Icon offIcon = new ImageIcon(offImg);
                Icon onIcon = new ImageIcon(onImg);

                for (int ii=0; ii<s*s; ii++) {
                    JToggleButton tb = new JToggleButton(offIcon, ii%2==0);
                    tb.setSelectedIcon(onIcon);
                    gui.add(tb);
                }

                JOptionPane.showMessageDialog(null, gui);
            }
        };
        // Swing GUIs should be created and updated on the EDT
        // http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
        SwingUtilities.invokeLater(r);
    }
}

答案 1 :(得分:2)

将名为boolean的{​​{1}}字段设置为on

false

并且在boolean on = false; 中有一个像这样的翻转逻辑

actionPerformed