Java ScrollPane和JList

时间:2015-06-28 12:08:41

标签: java swing jscrollpane jlist

我遇到了一个问题,似乎无法修复它。

我已经创建了两个列表,list1保留和在构造函数之外初始化的数组,而list2中没有任何内容。

我似乎无法解决的问题之一是,当我通过点击添加按钮在list1中选择一个单词时,它会显示在list2中,但出于某种奇怪的原因每次我尝试在list1中选择其他值,它会替换list2中已存在的值。我尝试了一切,没有任何效果。

我遇到的另一个问题是,list2当我输入一个比列表宽度更长的单词时,整个单词都没有显示出来。它只显示了单词末尾的几个单词和三个点。我在其中设置了滚动窗格。

任何人都可以帮我这个吗?

private String[] c = {"blue","white","cyan","darkGray","green","gray","black,"d","purple","orange","cyan"};    

public lala(){

model = new DefaultListModel();

list1 = new JList(c);
list1.setVisibleRowCount(10);
list1.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);   


b2 = new JButton("ADD");
b2.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        list.setListData(list1.getSelectedValues());

    }
});

b3 = new JButton("MOVE-->>");
b3.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
          model.addElement(field.getText());
          list.setModel(model);
          field.setText("");

    }
});

list2 = new JList();
list2.setFixedCellHeight(50);
list2.setFixedCellWidth(50);
list2.setVisibleRowCount(10);
list2.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

scroll = new JScrollPane(list2);
scroll.setPreferredSize(new Dimension(150,150));

field = new JTextField(19);
field.setToolTipText("Input Text Area Here");
field.setFont(new Font("Courier",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(new JScrollPane(list1));
panel.add(scroll);
add(panel);

   }
}

1 个答案:

答案 0 :(得分:2)

  

我似乎无法解决的问题之一是,当我通过单击添加按钮在list1中选择一个单词时,它会显示在list2中,但是每次我尝试在list1中选择另一个值时出于某种奇怪的原因,它取代了list2中已存在的值。

您的代码只执行您告诉它的操作:

b2.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        list.setListData(list1.getSelectedValues());    
    }
});

在这里,您在列表中调用setListData(...),它完全替换了新数据所包含的数据。而是获取JList的模型,只需在模型上调用addElement(...)

b2.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        DefaultListModel model = (DefaultListModel) list.getModel();
        model.addElement(list1.getSelectedValues());    
    }
});
  

我尝试了一切,没有任何效果。

抱歉,您可能希望将来避免这样说,因为它显然不是真的。拍摄,你所要做的就是阅读JList Tutorial因为它在那里得到了很好的解释。

关于,

  

另一个问题是,在list2中,当我输入一个比列表宽度更长的单词时,整个单词都没有显示出来。它只显示了单词末尾的几个单词和三个点。我在其中设置了滚动窗格。

在list2上调用setPrototypeCellValue(...),并传入一个足够大的String来保存它将接收的字符串。

修改
在最近的previous question中,您已经被告知有关DefaultListModel的addElement(...)方法,这让我感到头疼,并想知道您为什么不在这里使用它。