日期:2014-05-18  浏览次数:20832 次

java List 删除 单选
本帖最后由 fu755383249 于 2013-10-29 20:54:06 编辑
一个小程序,在窗口添加了两个List:te1,te2。分别向两个列表中添加值后,怎么判断想要删除的是那个列表中的值?我添加了两个动作监听器分别对他们进行监听,但对于List,动作监听需要双击列表中的值才会触发事件,单击不响应,能怎么解决?还有就是怎么设置使两个列表框中只能有一个项被选中?多谢!
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.*;
class Student extends JFrame implements ActionListener
{
Boolean a = true;
int b = 0; 
JLabel la1 = new JLabel("男生列表:                         ");
JLabel la2 = new JLabel("女生列表:                         ");
JLabel la3 = new JLabel("新学生: 姓名");
JButton bu1= new JButton("添加");
JButton bu2= new JButton("删除");
JRadioButton bu3 =new JRadioButton("男",true);
JRadioButton bu4 =new JRadioButton("女");
List te1= new List(8,false);
List te2= new List(8,false);
TextField tex = new TextField(5);
Student(String s)
{
super(s);
setIconImage(getToolkit().getImage("3.jpg"));
JPanel pa1 = new JPanel();
JPanel pa2 = new JPanel();
JPanel pa3 = new JPanel();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(400,250);
setVisible(true);
setLayout(new BorderLayout());
bu1.addActionListener(this);
bu2.addActionListener(this);
bu3.addActionListener(this);
bu4.addActionListener(this);
tex.addActionListener(this);
te1.addActionListener(this);
te2.addActionListener(this);
add(pa3,BorderLayout.NORTH);
add(pa1,BorderLayout.CENTER);
add(pa2,BorderLayout.SOUTH);
pa3.add(la1);
pa3.add(la2);
pa1.add(te1);
pa1.add(te2);
pa2.add(la3);
pa2.add(tex);
ButtonGroup bg =new ButtonGroup();
bg.add(bu3);
bg.add(bu4);
pa2.add(bu3);
pa2.add(bu4);
pa2.add(bu1);
pa2.add(bu2);

}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() ==bu3)a =true;
if(e.getSource() ==bu4)a =false;
if(e.getSource() ==bu1 && a == true)
{
if(tex.getText().length()>0){te1.add(tex.getText()+"\n");/*tex.setText("");*/}
else JOptionPane.showMessageDialog(null,"请输入姓名!");
}
if(e.getSource() ==bu1 && a == false)
{
if(tex.getText().length()>0){te2.add(tex.getText()+"\n");/*tex.setText("");*/}
else JOptionPane.showMessageDialog(null,"请输入姓名!");
}
if(e.getSource() ==te1 ){b = 1;}
if(e.getSource() ==te2 ){b = 2;}
if(e.getSource() ==bu2 )
{

if(b == 1 && te1.getSelectedIndex()!= -1)te1.remove(te1.getSelectedIndex());
else if(b == 2 && te2.getSelectedIndex()!= -1)te2.remove(te2.getSelectedIndex());
else JOptionPane.showMessageDialog(null,"请选择删除的项!");

}
}
}

public class StudentApp
{
public static void main (String []args)