4 流佈局 FlowLayout & 邊界佈局 BorderLayout & 卡片佈局 CardLayout
阿新 • • 發佈:2021-01-09
技術標籤:JavaSwing基礎swingjava
流佈局 FlowLayout
流佈局 FlowLayout:
- 預設地,自左向右逐個排列
- 當一行排滿時,自動排到下一行
- setPreferredSize(); //設定每個控制元件的尺寸,這個方法繼承自JComponent
可以選擇居左、居右、居中對齊:
- new FlowLayout(FlowLayout.LEFT);
- new FlowLayout(FlowLayout.RIGHT);
- new FlowLayout(FlowLayout.CENTER);
邊界佈局 BorderLayout
邊界佈局 BorderLayout,把容器分為上、下、左、右、中五個區域。
setPreferredSize():
- 對於上下邊界,可以調整高度
- 對於左右邊界,可以調整寬度
卡片佈局 CardLayout
卡片佈局 CardLayout
卡片佈局:猶如多張疊在一起的卡片,每次只顯示一張卡片的內容
CardLayout的使用:
pane.setLayout(new CardLayout());
pane.add(c1, "name1");
pane.add(c2, "name2");
在新增控制元件時,關聯一個 string 作為名字,便於後面的控制:
例如,cardLayout.show(pane, “name1”);
程式碼:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Demo{
public static void main(String[] args) {
MyFrame frame = new MyFrame("Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
}
}
class MyFrame extends JFrame{
JComboBox<String> jcb = new JComboBox<>();
JPanel panel = new JPanel();
public MyFrame(String title) {
super(title);
Container contentPane = this.getContentPane();
contentPane.setLayout(new BorderLayout());
contentPane.add(jcb, BorderLayout.NORTH);
contentPane.add(panel, BorderLayout.CENTER);
jcb.addItem("第一個面板");
jcb.addItem("第二個面板");
panel.setLayout(new CardLayout());
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.add(new JButton("紅色"));
buttonPanel.add(new JButton("藍色"));
buttonPanel.add(new JButton("綠色"));
JPanel textPanel = new JPanel();
textPanel.setLayout(new FlowLayout());
textPanel.add(new JLabel("請輸入:"));
textPanel.add(new JTextField(10));
panel.add(buttonPanel, "button");
panel.add(textPanel, "text");
jcb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
panelChange();
}
});
panelChange();
}
public void panelChange() {
CardLayout cardLayout = (CardLayout)panel.getLayout();
if("第一個面板".equals(jcb.getSelectedItem())) {
cardLayout.show(panel, "button");
}else {
cardLayout.show(panel, "text");
}
}
}
輸出: