How to change button background inside JOptionPane

I was wondering if anyone knew if it was possible to change the background color of the buttons inside the JOptionPane . I know how to change the whole JOptionPane background using UIManager , but I know that I want to set separate okButton, cancelButton, etc. Within JOptionPane to separate individual colors. If I can do it, how would I do it?

Thanks for the help.

+3
source share
4 answers

There is no direct way to do this.

But if you really want to try, you will need to read the JOptionPane API, which gives you code that shows you how to manually create and display a JOptionPane without using showXXX methods.

Using this approach, you now have access to the executive JDialog. You can then use Darryl SwingUtils to access individual buttons, and then set the background.

The code will look something like this:

 JButton ok = SwingUtils.getDescendantOfType(JButton.class, dialog, "Text", "Ok"); ok.setBackground(...); 
+7
source

The simplest thing would be to simply create your own JDialog and set the button characteristics for your hearty content.

+3
source

You can use your own buttons with your own characteristics in showOptionDialog . I think this is not the best solution, but it just works.

 JButton button = new JButton("OK"); button.setBackground(Color.BLACK); button.setForeground(Color.WHITE); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { JOptionPane.getRootFrame().dispose(); } }); JButton[] buttons = { button }; OptionPane.showOptionDialog(null, "Test Message", "Dialog", JOptionPane.OK_OPTION, JOptionPane.INFORMATION_MESSAGE, new ImageIcon(), buttons, buttons[0]); 

enter image description here

0
source

Add the line of code below before your JOptionPane

 UIManager.put("Button.background", Color.white); JOptionPane.showMessageDialog(null, "Project, Please"); 
0
source

Source: https://habr.com/ru/post/1389694/


All Articles