Java6学习笔记22——在Swing中不使用Layout管理器直接描绘窗口

import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.Container;
import java.awt.Insets;
import java.awt.Dimension;
import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class XYLayout extends JFrame implements ActionListener {
public static void main(String arg[]) {
new XYLayout();
}
public XYLayout() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
} );
buildFrame();
setLocation(250,150);
setVisible(true);
}
private void buildFrame() {
JButton button;
Dimension size;

Container pane = getContentPane();
pane.setLayout(null);

Insets insets = pane.getInsets();

button = new JButton("first");
size = button.getPreferredSize();
button.setBounds(25 + insets.left,15 + insets.top,
size.width,size.height);
pane.add(button);

button = new JButton("second");
size = button.getPreferredSize();
button.setBounds(55 + insets.left,120 + insets.top,
size.width,size.height);
pane.add(button);

button = new JButton("Exit");
size = button.getPreferredSize();
button.addActionListener(this);
button.setBounds(150 + insets.left,45 + insets.top,
size.width + 50,size.height + 20);
pane.add(button);

int width = 300 + insets.left + insets.right;
int height = 200 + insets.top + insets.bottom;
setSize(width,height);
}
public void actionPerformed(ActionEvent e) {
String selection = e.getActionCommand();
if(selection.equals("Exit")) {
System.exit(0);
}
}
}

你可能感兴趣的:(java,swing)