- When changing the background color of JOptionPane it is not possible to change the background color of the text as shown in the image?!
The image that contains the problem
and
- Also, how can I change the background color of the OK button and the font color??
Note: that I have tried many solutions, but none of them work.
this is code:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
UIManager.put("OptionPane.buttonFont", new Font("Arial", PLAIN, 30));
JOptionPane pane = new JOptionPane("<html><b style=\"color:RED; font-size:20px;\">login successful</b></html>",
JOptionPane.INFORMATION_MESSAGE,
JOptionPane.DEFAULT_OPTION,
ChangeIconJoptionPane("/photo/icons8_Done_70px.png", 60, 60));
getComponents(pane);
pane.setBackground(new Color(32, 139, 223));
JDialog jd = pane.createDialog(this, "Success");
jd.setVisible(true);
}
CodePudding user response:
JOptionPane is made up of many components. You will need to set the background for all of them.
Here is an easy way to traverse an entire component tree:
private static Stream<Component> walk(Component root) {
Stream<Component> stream = Stream.of(root);
if (root instanceof Container) {
Component[] children = ((Container) root).getComponents();
stream = Stream.concat(
Arrays.stream(children).flatMap(c -> walk(c)), stream);
}
return stream;
}
private void jButton1ActionPerformed(ActionEvent evt) {
JOptionPane pane = new JOptionPane(
"<html><b style=\"color:RED; font-size:20px;\">login successful</b></html>",
JOptionPane.INFORMATION_MESSAGE,
JOptionPane.DEFAULT_OPTION,
ChangeIconJoptionPane("/photo/icons8_Done_70px.png", 60, 60));
Color background = new Color(32, 139, 223);
walk(pane).forEach(c -> c.setBackground(background));
}
However… in some look-and-feels, it is not possible to change the background color of a JButton. The system look-and-feels for Windows and Mac will ignore a JButton’s background property, and will always render the button using the system settings.
The most reliable way to customize the OK button is to create the button yourself, and pass it as an option value to the JOptionPane:
private void jButton1ActionPerformed(ActionEvent evt) {
JButton okButton = new JButton("OK");
Font font = okButton.getFont();
font = font.deriveFont(font.getSize2D() * 1.5f);
okButton.setFont(font);
JOptionPane pane = new JOptionPane(
"<html><b style=\"color:RED; font-size:20px;\">login successful</b></html>",
JOptionPane.INFORMATION_MESSAGE,
JOptionPane.DEFAULT_OPTION,
ChangeIconJoptionPane("/photo/icons8_Done_70px.png", 60, 60),
new Object[] { okButton });
okButton.addActionListener(e -> pane.setValue(JOptionPane.OK_OPTION));
Color background = new Color(32, 139, 223);
walk(pane).forEach(c -> c.setBackground(background));
}