1:
相对于窗口的具体位置
关键点:
JButton组件添加到JPanel时,如果想自己位置,需要对JPanel进行如下设置,才能自定义按钮位置
需要将组件添加到画板上去,才可以设置组件的相对具体位置
button1.setBounds(20, 200, 100, 100);//按钮的位置为(20,200),大小为(100,100)
import javax.swing.*;
import java.awt.*;public class win extends JFrame{public static void main(String []args){win w = new win();}public win(){init();this.setTitle("多个组件的位置相对于窗口的具体位置");this.setBounds(100,200,500,500);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setVisible(true);}public void init(){JPanel panel1 = new JPanel();panel1.setLayout(null);JButton button1= new JButton("JButton1");button1.setForeground(Color.BLUE);//设置按钮的颜色button1.setBounds(20, 200, 100, 100);//按钮的位置为(20,200)//大小为(100,100)panel1.add(button1);JButton button2= new JButton("JButton2");button2.setForeground(Color.GREEN);button2.setBounds(20, 50, 100, 100);panel1.add(button2);this.add(panel1);}
}
建立两个面板
在面板上进行按钮位置的操作
2:
边界布局
import java.awt.*;
import javax.swing.*;
public class win extends JFrame{public static void main( String [] args){win w = new win();}public win(){init();this.setTitle("多个组件的位置");this.setBounds(200,200,500,300);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setVisible(true);}public void init(){//设置窗口的背景颜色Container con=this.getContentPane();//得到内容窗格con.setBackground(Color.gray);//设置整体布局 this.setLayout(new BorderLayout(10,10));//设置两个画板JPanel panel1 = new JPanel(new BorderLayout(5,5));JButton button1= new JButton("JButton1");button1.setForeground(Color.BLUE);//设置按钮的颜色panel1.add(button1,BorderLayout.EAST);//将按钮添加到画板1中去JButton button2= new JButton("JButton2");button2.setForeground(Color.GREEN);panel1.add(button2,BorderLayout.CENTER);JButton button3= new JButton("JButton3");button3.setForeground(Color.pink);panel1.add(button3,BorderLayout.NORTH);JButton button4= new JButton("JButton4");button4.setForeground(Color.ORANGE);panel1.add(button4,BorderLayout.SOUTH);JButton button5= new JButton("JButton5");panel1.add(button5,BorderLayout.WEST);//画板2JPanel panel2 = new JPanel(new BorderLayout(5,5));JTextField text = new JTextField(10);JLabel label = new JLabel("标签:代码书写者");panel2.add(text,BorderLayout.NORTH);panel2.add(label,BorderLayout.SOUTH);//将两个画板添加到窗口中去this.add(panel1,BorderLayout.NORTH);this.add(panel2,BorderLayout.SOUTH);}}
3:
将窗口的布局更改为流式布局后,在窗口上就可以添加多个组件了
import javax.swing.*;
import java.awt.*;public class win extends JFrame{public static void main(String []args){win w = new win();}public win(){init();this.setTitle("多个组件的位置相对于窗口的具体位置");this.setBounds(100,200,500,500);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setVisible(true);}public void init(){this.setLayout(new FlowLayout());this.setLayout(null);JButton button1= new JButton("JButton1");button1.setForeground(Color.BLUE);//设置按钮的颜色button1.setBounds(20, 200, 100, 100);this.add(button1);JButton button2= new JButton("JButton2");button2.setForeground(Color.GREEN);button2.setBounds(20, 50, 150, 150);this.add(button2);}
}