valueLabel.setFont(displayFont); valueField = new JTextField(, 6); valueField.setFont(displayFont); JPanel valuePanel = new JPanel(); valuePanel.setBackground(Color.white); Border valuePanelBorder = BorderFactory. createTitledBorder(JList选择); valuePanel.setBorder(valuePanelBorder); valuePanel.add(valueLabel); valuePanel.add(valueField); content.add(valuePanel, BorderLayout.SOUTH); pack(); setVisible(true); } private class ValueReporter implements ListSelectionListener { public void valueChanged(ListSelectionEvent event){ if (!event.getValueIsAdjusting()) valueField.setText( jl.getSelectedValue().toString()); } } 程序的运行结果如图所示。 9.3.8 组合框(JComboBox) 在Java语言中,组合框有可编辑的和不可编辑的两种不同的形式。缺省是不可编辑的组合框。这里对不可编辑的组合框进行介绍。组合框用于在多项选择中选择一项的操作。在未选择组合框时,组合框显示为带按钮的一个选项的形式,当对组合框按键或单击时,组合框会打开可列出多项的一个列表,提供给用户选择。 类JComboBox提供组合框的支持,其相关类的层次如下: javax.swing.Jcomponent └ javax.swing.JComboBox 类JComboBox()的构造方法有四种,常用的有两种: JComboBox()用缺省的数据模式创建组合框。 JComboBox(Object[] items)用指定数组创建组合框。 创建组合框后,可用方法setSelectedIndex(int anIndex)选定指定下标anIndex处的项目; 可用方法getSelectedIndex()获得选定项目的数组下标;可用方法getSelectedItem()获取选定的项目。 组合框事件是ActionEvent事件。事件处理方法与其他处理同类事件的方法类似。 【例9.19】使用JComboBox。 import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JComboBoxDemo extends JPanel { JLabel picture,text; public JComboBoxDemo() { String[] pStrings = {cup,cat,boy,girl}; JComboBox pList = new JComboBox(pStrings); pList.setSelectedIndex(0); pList.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JComboBox cb = (JComboBox)e.getSource(); String pName = (String)cb.getSelectedItem(); picture.setIcon(new ImageIcon(images/“ + pName + .gif)); text.setText(pName); text.setHorizontalAlignment(JLabel.CENTER); } }); picture = new JLabel(new ImageIcon(images/ + pStrings[pList.getSelectedIndex()] +.gif)); JLabel(String text, int horizontalAlignment)创建一个带文字和指定水平对齐方式的标签。 其中,horizontalAlignment水
原创力文档

文档评论(0)