改变 JButton 的颜色而不改变它的形状 [英] Change color of JButton without changing its shape

查看:63
本文介绍了改变 JButton 的颜色而不改变它的形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过以下方式更改 JButton 的颜色:

I want to change the color of JButton by:

JButton button = new JButton();

button.setBackground(Color.decode("#00a5ff"));

为了发生变化,我必须补充:

In order for change to occur, I have to add:

button.setOpaque(true);
button.setBorderPainted(false);

然而,这会移除边缘周围的曲线,从而改变按钮的形状.有没有一种方法可以简单地更改颜色并保留其他属性?另一个例子是当你按下一个按钮而没有改变它的颜色时颜色的改变(变暗).

However, this remove the curves around the edges and thus changes the shape of the button. Is there a way to just simply change to color and keep the other properties? Another example is the changing of color (getting darker) when you press a button without having changed its color.

下面是一些代码,说明了两个按钮之间的区别:

Here is some code that illustrates the difference between the two buttons:

    public static void main(String[] args) {
    JFrame frame = new JFrame("frame");
    frame.setSize(new Dimension(300, 300));
    JButton button1 = new JButton();
    JButton button2 = new JButton();

    button1.setPreferredSize(new Dimension(100,100));
    button2.setPreferredSize(new Dimension(100,100));
    button2.setBackground(Color.decode("#00a5ff"));
    button2.setBorderPainted(false);
    button2.setOpaque(true);

    JPanel pane1 = new JPanel(new FlowLayout());
    JPanel pane2 = new JPanel(new FlowLayout());

    pane1.add(button1);
    pane2.add(button2);
    frame.add(pane1, BorderLayout.WEST);
    frame.add(pane2, BorderLayout.EAST);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

谢谢

推荐答案

我实际上只是测试了以下内容:

I literally just tested the following:

JFrame frame = new JFrame("frame");
frame.setSize(new Dimension(300, 300));
JButton button = new JButton();

button.setBackground(Color.decode("#00a5ff"));
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

它似乎有效,但我正在使用 Ubuntu Studio 16.04.如果您发现它不起作用,请告诉我.能否请您显示您的白色按钮或失败按钮的结果(如果它仍然不起作用)?

It seemed to work, but I am working on Ubuntu Studio 16.04. If you notice that it does not work, then let me know. Could you please show the result of your white button or your failed button (if it still doesn't work)?

这篇关于改变 JButton 的颜色而不改变它的形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆