package demo;
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
class ItemComponents extends JFrame{
JComboBox cb_channel; JList list_shows;
JLabel label; Object[] channel={"中央一台","中央二台"};
//用来作为组合框的条目
Object[][] shows={{"新闻联播","焦点访谈"},{"交换空间","经济与法","经济半小时"}}; //用来作为列表框的条目
public ItemComponents(){ super("按钮组件示例");
this.setBounds(100,100,250,180);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this. setLayout(new FlowLayout()); //添加组合框、列表框、标签
cb_channel=new JComboBox(channel);
this. add(cb_channel);
list_shows=new JList(shows[0]);
this. add(list_shows);
label=new JLabel("");
this. add(label); //为组合框注册监听器ItemListener
cb_channel.addItemListener(new ItemListener(){ //匿名内部类,静态组件与动态响应的功能在一个方法中实现,不是在两个方法中实现,更不是在两个类中实现.
public void itemStateChanged(ItemEvent e) {
int i=cb_channel.getSelectedIndex();
list_shows.setListData(shows[i]);
}
}); //为列表框注册事件监听器ListSelectionListener
list_shows.addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent e) {
String str=cb_channel.getSelectedItem().toString();
if (!list_shows.isSelectionEmpty()) //如果有选中的选项,则在label中显示该值
str+=" "+list_shows.getSelectedValue(); label.setText("您选择的是:"+str);
}
});
this.setVisible(true);
}
}
public class demo10 {
public static void main(String[] args) {
new ItemComponents();
}
}
JAVA图形用户界面
于 2023-09-26 16:15:53 首次发布