gpt4 book ai didi

java - 为一个 JButton 提供两种不同的操作

转载 作者:行者123 更新时间:2023-12-01 17:23:38 26 4
gpt4 key购买 nike

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

最佳答案

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("/image/gJmeJ.png");
URL onUrl = new URL("/image/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);
}
}

关于java - 为一个 JButton 提供两种不同的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16687639/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com