Java Tutorial/Swing/No Layout
Содержание
Laying Out Components Using Absolute Coordinates
import javax.swing.JButton;
import javax.swing.JPanel;
public class Main {
public static void main(String[] argv) throws Exception {
JButton component = new JButton();
JPanel panel = new JPanel(null);
component.setBounds(1, 1, 100, 100);
panel.add(component);
}
}
No LayoutManager: Absolute positioning
To absolute positioning components, passing null to the setLayout method of a container.
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class NoLayoutTest extends JFrame {
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("NoLayout Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
JLabel label = new JLabel("First Name:");
label.setBounds(20, 20, 100, 20);
JTextField textField = new JTextField();
textField.setBounds(124, 25, 100, 20);
frame.add(label);
frame.add(textField);
frame.setSize(300, 100);
frame.setVisible(true);
}
}
Without layout manager, we position components using absolute values.
import javax.swing.JButton;
import javax.swing.JFrame;
public class Absolute {
public static void main(String[] args) {
JFrame f = new JFrame();
f.setLayout(null);
JButton ok = new JButton("OK");
ok.setBounds(50, 150, 80, 25);
JButton close = new JButton("Close");
close.setBounds(150, 150, 80, 25);
f.add(ok);
f.add(close);
f.setSize(300, 250);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
Z Order
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ZOrder extends JPanel {
public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(new ZOrder());
f.setSize(400, 300);
f.setVisible(true);
}
public ZOrder() {
setLayout(null);
JButton first = new JButton("This button is added first");
first.setBounds(20, 50, 200, 30);
add(first);
JButton second = new JButton("This button is added second");
second.setBounds(120, 65, 200, 30);
add(second);
}
}