在Java Swing中更改JButton的边框颜色,以保留插图

时间:2019-05-15 21:10:18

标签: java swing border jbutton

我想更改Java Swing中JButton组件的边框颜色。

我尝试了以下方法:

package com.example.test;

import java.awt.Color;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test extends JFrame {

    public Test() {

        JPanel panel = new JPanel();
        JButton button1 = new JButton("Test Button 1");
        JButton button2 = new JButton("Test Button 2");
        button2.setBorder(BorderFactory.createLineBorder(Color.RED));

        panel.add(button1);
        panel.add(button2);

        this.add(panel);


        setSize(400, 400);
        setVisible(true);

    }

    public static void main(String[] args) {

        try {
            UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName() );
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedLookAndFeelException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        }
        Test t = new Test();
    }
}

这会生成两个按钮,在button2组件上,我尝试更改边框颜色,但删除了填充。无论如何,是否可以保留标准JButton的原始插图并仅更改颜色?

注意:我假设在分配新的Border时将移除插图。但是我对此不是100%肯定。

JButton Change Border Color

1 个答案:

答案 0 :(得分:4)

使用LineBorder代替创建CompoundBorder

button2.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createLineBorder(Color.RED, 1), 
            BorderFactory.createEmptyBorder(
                button1.getBorder().getBorderInsets(button1).top, 
                button1.getBorder().getBorderInsets(button1).left, 
                button1.getBorder().getBorderInsets(button1).bottom, 
                button1.getBorder().getBorderInsets(button1).right)));

我将BorderInsets换成button1,以使它们的大小相同。

我的答案基于this question的@MadProgrammer答案

enter image description here


顺便说一句,不要扩展JFrame,而是创建它的实例,如果您确实需要扩展组件,可以是JPanelExtends JFrame vs. creating it inside the program

也别忘了打电话

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

在您的JFrame实例上,以便您的程序在关闭时终止。

您还错过了将程序放置在EDT上的更多信息,请访问this answer