改变JButton的颜色而不改变其形状

时间:2017-02-01 21:57:03

标签: java swing

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

JButton button = new JButton();

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

为了进行更改,我必须添加:

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

然而,这会移除边缘周围的曲线,从而改变按钮的形状。有没有办法简单地改变颜色并保留其他属性?另一个例子是在没有改变颜色的情况下按下按钮时颜色变暗(变暗)。

以下是一些代码,用于说明两个按钮之间的区别:

    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);
}

由于

2 个答案:

答案 0 :(得分:0)

我只是测试了以下内容:

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。如果您发现它不起作用,请告诉我。您能否显示白色按钮或失败按钮的结果(如果它仍然无效)?

答案 1 :(得分:-1)

也许您的代码中还有其他内容。我改变了一个小例子,颜色只用setBackground(Color)使用常规Button和JButton改变。请参阅以下内容......

public static void main(String[] args) {
    Frame frame = new Frame();
    Panel panel = new Panel();
    Button closeButton = new Button("Close");
    closeButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            frame.setVisible(false);
            frame.dispose();
        }           
    });
    closeButton.setBackground(Color.decode("#00a5ff"));
    panel.add(closeButton);
    frame.add(panel);
    frame.setSize(200, 100);
    frame.setLocation(200, 50);
    frame.setVisible(true);
}