日期:2014-05-20  浏览次数:20691 次

花几分钟帮忙看下JList问题。。
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;
import static java.awt.BorderLayout.*;



public class List {
  JFrame f=new JFrame();

   
  DefaultListModel model1 = new DefaultListModel();
  DefaultListModel model2 = new DefaultListModel();
   
  JList l=new JList(model1); 
  JList r=new JList(model2);
  JPanel p=new JPanel();
  JButton zuo=new JButton("<<");
  JButton you=new JButton(">>");
   

public void init()

  model1.addElement("选项1");
  model1.addElement("选项3");
  model2.addElement("选项2");
you.addActionListener(new B());

   
f.setLayout(new BorderLayout());
f.add(l,WEST);
f.add(r,EAST);
f.add(p,CENTER);
p.setLayout(new BorderLayout());
p.add(you,SOUTH);
p.add(zuo,NORTH);

f.pack();
f.setSize(500,300);
f.setVisible(true);

}

class B implements ActionListener{
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==you)

{
model1.removeElement(l.getSelectedIndex());

}
}
}
public static void main(String[] args)
{
new List().init();

}
}




我点击按钮“>>” 为什么l列表里面的选项不会删除掉?

------解决方案--------------------
删除函数调用错了吧、、
Java code
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;
import static java.awt.BorderLayout.*;

public class Tet2 
{
    JFrame f = new JFrame();

    DefaultListModel model1 = new DefaultListModel();
    DefaultListModel model2 = new DefaultListModel();

    JList l = new JList(model1);
    JList r = new JList(model2);
    JPanel p = new JPanel();
    JButton zuo = new JButton("<<");
    JButton you = new JButton(">>");

    public void init()
    {
        model1.addElement("选项1");
        model1.addElement("选项3");
        model2.addElement("选项2");
        you.addActionListener(new B());

        f.setLayout(new BorderLayout());
        f.add(l, WEST);
        f.add(r, EAST);
        f.add(p, CENTER);
        p.setLayout(new BorderLayout());
        p.add(you, SOUTH);
        p.add(zuo, NORTH);

        f.pack();
        f.setSize(500, 300);
        f.setVisible(true);

    }

    class B implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            if (e.getSource() == you)

            {
//                model1.clear();
                System.out.println(l.getSelectedIndex());
                model1.[color=#FF0000]removeElementAt[/color](l.getSelectedIndex());

            }
        }
    }

    public static void main(String[] args)
    {
        new Tet2().init();

    }
}

------解决方案--------------------
应该用removeElementAt,他接受index。你写的应该传对象。