如何使用 Java 中的 BorderFactory 实现不同的边框?\
awtjavaobject oriented programmingprogrammingswing
BorderFactory 是一个 Factory 类,它在 Java 中提供不同类型的边框。
边框类型
- BevelBorder:此边框绘制 凸起 或 降低 斜角边缘。
- EmptyBorder:它不进行任何绘制,但会占用空间。
- EtchedBorder:降低蚀刻边框 呈现矩形外观,而凸起蚀刻边框呈现矩形外观。边框 看起来像屏幕的表面。
- LineBorder:在组件周围绘制一个简单的矩形。我们可以在LineBorder 构造函数中指定线条的颜色和宽度。
- MatteBorder:我们可以创建一个具有特定颜色的MatteBorder ,并指定组件左侧、顶部、右侧和底部边框的大小。MatteBorder 还允许我们传递用于绘制边框的图标。这可以是图像(ImageIcon)或Icon 接口的任何其他实现。
- TitledBorder:带有标题的常规边框。 TitledBorder实际上并不绘制边框;它只是与另一个边框对象一起绘制标题。此边框类型对于在复杂界面中对不同控件集进行分组特别有用。
- 组件边框:包含其他两个边框的边框。如果我们想将组件封闭在 EmptyBorder中,然后在其周围放置一些装饰物(例如 EtchedBorder 或 MatteBorder),这尤其方便。
示例
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; public class BorderFactoryMain { public static void main(String[] args) { SwingUtilities.invokeLater(run); } static Runnable run = new Runnable() { @Override public void run() { BorderFactoryTest test; test = new BorderFactoryTest(); test.setVisible(true); } }; public static class BorderFactoryTest extends JFrame { public BorderFactoryTest() { setTitle("BorderFactory Test"); setSize(350, 400); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new FlowLayout()); add(createBorderedPanel(BorderFactory.createRaisedBevelBorder(), "createRaisedBevelBorder()")); add(createBorderedPanel(BorderFactory.createBevelBorder(BevelBorder.LOWERED), "createBevelBorder(BevelBorder.LOWERED)")); add(createBorderedPanel(BorderFactory.createBevelBorder(BevelBorder.RAISED), "createBevelBorder(BevelBorder.RAISED)")); add(createBorderedPanel(BorderFactory.createCompoundBorder(BorderFactory. createBevelBorder(BevelBorder.RAISED),BorderFactory.createBevelBorder(BevelBorder.LOWERED)), "createCompoundBorder(RAISED, LOWERED)")); add(createBorderedPanel(BorderFactory.createEtchedBorder(), "createEtchedBorder()")); add(createBorderedPanel(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "createEtchedBorder(EtchedBorder.LOWERED)")); add(createBorderedPanel(BorderFactory.createEtchedBorder(EtchedBorder.RAISED), "createEtchedBorder(EtchedBorder.RAISED)")); add(createBorderedPanel(BorderFactory.createEtchedBorder(Color.lightGray, Color.yellow), "createEtchedBorder(Color.lightGray, Color.yellow)")); add(createBorderedPanel(BorderFactory.createLineBorder(Color.red), "createLineBorder(Color.red)")); add(createBorderedPanel(BorderFactory.createLineBorder(Color.blue, 5), "createLineBorder(Color.blue, 5)")); add(createBorderedPanel(BorderFactory.createDashedBorder(null), "createDashedBorder(null)")); setLocationRelativeTo(null); } } private static JPanel createBorderedPanel(Border b, String name) { JLabel label = new JLabel(name); JPanel panel = new JPanel(); panel.setBorder(b); panel.add(label); return panel; } }