繁体   English   中英

在Java Swing中更改JButton的边框颜色,保留insets

[英]Change Border Color of a JButton in Java Swing preserving the insets

我想在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的原始插图,只是改变颜色?

注意:我假设在分配新边框时删除了插图。 但我并非百分百肯定。

JButton更改边框颜色

使用CompoundBorder而不是创建LineBorder

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

我为button1BorderInsets ,以便它们都具有相同的大小。

我的回答是基于@MadProgrammer对这个问题的回答

在此输入图像描述


顺便说一下,不要扩展JFrame ,而是创建它的实例,如果你真的需要扩展一个组件,那就是JPanel扩展JFrame而不是在程序中创建它

也别忘了打电话

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

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

而且你错过了把你的节目放在EDT上,在这个答案上看到更多这个

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM