gpt4 book ai didi

Java 用方法改变 JButton 颜色

转载 作者:行者123 更新时间:2023-12-02 10:34:33 24 4
gpt4 key购买 nike

我实现了一个带有 25 个 JButton 组件的 JFrame 来表示酒店中的可用房间。我确实知道这不是整个程序,但是我如何创建一种方法,在按下时颜色会发生变化?

可用房间的颜色是绿色,我想将它们更改为红色。

最佳答案

此代码使用 JToggleButton,其中针对标准状态和选定状态具有不同颜色的图标。也可以使用 JCheckBox

enter image description here

import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.net.*;
import java.util.*;

public class RoomReservationToggle {

private JComponent ui = null;
private String reservedPath = "/image/xj49g.png";
private String freePath = "/image/zJ8am.png";

RoomReservationToggle() {
try {
initUI();
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
}

public void initUI() throws MalformedURLException {
if (ui != null) {
return;
}
ui = new JPanel(new GridLayout(0, 4, 4, 4));
ui.setBorder(new EmptyBorder(4, 4, 4, 4));

ImageIcon reservedIcon = new ImageIcon(new URL(reservedPath));
ImageIcon freeIcon = new ImageIcon(new URL(freePath));

Random r = new Random();
for (int ii = 1; ii < 17; ii++) {
// a JCheckBox might also be used
JToggleButton tb = new JToggleButton(freeIcon, r.nextBoolean());
tb.setSelectedIcon(reservedIcon);
ui.add(tb);
}
}

public JComponent getUI() {
return ui;
}

public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
RoomReservationToggle o = new RoomReservationToggle();

JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);

f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());

f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}

关于Java 用方法改变 JButton 颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53384581/

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