使用BorderLayout布局,就可以了!
如果想美观的话,可以结合其他布局(如GridBagLayout),有问题再问,good luck!~
例子:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class MyJPanel extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public MyJPanel() {
// TODO Auto-generated constructor stub
Container c = this.getContentPane();
//东西南北中布局,上北下南左西右东
c.setLayout(new BorderLayout());
JPanel jp = new JPanel();
JTextArea jta = new JTextArea("中间");
jp.add(jta);
c.add(jp, BorderLayout.CENTER);
c.add(new JButton("东边"), BorderLayout.EAST);
c.add(new JButton("西边"), BorderLayout.WEST);
c.add(new JButton("南边"), BorderLayout.SOUTH);
c.add(new JButton("北边"), BorderLayout.NORTH);
this.setSize(300, 300);
this.setVisible(true);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args) {
new MyJPanel();
}
}
设置JPanel在JFrame的正中间显示的程序片段:
JFrame jf=new JFrame();
JPanel jp=new JPanel();
jf.add(jp,BorderLayout.CENTER);
jf.setSize(300,300);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
setboundes()方法应该可以把