Text is greyed out when JButton is disabled

允我心安 提交于 2019-12-24 01:18:38

问题


I'm making Minesweeper for a school project. When a field/button is clicked, it gets disabled, and it shows its neighbors with a different color depending on the number of neighbors it has. I'm working on this in Eclipse. It works all perfectly and I'm almost ready to submit it. The only problem is that the colors work when run in Eclipse and JCreator, but when I run it with a .bat/command (java Minesweeper), the numbers show up greyed out instead of colored.

I change the colors with html tags when I call setText(). Ex: setText("<html><font color=red>3</font></html>") etc

Why is this happening? Colors work fine in Eclipse/JCreator, but not when I run the game through cmd or a batch script

Try this: It doesn't work for me...

Compile and run this in Eclipse/JCreator. Then try running it using java Test

The text will be red when run in Eclipse/JCreator, and grey when run in a script

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

class Test {
    public static void main(String[] args) {
        JFrame mainFrame = new JFrame("Test");
        JButton testButton = new JButton("Click this");

        MouseAdapter buttonListener = new MouseAdapter() {
            public void mouseReleased(MouseEvent e) {
                int modifier = e.getModifiers();
                JButton clicked = (JButton)e.getSource();
                clicked.setForeground(Color.RED);
                clicked.setText("<html><font color=red>" + clicked.getText() + "</font></html>");
                clicked.setEnabled(false);
            }
        };

        mainFrame.setMinimumSize(new Dimension(640,480));
        mainFrame.getContentPane().add(testButton);
        testButton.addMouseListener(buttonListener);
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainFrame.setVisible(true);
    }
}

回答1:


you have to test for JButton#isEnabled(), for example

JButton.setText("<html><font color="
  + (bClose.isEnabled() ? "black" : "red") + ">"
  + bClose.getText() + "</font></html>");

and very nice is JButton#setDisabledIcon(Icon) too




回答2:


Turns out the command java on my system points to JRE 1.7.0_1 instead of JRE 1.6.0_29 (even though I never added JRE 7's directory to the PATH variable...). And for some reason, this code behaves differently on the two JREs. On JRE 7, the text gets greyed out. On JRE 6, it behaves the way I want it to, and the text doesn't get greyed out.



来源:https://stackoverflow.com/questions/9008814/text-is-greyed-out-when-jbutton-is-disabled

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!