0

我对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);
    }
}
4

2 回答 2

3

EG(使用此答案中的图像)。

带有图标的 JToggleButton

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);
    }
}
于 2013-05-22T09:22:15.353 回答
2

有一个boolean名为onset的字段false

boolean on = false;

在你actionPerformed有一个类似这样的翻转逻辑

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

    if (!on) {
            contentPane.setBackground(Color.YELLOW);
            on = true;
    }
    else  {
        contentPane.setBackground(Color.DARK_GRAY);
        on = false;
    }
}
于 2013-05-22T09:04:19.293 回答