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);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
);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
);JPanel 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
);}
}
總結
以上是生活随笔為你收集整理的java实用教程——组件及事件处理——设置组件的位置(相对于窗口具体位置和布局)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。