问题描述
我正在使用BlueJ,但遇到了问题。我有一个带有3个选项的组合框。每个选项都是一个字符串。这三个选项是日,周和月。我想做的是,如果选择的Day大于等于30(双精度)的变量,依此类推。有人可以帮我买吗,告诉我如何根据组合框中的所选选项为 emailvalue赋予值?
Im using BlueJ and I have run into problem. I have a combo box with 3 options. Each option is a string. The three options are Day, Week, and Month. What I want to do is if Day is picked than a variable equals 30 (a double) and so on. Can someone help me buy telling me how to give "emailvalue" a value based on the selected option in the combobox?
编辑:我将添加我的实际程序代码,该程序代码是每月的数据计算工具。确实会编译。
Im going to add my actual program code which is a monthly data calculater. It does compile.
这里是代码:
To solve this we must simply give it a default selected value by calling setSelectedItem(..) before its visible:
final JComboBox date1 = new JComboBox(date); date1.addActionListener(new ActionListener() {//add actionlistner to listen for change @Override public void actionPerformed(ActionEvent e) { String s = (String) date1.getSelectedItem();//get the selected item switch (s) {//check for a match case "Day": emailvalue = 30; break; case "Week": emailvalue = 4; break; case "Month": emailvalue = 1; System.out.println("Month selected, emailvalue:" + emailvalue); break; } } }); date1.setSelectedItem(date[0]);//set Day as default selected item/emailvalue关于代码的建议:
-
应在通过 SwingUtilities.invokeLater(Runnable r)块。
不要覆盖 paint( ..)的 JFrame 而不是添加 JPanel 并覆盖 paintComponent (图形g)
Dont override paint(..) of JFrame rather add JPanel and override paintComponent(Graphics g)
不要调用 setBounds 或 setSize 而不是使用适当的 LayoutManager 和/或覆盖 getPreferredSize() code> JPanel 并返回适合其内容的 Dimension s,而不是调用 pack()$ c $在 JFrame 上将c>设置为可见。
Dont call setBounds or setSize rather use an appropriate LayoutManager and/or override getPreferredSize() of JPanel and return Dimensions which fit its contents than call pack() on JFrame before setting it visible.
不要扩展 JFrame 不必要
不要在类上实现 ActionListener ,除非该类将用作一个类,或者必须公开其方法到其他班级
Dont implement ActionListener on the class unless the class will be used as one and or its methods must be exposed to other classes
这篇关于如何在ComboBox上使用ActionListener为变量赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!