我想检查点击JComboBox
时选择的JButton
项。结果将放置在我执行的操作中累积的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();
}
}
答案 0 :(得分:0)
首先,您不需要addActionListener()
来获取txtField和cboAge
因为在那里执行动作时你没有做任何事情。
只需按钮即可。
这就是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);
}
}