我有一个 LoginScreen
和一个 MainWindow
。当 DB 连接尝试成功时,出现 LoginScreen disposed
和 MainWindow。
我有一个按钮有 ActionListener
用于创建 JOptionPane
。代码实际上成功地工作。我认为 Painting
有三个问题。让我一一解释问题;
问题一;
UIManager UI=new UIManager();
Object paneBG = UI.get("OptionPane.background");
Object panelBG = UI.get("Panel.background");
UI.put("OptionPane.background", Color.red);
UI.put("Panel.background", Color.red);
String[] buttons2 = { "EXIT", "OK" };
int rc2 = JOptionPane.showOptionDialog(MainWindow.this,
panel,
"User Input",
JOptionPane.INFORMATION_MESSAGE,
JOptionPane.PLAIN_MESSAGE,
icon,
buttons2,
buttons2[1]
);
UI.put("OptionPane.background", paneBG);
UI.put("Panel.background", panelBG);
我使用上面的代码更改 OptionPane
的 background color
,向用户显示并将 UI 颜色回滚到原始颜色。
如果我直接运行 MainWindow
并单击按钮,颜色会改变(确定面板和按钮区域在 OptionPane 中保持原始颜色,但其他 OptionPane 区域变为红色。这是另一个问题) 像这样;
但是当我来自 LoginScreen
时,登录尝试成功,出现 LoginScreen disposed
和 MainWindow。我点击同一个按钮,但 OptionPane
现在没有绘制,就像这样;
问题2;
我在 MainWindow 中有另一个按钮,它创建了另一个 OptionPane。我直接运行 MainWindow 并单击第一个按钮(它更改了 UI 颜色和回滚操作),关闭它而不是单击第二个按钮(它有另一个 OptinPane)OptionPane 仍然绘制,因此 UI 颜色不会回滚到默认值。
问题3;
如果我们解决了第一个和第二个问题,我怎样才能使这些内部面板透明
(其中有标签和文本字段面板和按钮)
最佳答案
首先,UIManager的公共(public)方法是静态的。创建 UIManager 的实例是不正确的、具有误导性的并且毫无意义。调用这些方法的正确方法是:
UIManager.put("OptionPane.background", Color.red);
其次,您可能不应该使用全局设置来更改颜色,尤其是动态更改。相反,通过创建 JOptionPane 的实际实例而不是使用静态便捷方法来设置相关对象的颜色:
static void setBackground(Component c,
Color color) {
if (c instanceof JTextField || c instanceof AbstractButton) {
return;
}
c.setBackground(color);
if (c instanceof Container) {
Component[] children = ((Container) c).getComponents();
for (Component child : children) {
setBackground(child, color);
}
}
}
int show(Icon icon,
JComponent panel) {
String[] buttons2 = { "EXIT", "OK" };
JOptionPane optionPane = new JOptionPane(panel,
JOptionPane.PLAIN_MESSAGE,
JOptionPane.DEFAULT_OPTION,
icon,
buttons2,
buttons2[1]);
setBackground(optionPane, Color.RED);
optionPane.createDialog(MainWindow.this, "User Input").setVisible(true);
Object value = optionPane.getValue();
int rc2 = JOptionPane.CLOSED_OPTION;
if (value instanceof String) {
rc2 = Arrays.asList(buttons2).indexOf(value);
}
return rc2;
}
您要小心区分消息类型 参数和选项类型 参数。将 INFORMATION_MESSAGE 和 PLAIN_MESSAGE 作为参数传递是永远不正确的。 documentation声明第四个和第五个参数分别是选项类型和消息类型;选项类型参数应该是 DEFAULT_OPTION、OK_CANCEL_OPTION、YES_NO_OPTION 等。
关于java - 按钮操作中的 UIManager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34881250/