近使用Java进行客户端编程,使用了大量的Swing控件,由于系统默认的边框无法满足项目的要求,不得不自己更改控件的边框样式,网上找了不少资料,本文对Swing编程边框(Border)的用法进行归纳,以便有着同样需求的朋友参考。
Swing客户端程序中的控件调用setBorder可以设置边框,setBorder是JComponent类的成员方法,其函数原型如下:
public void setBorder(Border border)
参数:
border
- 要为此组件呈现的边框
对参数Border对象的定义主要通过BorderFactory进行,这也是本文讨论的重点,根据API的解释:BorderFactory提供标准 Border
对象的工厂类。在任何可能的地方,此工厂类都将提供对已共享 Border
实例的引用。下面讨论具体的应用方法:
1. 首先展示程序的运行效果:
2. 下面列出程序的完整实现代码:
Java示例:
package Test;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class BorderDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("Swing边框演示-宋小生");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 2, 5, 10));
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JButton p1 = new JButton();
p1.setBorder(BorderFactory.createLineBorder(Color.red, 3));
p1.add(new JLabel("线边框"));
panel.add(p1);
JPanel p2 = new JPanel();
p2.setBorder(BorderFactory.createEtchedBorder());
p2.add(new JLabel("蚀刻边框"));
panel.add(p2);
JPanel p3 = new JPanel();
p3.setBorder(BorderFactory.createRaisedBevelBorder());
p3.add(new JLabel("斜面边框(凸)"));
panel.add(p3);
JPanel p4 = new JPanel();
p4.setBorder(BorderFactory.createLoweredBevelBorder());
p4.add(new JLabel("斜面边框(凹)"));
panel.add(p4);
JPanel p5 = new JPanel();
p5.setBorder(BorderFactory.createTitledBorder("标题"));
p5.add(new JLabel("标题边框"));
panel.add(p5);
JPanel p6 = new JPanel();
TitledBorder tb = BorderFactory.createTitledBorder("标题");
tb.setTitleJustification(TitledBorder.RIGHT);
p6.setBorder(tb);
p6.add(new JLabel("标签边框(右)"));
panel.add(p6);
JPanel p7 = new JPanel();
p7.setBorder(BorderFactory.createMatteBorder(1, 5, 1, 1, Color.yellow));
p7.add(new JLabel("花色边框"));
panel.add(p7);
JPanel p8 = new JPanel();
Border b1 = BorderFactory.createLineBorder(Color.blue, 2);
Border b2 = BorderFactory.createEtchedBorder();
p8.setBorder(BorderFactory.createCompoundBorder(b1, b2));
p8.add(new JLabel("组合边框"));
panel.add(p8);
JScrollPane scrollPane = new JScrollPane(panel);
scrollPane.setPreferredSize(new Dimension(300, 300));
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
到此,Java客户端Swing程序中控件的边框定义便介绍完了,本文中,我们演示了线边框、蚀刻边框、斜面边框、标题边框、组合边框的实际用法,希望对你有所帮助。