【问题标题】:JButton, JTextFeild, JLabel set background color not workingJButton、JTextFeild、JLabel 设置背景颜色不起作用
【发布时间】:2019-07-07 04:41:17
【问题描述】:

这是我的 JButton 代码。我在为此登录按钮设置背景颜色时遇到问题

JButton btnlogin = new JButton("Log in");
    btnlogin.setFont(new Font("Lucida Grande", Font.BOLD, 14));
    btnlogin.setAlignmentX(Component.CENTER_ALIGNMENT);
    btnlogin.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            EmailValidator emailValidator = new EmailValidator();
            if(!emailValidator.validate(txtEmail.getText().trim())) {
                System.out.print("Invalid Email ID");
                validationtext.setText("Invalid Email");
            }
        }
    });
    btnlogin.setBounds(210, 432, 200, 48);
    btnlogin.setBackground(new Color(66, 185, 217));
    frame.getContentPane().add(btnlogin);

我已经尝试将 opaque 值设置为 true,但仍然无法正常工作。

【问题讨论】:

  • 对于JTextFieldJLabel,您只需将 opaque 设置为 true。
  • 问题已解决。谢谢@SWETAKESUR

标签: java swing jbutton jlabel jtextfield


【解决方案1】:

您只需要在设置背景颜色之前添加两行即可获得预期的结果:

  1. 通过编写以下代码将不透明值设置为真:btnlogin.setOpaque(true);
  2. 默认情况下,JFrame 中设置了边框,您必须根据自己的意愿进行更改。这里我使用的是 MatteBorder 的例子:btnlogin.setBorder(new MatteBorder(1, 1, 1, 1, (Color) new Color(0, 0, 0)));

然后你会得到你预期的结果。

【讨论】:

    【解决方案2】:

    这段代码实际上改变了按钮的颜色:

    btnlogin.setOpaque(true);
    btnlogin.setBorder(null);
    btnlogin.setBackground(Color.red); // Any color you wish
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-11
      • 2022-01-22
      • 1970-01-01
      • 2013-08-12
      相关资源
      最近更新 更多