19.下拉框、列表框
下拉框:JComboBox、addItem
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.gui.lesson6; 2 3 import javax.swing.*; 4 import java.awt.*; 5 6 public class TestComboBoxDemo1 extends JFrame { 7 8 public TestComboBoxDemo1() { 9 Container container = this.getContentPane(); 10 11 JComboBox status = new JComboBox(); 12 13 status.addItem(null); 14 status.addItem("正在热映"); 15 status.addItem("已下架"); 16 status.addItem("即将上映"); 17 18 container.add(status); 19 20 this.setVisible(true); 21 this.setSize(300, 350); 22 this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 23 } 24 25 public static void main(String[] args) { 26 new TestComboBoxDemo1(); 27 } 28 }
列表框:contents、JList
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.gui.lesson6; 2 3 import javax.swing.*; 4 import java.awt.*; 5 import java.util.Vector; 6 7 public class TestListBoxDemo1 extends JFrame { 8 9 public TestListBoxDemo1() { 10 Container container = this.getContentPane(); 11 12 //生成列表的内容,静态 13 //String[] contents = {"1", "2", "3"}; 14 //放一个引用,动态的添加 15 Vector contents = new Vector(); 16 //列表中需要放入内容 17 JList jList = new JList(contents); 18 19 contents.add("1"); 20 contents.add("2"); 21 contents.add("3"); 22 23 container.add(jList); 24 25 this.setVisible(true); 26 this.setSize(300, 300); 27 this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 28 } 29 30 public static void main(String[] args) { 31 new TestListBoxDemo1(); 32 } 33 }
应用场景:
- 下拉框:选择地区。或者一些单个选项,如果只有两个建议使用单选框按钮,如果超过两个,用下拉框去做,这样可以节省一些内存的布局。
- 列表:展示信息,一般是动态扩容。