Java Tutorial/Swing/EmptyBorder
Содержание
14. Adding EmptyBorder to a JButton
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.border.Border;
public class AnEmptyBorder {
public static void main(String args[]) {
JFrame frame = new JFrame("Empty Borders");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Border emptyBorder = BorderFactory.createEmptyBorder(20, 20, 0, 0);
JButton emptyButton = new JButton("With Empty");
emptyButton.setBorder(emptyBorder);
JButton nonemptyButton = new JButton("Without Empty");
Container contentPane = frame.getContentPane();
contentPane.add(emptyButton, BorderLayout.NORTH);
contentPane.add(nonemptyButton, BorderLayout.SOUTH);
frame.pack();
frame.setSize(300, frame.getHeight());
frame.setVisible(true);
}
}
14. Creating and Setting an Empty Border from BorderFactory
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.border.EmptyBorder;
public class Main {
public static void main(String[] argv) {
EmptyBorder emptyBorder = (EmptyBorder) BorderFactory.createEmptyBorder();
JLabel component = new JLabel("label");
component.setBorder(emptyBorder);
}
}
14. Creating Empty using its Constructor
EmptyBorder is a border with nothing drawn in it.
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
public class EmptyBorderSample {
public static void main(String args[]) {
JFrame frame = new JFrame("Sample Borders");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Border emptyBorder = new EmptyBorder(5, 10, 5, 10);
JLabel aLabel = new JLabel("Bevel");
aLabel.setBorder(emptyBorder);
aLabel.setHorizontalAlignment(JLabel.CENTER);
frame.add(aLabel);
frame.setSize(400, 200);
frame.setVisible(true);
}
}
14. Empty Border
- The empty border leaves a transparent margin without any associated drawing.
- It"s an alternative to using the insets in AWT.
- The class requires that fields such as top, left, bottom, and right be specified.
- You can also use an insets object to create an empty border.
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class EmptyBorderForLabel extends JFrame {
public EmptyBorderForLabel() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JLabel label;
label = new JLabel("Empty");
label.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
panel.add(label);
getContentPane().add(panel);
pack();
}
public static void main(String[] args) {
EmptyBorderForLabel s = new EmptyBorderForLabel();
s.setVisible(true);
}
}