《Java核心技术I》Swing中的边框
边框
BorderFactory静态方法创建边框,凹斜面,凸斜面,蚀刻,直线,蒙版,空白。
边框添加标题,BorderFactory.createTitledBorder
组合边框,BorderFactory.createCompoundBorder
JComponent的setBorder方法添加边框到组件。
package swing;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.border.Border;
import javax.swing.border.MatteBorder;
public class BorderTest {
private static JPanel buttonPanel = new JPanel();
private static ButtonGroup buttonGroup = new ButtonGroup();
public static void main(String[] args) {
JFrame frame = new JFrame("边框");
addRadioButton("凹斜面", BorderFactory.createLoweredBevelBorder());
addRadioButton("凸斜面", BorderFactory.createRaisedBevelBorder());
addRadioButton("蚀刻", BorderFactory.createEtchedBorder());
addRadioButton("直线", BorderFactory.createLineBorder(Color.BLUE));
addRadioButton("蒙版", BorderFactory.createMatteBorder(1, 1, 1, 1, Color.RED));
addRadioButton("空白", BorderFactory.createEmptyBorder());
frame.add(buttonPanel,BorderLayout.CENTER);
frame.setSize(600, 400);
//初始打开为屏幕中央
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension screenSize = toolkit.getScreenSize();
int screenWidth = (int) screenSize.getWidth();
int screenHeight = (int) screenSize.getHeight();
//计算窗口位置
int x = (screenWidth - frame.getWidth())/2;
int y = (screenHeight - frame.getHeight())/2;
frame.setLocation(x, y);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void addRadioButton(String name,Border border) {
boolean selected = name.equals("空白");
var button = new JRadioButton(name, selected);
buttonGroup.add(button);
Border titled = BorderFactory.createTitledBorder(border, name);
buttonPanel.setBorder(titled);
buttonPanel.add(button);
ActionListener listener = e -> buttonPanel.setBorder(titled);;
button.addActionListener(listener);
}
}