【问题标题】:How to change button properties using UIManager如何使用 UIManager 更改按钮属性
【发布时间】:2021-07-23 21:06:40
【问题描述】:

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

JOptionPane 的特定部分目前看起来像这样:

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

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",new ColorUIResource(32, 38, 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",new ColorUIResource(62, 68, 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, 38, 44));
    JLabel labelPass = new JLabel("Enter a password:");
    JPasswordField pass = new JPasswordField(16);
    pass.setBackground(new Color(32, 38, 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);
}

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

【问题讨论】:

    标签: java swing uimanager


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 感谢您的回答!代表未包含在特定 JFrame 或 JPanel 中的事物的一个小问题,因为例如,如果我有一个 if 语句运行类似 JOptionPane.showMessageDialog(null, "Looks like you exited the program. If you think this is a mistake, please report it to the developer!"); 的东西,那么 UIManager 不会更改其属性。我必须将它添加到面板或框架中吗?
    猜你喜欢
    • 1970-01-01
    • 2014-12-10
    • 2020-01-29
    • 1970-01-01
    • 2017-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多