首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2EE开发 >

java List 剔除 单选

2013-10-31 
javaList删除单选本帖最后由 fu755383249 于 2013-10-29 20:54:06 编辑一个小程序,在窗口添加了两个List:t

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)
{
new Student("男女生");
}
}

java
[解决办法]
本来感觉你这涉及到一个焦点转移的问题。。。不过我测试时候没发现有什么大的问题。你说的双击没感觉出来

至于两个表只能有一个值被选中。。
那很简单,构建一个索引值,存放被选择的对象的地址。
比如b1 4  表示b1表的第5个值。
选择下一个的时候,如果索引值不为空,则根据索引值取消选择
te1.deselect(4);取消te1表中对第五个值的选择
然后把索引值指向被选择的新值。



热点排行