JList具有自己的数据模型

时间:2016-01-10 21:40:42

标签: java swing jlist

我正在尝试弄清楚如何正确使用JList。我正在努力将列表的使用与我自己的类/数据模型结合起来。 我的目标是在单独的类中提取列表,并从多个操作(按钮事件/动作侦听器)更改列表中显示的数据。

例如:如果用户选择了兼容的CSV文件,则列表应显示该文件的内容。该文件本身包含一个简单的播放列表,其复合如下:艺术家;标题;文件路径

如果用户将另一首歌曲添加到播放列表,则该列表应“刷新”。我读过一些关于“FireContents ......”的内容,但我首先想知道如何正确使用这些列表。

我要添加源代码的相关部分。任何帮助&建议表示赞赏。

public class MusicTrack implements project.model.Track{
private String strArtist;
private String strTitle;
private String strFilepath;

public MusicTrack(String strArtist, String strTitle, String strFilepath){
    this.strArtist = strArtist;
    this.strTitle = strTitle;
    this.strFilepath = strFilepath;
}

MusicPlayer:

public class MusicPlayer implements ActionListener{

private JFrame mainframe;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                MusicPlayer window = new MusicPlayer();
                window.mainframe.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */
public MusicPlayer() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    mainframe = new JFrame();
    mainframe.setTitle("MusicPlayer");
    mainframe.setBounds(100, 100, 450, 300);
    mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mainframe.setLocationRelativeTo(null);

    // menu & menuitems
    JMenuBar menuBar = new JMenuBar();
    mainframe.setJMenuBar(menuBar);

    JMenu mnFile = new JMenu("Datei");
    menuBar.add(mnFile);

    JMenuItem mnItemLoadNewList = new JMenuItem("Neue Liste laden");
    mnFile.add(mnItemLoadNewList);


    JMenuItem mnItemLoadLIst = new JMenuItem("Liste laden & anhängen");
    mnFile.add(mnItemLoadLIst);

    JMenuItem mnItemSave = new JMenuItem("Speichern");
    mnFile.add(mnItemSave);

    JMenuItem mnItemNewEntry = new JMenuItem("Neuer Eintrag");
    mnFile.add(mnItemNewEntry);

    JMenu mnSort = new JMenu("Sortieren");
    menuBar.add(mnSort);

    JMenuItem mnItemArtist = new JMenuItem("nach Interpret");
    mnSort.add(mnItemArtist);

    JMenuItem mnItemTitle = new JMenuItem("nach Titel");
    mnSort.add(mnItemTitle);

    GridBagLayout gridBagLayout = new GridBagLayout();
    gridBagLayout.columnWidths = new int[]{450, 0};
    gridBagLayout.rowHeights = new int[]{227, 29, 0};
    gridBagLayout.columnWeights = new double[]{1.0, Double.MIN_VALUE};
    gridBagLayout.rowWeights = new double[]{1.0, 0.0, Double.MIN_VALUE};
    mainframe.getContentPane().setLayout(gridBagLayout);
    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.BOTH;


    JPanel listPanel = new JPanel();
    listPanel.setLayout(gridBagLayout);
    mainframe.getContentPane().add(listPanel);
    listPanel.setVisible(true);



    // Buttons
    JButton btnPlayAll = new JButton("Play All");
    GridBagConstraints gbc_btnPlayAll = new GridBagConstraints();
    gbc_btnPlayAll.anchor = GridBagConstraints.NORTH;
    gbc_btnPlayAll.fill = GridBagConstraints.HORIZONTAL;
    gbc_btnPlayAll.gridx = 0;
    gbc_btnPlayAll.gridy = 1;
    mainframe.getContentPane().add(btnPlayAll, gbc_btnPlayAll);

    //Action- & Eventlistener, registering individual ActionListener per Button
    mnItemLoadNewList.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            JFileChooser fChoose = new JFileChooser();
            FileNameExtensionFilter fExt = new FileNameExtensionFilter("CSV", "csv");
            fChoose.setFileFilter(fExt);
            int returnVal = fChoose.showOpenDialog(null);
            if(returnVal == JFileChooser.APPROVE_OPTION){
                JList<Track> list = new JList<Track>();
                ListModel<Track> listModel = new DefaultListModel<Track>();
                list.setModel(listModel);
                JScrollPane sPane = new JScrollPane(list);
                sPane.add(listPanel);                   
            }
        };          
    });

    // FIXME - Attach!
    mnItemLoadLIst.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            JFileChooser fChoose = new JFileChooser();
            FileNameExtensionFilter fExt = new FileNameExtensionFilter("CSV", "csv");
            fChoose.setFileFilter(fExt);
            int returnVal = fChoose.showOpenDialog(null);
            if(returnVal == JFileChooser.APPROVE_OPTION){                   

            }
        };          
    });

    // FIXME - Save!
    mnItemSave.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            JFileChooser fChoose = new JFileChooser();
            FileNameExtensionFilter fExt = new FileNameExtensionFilter("CSV", "csv");
            fChoose.setFileFilter(fExt);
            int returnVal = fChoose.showOpenDialog(null);
            if(returnVal == JFileChooser.APPROVE_OPTION){
                File selcdFile = new File(fChoose.getSelectedFile().toString());
                PlayList myPL = new PlayList();
                myPL.getTracks();
                try {
                    myPL.save(selcdFile);
                } catch (IOException e1) {
                    JOptionPane.showMessageDialog(mainframe, e1 + "\n\nBitte eine kompatible Datei wählen.", "MusicPlayer Error", JOptionPane.WARNING_MESSAGE);
                }
            }               
        };          
    });

    mnItemNewEntry.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            NewEntry myNewEntry = new NewEntry(new JFrame(), "Neuer Eintrag");
            myNewEntry.setSize(300, 240);
            myNewEntry.setLocationRelativeTo(mainframe);
            myNewEntry.setVisible(true);

        };          
    });

Class NewEntry

            // FIXME - btnChooseFile
        btnChooseFile.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                JFileChooser fChoose = new JFileChooser();
                FileNameExtensionFilter fExt = new FileNameExtensionFilter("MP3", "mp3"); // FIXME add wave etc.
                fChoose.setFileFilter(fExt);
                int returnVal = fChoose.showOpenDialog(null);
                if(returnVal == JFileChooser.APPROVE_OPTION){
                    txtFilepath.setText(fChoose.getSelectedFile().getAbsolutePath());
                }
            };          
        });

PlayList(包含简单的方法,如保存,加载)

public class PlayList implements project.model.PlayList{

private List<Track> playList = new LinkedList<>();
private String strDelimiter = ";";

public void setPlayList(List<Track> playList) {
    this.playList = playList;
}

JList的代码,仍然令我头疼。

        ListModel<PlayList> theModel = new DefaultListModel<PlayList>();
    JList<PlayList> myJList = new JList<PlayList>(theModel);
    for(int i = 0; i < myPlayList.getTracks().size(); i++){
        theModel.addElement(i);
    }
    JScrollPane myScrollPane = new JScrollPane(myJList);
    mainframe.add(myScrollPane);

1 个答案:

答案 0 :(得分:2)

您应该首先阅读JList的{​​{3}},因为有很多要涵盖的内容。不过这是概述:

  1. 创建一个列表模型 - 大部分时间official tutorial都可以。
  2. 创建一个JList,并在构造函数中传递模型(以便它使用该模型)。
  3. 初始化列表,例如设置选择模式,可能还有自定义DefaultListModel
  4. 从现在开始,与模型而不是列表进行交互。该模型将为您启动事件。