gpt4 book ai didi

java - 如何在不隐藏其标签的情况下禁用 JButton?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:35:42 25 4
gpt4 key购买 nike

我正在使用 netbeans IDE 开发 Java 项目,我需要禁用特定的 JButton。为此,我使用以下代码。

IssuBtn.setEnabled(false);

但在它被禁用后,它不会在 JButton 上显示文本。我怎样才能将该文本保留在 JButton 上?

最佳答案

这个实验表明一个答案是“使用非金属的 PLAF”。

Look Of Disabled Buttons

import java.awt.*;
import javax.swing.*;

class LookOfDisabledButton {

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JPanel gui = new JPanel(new BorderLayout(3,3));
JPanel pEnabled = new JPanel(new GridLayout(1,0,2,2));
pEnabled.setBackground(Color.green);
gui.add(pEnabled, BorderLayout.NORTH);

JPanel pDisabled = new JPanel(new GridLayout(1,0,2,2));
pDisabled.setBackground(Color.red);
gui.add(pDisabled, BorderLayout.SOUTH);

UIManager.LookAndFeelInfo[] plafs =
UIManager.getInstalledLookAndFeels();
for (UIManager.LookAndFeelInfo plafInfo : plafs) {
try {
UIManager.setLookAndFeel(plafInfo.getClassName());
JButton bEnabled = new JButton(plafInfo.getName());
pEnabled.add(bEnabled);
JButton bDisabled = new JButton(plafInfo.getName());
bDisabled.setEnabled(false);
pDisabled.add(bDisabled);
} catch(Exception e) {
e.printStackTrace();
}
}

JOptionPane.showMessageDialog(null, gui);
}
});
}
}

或者,调整 UIManager 中的值。

UIManager tweak

import java.awt.*;
import javax.swing.*;

class LookOfDisabledButton {

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JPanel gui = new JPanel(new BorderLayout(3,3));
JPanel pEnabled = new JPanel(new GridLayout(1,0,2,2));
pEnabled.setBackground(Color.green);
gui.add(pEnabled, BorderLayout.NORTH);

JPanel pDisabled = new JPanel(new GridLayout(1,0,2,2));
pDisabled.setBackground(Color.red);
gui.add(pDisabled, BorderLayout.SOUTH);

// tweak the Color of the Metal disabled button
UIManager.put("Button.disabledText", new Color(40,40,255));

UIManager.LookAndFeelInfo[] plafs =
UIManager.getInstalledLookAndFeels();
for (UIManager.LookAndFeelInfo plafInfo : plafs) {
try {
UIManager.setLookAndFeel(plafInfo.getClassName());
JButton bEnabled = new JButton(plafInfo.getName());
pEnabled.add(bEnabled);
JButton bDisabled = new JButton(plafInfo.getName());
bDisabled.setEnabled(false);
pDisabled.add(bDisabled);
} catch(Exception e) {
e.printStackTrace();
}
}

JOptionPane.showMessageDialog(null, gui);
}
});
}
}

正如 kleopatra 所指出的..

it's not a solution but might be a pointer to the direction to search for a solution

“它”是我的答案。事实上,我怀疑她是通过评论找到了真正的原因:

guessing only: here it's due to violating the one-plaf-only rule.

我同意这个猜测。

关于java - 如何在不隐藏其标签的情况下禁用 JButton?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7631085/

25 4 0