JOptionPaneの背景色を変更する
Total: 2995, Today: 1, Yesterday: 0
Posted by aterai at
Last-modified:
Summary
JOptionPaneで使用されている子JPanelをすべて透明化して背景色を指定した色に変更します。
Screenshot

Advertisement
Source Code Examples
UIManager.put("OptionPane.background", Color.LIGHT_GRAY);
String txt = "<html>JOptionPane:<br><li>messageArea<li>realBody<li>separator<li>body<li>buttonArea";
String title = "Title";
int type = JOptionPane.WARNING_MESSAGE;
JLabel label = new JLabel(txt);
label.addHierarchyListener(e -> {
Component c = e.getComponent();
if ((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0 && c.isShowing()) {
stream(SwingUtilities.getAncestorOfClass(JOptionPane.class, c))
.filter(JPanel.class::isInstance)
.map(JPanel.class::cast) // TEST: .peek(cc -> System.out.println(cc.getName()))
.forEach(p -> p.setOpaque(false));
}
});
JButton b2 = new JButton("background");
b2.addActionListener(e -> JOptionPane.showMessageDialog(b2.getRootPane(), label, title, type));
View in GitHub: Java, KotlinDescription
defaultUIManager.put("OptionPane.background", Color.LIGHT_GRAY)でJOptionPaneの背景色を変更JOptionPaneで使用されている子JPanelが不透明のためフチ色のみ変更される
backgroundUIManager.put("OptionPane.background", Color.LIGHT_GRAY)でJOptionPaneの背景色を変更- メッセージ用コンポーネントに
HierarchyListenerを追加してJOptionPaneのオープンイベントを取得 JOptionPaneが表示状態になったらその子JPanelを検索し、すべてsetOpaque(false)で透明化- デフォルトの
JOptionPaneは以下の名前の5つのJPanelで構成されているOptionPane.messageAreaOptionPane.realBodyOptionPane.separatorOptionPane.bodyOptionPane.buttonArea
overrideJOptionPane.paintComponent(...)をオーバーライドして背景を任意のTextureに変更JOptionPaneの子JPanelを検索し、すべてsetOpaque(false)で透明化