java jlist 鼠标事件,Java JList问题

Ok what am trying to do is allow the user to make a list for themselves, what ever they type in in the TextField the output of that will be shown in the Jlist but my problem here is that if i type in another word to the TextField the output of that is either appending or replacing the other word that was already there it suppose to go beneath the other word and save there can anyone help me please??

public lala(){

b2 = new JButton("ADD");

b2.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

model.removeAllElements();

list1.setModel(model);

}

});

b3 = new JButton("MOVE");

b3.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

model = new DefaultListModel();

model.addElement(field.getText());

list.setModel(model);

field.setText("");

}

});

list = new JList();

list.setFixedCellHeight(10);

list.setFixedCellWidth(10);

list.setVisibleRowCount(10);

list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

scroll = new JScrollPane(list);

scroll.setPreferredSize(new Dimension(100,100));

field = new JTextField(19);

field.setToolTipText("Input Text Area Here");

field.setFont(new Font("Corier",Font.BOLD,20));

field.setBackground(Color.BLACK);

field.setForeground(Color.RED);

field.setDragEnabled(true);

panel = new JPanel();

panel.setBackground(Color.BLACK);

panel.add(b3);

//panel.add(b2);

panel.add(field);

panel.add(scroll);

add(panel);

}

}

解决方案

Your issue is that you are creating a whole new DefaultListModel on each Action in the event listener.

You need to declare a global DefaultListModel and addElement() to it as your user presses the button.

This might be able to help point you in the right direction:

public class Examples {

private DefaultListModel modelList;

private JList list;

private JButton button;

private JTextField field;

public Examples() {

modelList = new DefaultListModel();

list = new JList(modelList);

button = new JButton("Add To List");

field = new JTextField();

init();

}

private void init() {

button.addActionListener((ActionEvent e) -> {

modelList.addElement(field.getText());

// !! list.setModel(modelList);

field.setText("");

});

}

}

Here, we have registered our DefaultListModel as a instance field in our Examples class.

Then we register a new listener using the lambda expression, and have the modelList updated with the field's text, and set the modelList as the model for the JList.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值