如何使Jbutton周围的边框更厚?

时间:2015-03-20 05:25:37

标签: java swing jbutton

我正在构建的GUI界面上有以下JButton。

http://i.imgur.com/MucqvGj.png

我想让按钮周围的边框更厚,以便从背景中脱颖而出。是否可以在Java中执行此操作?

2 个答案:

答案 0 :(得分:5)

您只需使用LineBorder

即可
JButton btn = ...;
btn.setBorder(BorderFactory.createLineBorder(Color.BLACK, 4));

请查看How to Use Borders了解更多详情和想法

根据模型状态更新边框状态

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.Border;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public static class TestPane extends JPanel {

        protected static final Border NORMAL_BORDER = BorderFactory.createLineBorder(Color.BLACK, 4);
        protected static final Border ROLLOVER_BORDER = BorderFactory.createLineBorder(Color.RED, 4);

        public TestPane() {

            JButton btn = new JButton("Click me!");
            btn.setContentAreaFilled(false);
            btn.setBorder(NORMAL_BORDER);
            btn.getModel().addChangeListener(new ChangeListener() {
                @Override
                public void stateChanged(ChangeEvent e) {
                    if (btn.getModel().isRollover()) {
                        btn.setBorder(ROLLOVER_BORDER);
                    } else {
                        btn.setBorder(NORMAL_BORDER);
                    }
                }
            });

            setLayout(new GridBagLayout());
            add(btn);

        }

    }

}

答案 1 :(得分:2)

首先创建Border -

Border border = new LineBorder(Color.WHITE, 13);

然后创建JButton并设置Border -

JButton button = new JButton("Button Name");
button.setBorder(border);  

希望它会有所帮助。
非常感谢。