【问题标题】:JComboBox with JButton into TextFieldJComboBox 与 JButton 进入 TextField
【发布时间】:2016-03-10 00:20:14
【问题描述】:

我想检测单击JButton 时选择了哪些JComboBox 项目。结果将放在我在执行的操作中堆积的TextField 中。

例如,当我选择一个合适的数字时,它将使用 JButton 分类,结果将显示在 TextField 上。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class mFrame extends JFrame implements ActionListener
{
JLabel lblAge = new JLabel("Age");
JComboBox cboAge = new JComboBox();
JButton btnClass = new JButton("Classification");
JTextField txtField = new JTextField();
JButton btnClose = new JButton("Close");

public mFrame()
{
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(null);
    setSize(400,200);

    add(lblAge);
    add(cboAge);
    add(btnClass);
    add(txtField);
    add(btnClose);

    lblAge.setBounds(10,10,100,20);
    cboAge.setBounds(140,10,120,20);
    btnClass.setBounds(10,30,120,20);
    txtField.setBounds(140,30,120,20);
    btnClose.setBounds(200,105,70,20);
    for (int j = 10; j < 101; j++) cboAge.addItem(new Integer(j));

    cboAge.addActionListener(this);
    btnClass.addActionListener(this);
    txtField.addActionListener(this);
    btnClose.addActionListener(this);
    setVisible(true);
}
public void actionPerformed(ActionEvent age)
{
    //if (age.getSource() == btnClass)
    {
        //
    if (age.getSource() == btnClose)
    {
        System.exit(0);
    }
}
}
}
  class StartHere
{
    public static void main(String [] args)
    {
        new mFrame();
    }
}

【问题讨论】:

标签: java jbutton jcombobox


【解决方案1】:

首先,对于 txtField 和 cboAge,您不需要 addActionListener() 因为在那里执行操作时您没有做任何事情。 只为按钮做。

这就是actionPerformed() 的样子(注意:我将ActionEvent age 更改为ActionEvent e

public void actionPerformed(ActionEvent e){
    if (e.getSource() == btnClass){
        String selectedValue = cboAge.getSelectedItem().toString();

        // if you need it as integer...
        int age = Integer.parseInt(selectedValue);

        // do your classification processing... assuming output value is assigned in String result.

        //ex for classification processing:
        String result = "";
        if(age>=10 && age<=19){
              result = "Teenage";
        }else if(age>=20 && age<=28){
              result = "blah blah";
        }//... and so on...

        txtField.setText(result);
    }else if (e.getSource() == btnClose){
        System.exit(0);
    }
}

【讨论】:

  • 谢谢你的回答,我试过了,但是如果我在组合框中选择的每个数字都有特定的分类怎么办?例如,当我单击 10 到 19 时,分类结果将是青少年,当我单击 20 到 30 等时,分类结果将是成人等!我只能得到 1 个数字的结果!抱歉,我对编程还是很陌生,需要帮助来探索更多
  • 这就是我所说的do your classification processing... 的意思,您可以将age 与您拥有的类别进行比较,例如if(age&gt;=10 &amp;&amp; age&lt;=19){result = "Teenage";} ...等等
  • 二元运算符 '>=' T_T 的操作数类型错误
  • 可能在我的 JCreator 中,明天在学校试试这个
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多