將JTextField輸入的字串,轉為JComboBox元件的選項,
選項字串不可重複,再將JComboBox元件選到的選項顯示在JLabel元件上。
import javax.swing.SwingUtilities; import javax.swing.JPanel; import javax.swing.JFrame; import javax.swing.JLabel; import java.awt.Rectangle; import javax.swing.JComboBox; import javax.swing.JTextField; import javax.swing.JButton; public class test extends JFrame { private static final long serialVersionUID = 1L; private JPanel jContentPane = null; private JLabel lblResult = null; private JComboBox cbxList = null; private JTextField txtInput = null; private JButton btnAdd = null; private JComboBox getCbxList() { if (cbxList == null) { cbxList = new JComboBox(); cbxList.setBounds(new Rectangle(49, 21, 81, 27)); cbxList.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent e) { lblResult.setText(cbxList.getSelectedItem().toString()); } }); } return cbxList; } private JTextField getTxtInput() { if (txtInput == null) { txtInput = new JTextField(); txtInput.setBounds(new Rectangle(51, 79, 83, 22)); } return txtInput; } private JButton getBtnAdd() { if (btnAdd == null) { btnAdd = new JButton(); btnAdd.setBounds(new Rectangle(176, 77, 62, 23)); btnAdd.setText("add"); btnAdd.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent e) { boolean flag=true; for (int i=0;i if (txtInput.getText().equals(cbxList.getItemAt(i))){ flag = false; break; } } if (flag){ cbxList.addItem(txtInput.getText()); } } }); } return btnAdd; } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { test thisClass = new test(); thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); thisClass.setVisible(true); } }); } public test() { super(); initialize(); } private void initialize() { this.setSize(300, 200); this.setContentPane(getJContentPane()); this.setTitle("JFrame"); } private JPanel getJContentPane() { if (jContentPane == null) { lblResult = new JLabel(); lblResult.setBounds(new Rectangle(175, 21, 67, 25)); lblResult.setText(""); jContentPane = new JPanel(); jContentPane.setLayout(null); jContentPane.add(lblResult, null); jContentPane.add(getCbxList(), null); jContentPane.add(getTxtInput(), null); jContentPane.add(getBtnAdd(), null); } return jContentPane; } }
全站熱搜
留言列表