How to change the button backgrounds inside JOptionPane

时光总嘲笑我的痴心妄想 提交于 2019-12-18 12:39:21

问题


I was wondering if anybody knew if it was possible to change the background color on the buttons inside a JOptionPane. I know how to change the entire JOptionPane background using a UIManager, but know what I want is to set the individual okButton, cancelButton, and so on within the JOptionPane to separate individual colors. If I can do this, how would I do this?

Thanks for the help.


回答1:


There is no direct way to do this.

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

Using this approach you now have access to the actuall JDialog. Then you can use Darryl's SwingUtils to access the individual buttons and then set the background.

The code would be something like:

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



回答2:


Simplest would be to just create your own JDialog and set the button characteristics to your heart's content.




回答3:


You can use your own buttons with yours characteristics in showOptionDialog. I guess it is not the best solution, but it simply 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]);




回答4:


Add the the line of code below before your JOptionPane

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


来源:https://stackoverflow.com/questions/5877994/how-to-change-the-button-backgrounds-inside-joptionpane

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