Java中已弃用代码的替代方案?

时间:2015-09-24 03:14:48

标签: java user-interface deprecated

我目前正在从一本名为&#34的书开始学习GUI应用程序;从Java"开始。我已经尝试过一篇关于JList的作者代码示例,但事实证明ButtonListener中的getSelectedValues()已经被弃用了。我只是想问一下你们是否知道该特定代码的替代品。虽然代码仍然适用,但我仍然想知道替代方案。

以下是代码:

package Practice; 
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Practice1 extends JFrame{
private JPanel monthPanel;
private JPanel selectedMonthPanel;
private JPanel buttonPanel;
private JList monthList;
private JList selectedMonthList;
private JScrollPane scrollPane1;
private JScrollPane scrollPane2;
private JButton button;

private String[]months = {"January","February","March","April",
        "May","June","July","August","September","October",
        "November","December"};

public Practice1(){
    setTitle("List Demo");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(new BorderLayout());
    buildMonthPanel();
    buildSelectedMonthPanel();
    buildButtonPanel();
    add(monthPanel,BorderLayout.NORTH);
    add(selectedMonthPanel,BorderLayout.CENTER);
    add(buttonPanel,BorderLayout.SOUTH);
    pack();
    setVisible(true);
}

private void buildMonthPanel(){
    monthPanel = new JPanel();
    monthList = new JList(months);
    monthList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    monthList.setVisibleRowCount(6);
    scrollPane1 = new JScrollPane(monthList);
    monthPanel.add(scrollPane1);
}

private void buildSelectedMonthPanel(){
    selectedMonthPanel = new JPanel();
    selectedMonthList = new JList();
    selectedMonthList.setVisibleRowCount(6);
    scrollPane2 = new JScrollPane(selectedMonthList);
    selectedMonthPanel.add(scrollPane2);
}

private void buildButtonPanel(){
    buttonPanel = new JPanel();
    button = new JButton("Get Selections");
    button.addActionListener(new ButtonListener());
    buttonPanel.add(button);
}

private class ButtonListener implements ActionListener{
    public void actionPerformed(ActionEvent e){
        Object[]selections = monthList.getSelectedValues();
        selectedMonthList.setListData(selections);
    }
}

public static void main(String[]args){
    new Practice1();
}
}

2 个答案:

答案 0 :(得分:0)

将其替换为以下

monthList.getSelectedValuesList().toArray()

有关详细信息,请参阅This post

答案 1 :(得分:0)

在文档中,它表示已弃用getSelectedValues,并表示此方法已替换为 getSelectedValuesList!如果您查看了文档,您就会知道这一点。下次遇到这类问题时,只需查看文档即可。这是文档:

http://docs.oracle.com/javase/7/docs/api/javax/swing/JList.html#getSelectedValuesList()

请注意,新方法会返回List<E>,而不是Object[]。您只需使用toArray方法将其转换为Object[]