如何使用 UIManager 更改按钮属性

问题描述

目前正在为使用 Java 的邮件 API 编程的电子邮件客户端进行项目。我在尝试使用 UIManager 更改 Swing 中的某些属性时遇到问题。

对于 JOptionPane 的特定部分,它目前看起来像这样:

enter image description here

可以看到按钮颜色没有随着当前代码的变化而变化:

protected static Credentials credentialHandler() {
    String EMAIL = null;
    String PASSWORD = null;

    UIManager.put("OptionPane.background",new ColorUIResource(32,38,44));
    UIManager.put("OptionPane.foreground",Color.WHITE);
    UIManager.put("Panel.background",44));
    UIManager.put("TextField.background",new ColorUIResource(62,68,74));
    UIManager.put("TextField.foreground",Color.WHITE);
    UIManager.put("Label.foreground",Color.WHITE);
    UIManager.put("PasswordField.foreground",Color.WHITE);
    UIManager.put("Button.background",74));
    JPanel panel = new JPanel();

    JLabel labelEmail = new JLabel("Enter an email:");
    labelEmail.setForeground(Color.WHITE);
    JTextField email = new JTextField(32);
    email.setBackground(new Color(32,44));
    JLabel labelPass = new JLabel("Enter a password:");
    jpasswordfield pass = new jpasswordfield(16);
    pass.setBackground(new Color(32,44));
    panel.add(labelEmail);
    panel.add(email);
    panel.add(labelPass);
    panel.add(pass);
    String[] options1 = new String[]{"Login","Cancel"};
    int option1 = JOptionPane.showOptionDialog(null,panel,"Credentials",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE,null,options1,options1[1]);
    if (option1 == 0) {
        EMAIL = email.getText();
        char[] passwordChar = pass.getpassword();
        PASSWORD = new String(passwordChar);
    } else {
        JOptionPane.showMessageDialog(null,"Looks like you exited the program. If you think this is a mistake,please report it to the developer!");
        System.exit(2);
    }
    return new Credentials(EMAIL,PASSWORD);
}

我想更改按钮的背景颜色和字体颜色(假设它与前景有关)。

解决方法

new ColorUIResource(62,68,74) 替换为 new java.awt.Color(62,74)

/* Add following "import":
 * import java.awt.Color;
 */
UIManager.put("Button.background",new Color(62,74));

要设置字体颜色,请使用以下内容(将 JButton 文本颜色设置为白色):

UIManager.put("Button.foreground",Color.white);