JButton更改默认边框

时间:2015-11-27 09:53:46

标签: java swing border jbutton look-and-feel

我正在使用SystemLookAndFeel,它在我的按钮周围设置了默认边框。

现在我想要一个黑色边框,但是当我设置边框时,它只是将我的新边框添加到默认边框周围,所以我有两个。

如何在不删除LookAndFeel的情况下更改或删除边框?

另外:我正在使用java 7和Win 8.1

1 个答案:

答案 0 :(得分:4)

在Windows 10上使用Java 8,我做了一点测试

Lots of buttons

正如您所看到的,关于我可以开展工作的唯一方法是使用setContentAreaFilled

一般问题是,许多外观并没有使用border属性,而是独立绘制自己的边框(因此setBorderPainted的原因),但外观和感觉对于Windows 10,只是想要与众不同

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.LineBorder;

public class ButtonTest {

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

    public ButtonTest() {
        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 class TestPane extends JPanel {

        public TestPane() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbc.fill = GridBagConstraints.HORIZONTAL;

            JButton btn = new JButton("Normal");
            add(btn, gbc);

            btn = new JButton("With border");
            btn.setBorder(new LineBorder(Color.BLACK));
            add(btn, gbc);

            btn = new JButton("borderPainted false");
            btn.setBorderPainted(false);
            btn.setBorder(new LineBorder(Color.BLACK));
            add(btn, gbc);

            btn = new JButton("contentArea false");
            btn.setContentAreaFilled(false);
            btn.setBorder(new LineBorder(Color.BLACK));
            add(btn, gbc);

            btn = new JButton("focusPained false");
            btn.setContentAreaFilled(false);
            btn.setFocusPainted(false);
            btn.setBorder(new LineBorder(Color.BLACK));
            add(btn, gbc);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

    }

}