问题
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