如何使我的排序功能正常工作

时间:2014-05-12 18:28:56

标签: java arrays swing jmenuitem

好的,我有一个Swing应用程序,我希望能够对我的数组进行排序。我已经构建了sort方法,我只需要条件触发器即可工作。出于某种原因,我无法弄清楚如何通过JMenuBar项目进行排序来触发它。正如你在我的代码中看到的那样,我已经尝试让它工作但似乎无法实现。 switch和if语句被注释掉,以便应用程序运行。现在其他一切都在工作了,我想通过功能工作进行排序。提前谢谢伙计们!

 import java.awt.*;
 import java.awt.event.*;
 import javax.swing.*;
 import javax.swing.text.*;

public class YourMusic extends JFrame implements ActionListener
{

 //construct components
JTextPane textPane = new JTextPane();



//initalize data in arrays
 String artist[]={"Eminem", "Britney S", "Dre" };
 String album[]={"Eminem Show", "Her Album", "Cronic" };
 String genre[]={"Rap", "Pop", "Hip-hop" };
 String hit[]={"Lose Yourself", "Toxic", "D.R.E" };
 String lable[]={"Interscope", "Britney Bitch", "Aftermath" };


//construct an instance of YourMusic
public YourMusic()
{
    super("Your Music");
}

 //create the menu system
public JMenuBar createMenuBar()
 {
   ///create instance of menu bar
    JMenuBar mnuBar =new JMenuBar();
    setJMenuBar(mnuBar);

    //Construct and Populate the File menu
    JMenu mnuFile = new JMenu("File",true);
        mnuFile.setMnemonic(KeyEvent.VK_F);
        mnuFile.setDisplayedMnemonicIndex(0);
        mnuBar.add(mnuFile);

    JMenuItem mnuFileExit =new JMenuItem("Exit");
        mnuFileExit.setMnemonic(KeyEvent.VK_E);
        mnuFileExit.setDisplayedMnemonicIndex(1);
        //mnuBar.add(mnuFileExit);
        mnuFile.add(mnuFileExit);
        mnuFileExit.setActionCommand("Exit");
        mnuFileExit.addActionListener(this);

    //construct and pop the edit menu
    JMenu mnuEdit = new JMenu("Edit",true);
        mnuEdit.setMnemonic(KeyEvent.VK_E);
        mnuEdit.setDisplayedMnemonicIndex(0);
        mnuBar.add(mnuEdit);

    JMenuItem mnuEditInsert = new JMenuItem("Insert New Song");
        mnuEditInsert.setMnemonic(KeyEvent.VK_I);
        mnuEditInsert.setDisplayedMnemonicIndex(1);
        mnuEdit.add(mnuEditInsert);
        mnuEditInsert.setActionCommand("insert");
        mnuEditInsert.addActionListener(this);


        //sort menu
    JMenu mnuSort = new JMenu("Sort",true);
        mnuSort.setMnemonic(KeyEvent.VK_S);
        mnuSort.setDisplayedMnemonicIndex(0);
        mnuBar.add(mnuSort);

     //These are the items id like to sort by

   JMenuItem mnuSortArtist =new JMenuItem("by Artist");
    mnuSort.setMnemonic(KeyEvent.VK_E);
    mnuSort.setDisplayedMnemonicIndex(1);

    mnuSort.add(mnuSortArtist);
    mnuSort.setActionCommand("artist");
    mnuSort.addActionListener(this);

    JMenuItem mnuSortAlbum =new JMenuItem("by album");
        mnuSort.setMnemonic(KeyEvent.VK_M);
        mnuSort.setDisplayedMnemonicIndex(1);
        mnuSort.add(mnuSortAlbum);
        mnuSort.setActionCommand("album");
        mnuSort.addActionListener(this);

    JMenuItem mnuSortGenre = new JMenuItem("by Genre");
        mnuSort.setMnemonic(KeyEvent.VK_G);
        mnuSort.setDisplayedMnemonicIndex(1);
        mnuSort.add(mnuSortGenre);
        mnuSort.setActionCommand("genre");
        mnuSort.addActionListener(this);

    JMenuItem mnuSortHit =new JMenuItem("by Hit");
        mnuSort.setMnemonic(KeyEvent.VK_H);
        mnuSort.setDisplayedMnemonicIndex(1);
        mnuSort.add(mnuSortHit);
        mnuSort.setActionCommand("hit");
        mnuSort.addActionListener(this);

    JMenuItem mnuSortLable =new JMenuItem("by Lable");
        mnuSort.setMnemonic(KeyEvent.VK_L);
        mnuSort.setDisplayedMnemonicIndex(1);
        mnuSort.add(mnuSortLable);
        mnuSort.setActionCommand("lable");
        mnuSort.addActionListener(this);


    return mnuBar;
}//End menu contructor


//Create the conetnt pane
public Container createContentPane()
{
    //construct and populate the north panel
    JPanel northPanel = new JPanel();
        northPanel.setLayout(new FlowLayout());

    //Create the JTextPane  and center Panel
    JPanel centerPanel = new JPanel();
        setTabsAndStyles(textPane);
        textPane = addTextToTextPane();
        JScrollPane scrollPane = new JScrollPane(textPane);
            scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
            scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
            scrollPane.setPreferredSize(new Dimension(600, 300));
        centerPanel.add(scrollPane);

    //create container and set attributes
    Container c =  getContentPane();
        c.setLayout(new BorderLayout(10,10));
        c.add(northPanel,BorderLayout.NORTH);
        c.add(centerPanel,BorderLayout.CENTER);

    return c;

}//end create container method


//method to create the tab stops and set fontstyles
protected void setTabsAndStyles(JTextPane textPane)
{
    //create Tab Stops
    TabStop[] tabs = new TabStop[4];
        tabs[0] = new TabStop(100, TabStop.ALIGN_LEFT,TabStop.LEAD_NONE);
        tabs[1] = new TabStop(200, TabStop.ALIGN_LEFT,TabStop.LEAD_NONE);
        tabs[2] = new TabStop(300, TabStop.ALIGN_LEFT,TabStop.LEAD_NONE);
        tabs[3] = new TabStop(400, TabStop.ALIGN_LEFT,TabStop.LEAD_NONE);
    TabSet tabset = new TabSet(tabs);

    //set tab style
    StyleContext tabStyle = StyleContext.getDefaultStyleContext();
    AttributeSet aset=
        tabStyle.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.TabSet,tabset);
    textPane.setParagraphAttributes(aset, false);

    //set Font Style
    Style fontStyle =
        StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);

    Style regular = textPane.addStyle("regular", fontStyle);
    StyleConstants.setFontFamily(fontStyle, "sansSerif");

    Style s = textPane .addStyle("italic",regular);
    StyleConstants.setItalic(s,true);

    s = textPane .addStyle("blod",regular);
    StyleConstants.setBold(s,true);

    s = textPane .addStyle("large",regular);
    StyleConstants.setFontSize(s,16);

}//method to ad text to textpane

public JTextPane addTextToTextPane()
{
    Document doc = textPane.getDocument();
    try
    {
        //clear previous text
        doc.remove(0, doc.getLength());

        //Insert title
        doc.insertString(0,"Artist\tAlbum\tGernre\tGreatest Hit\tRecord Lable\n",textPane.getStyle("large"));

        //insert detail
        for(int j=0;j<artist.length;j++)
        {
            doc.insertString(doc.getLength(),artist[j] + "\t",textPane.getStyle("bold"));
            doc.insertString(doc.getLength(),album[j] + "\t",textPane.getStyle("bold"));
            doc.insertString(doc.getLength(),genre[j] + "\t",textPane.getStyle("bold"));
            doc.insertString(doc.getLength(),hit[j] + "\t",textPane.getStyle("italic"));
            doc.insertString(doc.getLength(),lable[j] + "\n",textPane.getStyle("regular"));
        }//end loop
    } //end try
    catch (BadLocationException ble)
    {
        System.err.println("Couldnlt Insert Text");
    }//end catch
    return textPane;
}///end addtexttotextpane method

  public void actionPerformed(ActionEvent e)
   {
    String arg = e.getActionCommand();

   //user clicks the sort
     //   if(e.getSource() == artist)
   //   {
  /*/    switch(mnubar.getSelectedIndex())
      {
     case 0:
         sort(artist);
         break;
     case 1:
         sort(album);
         break;
     case 2:
         sort(genre);
         break;
     case 3:
         sort(hit);
         break;
     case 4:
         sort(lable);
         break;
  /*///    }//end swictch
    //    } //end if

 //user clicks exit on file menu
 if (arg.equals("Exit"))
 System.exit(0);
 //user clicks insert new dvd on edit menu
 if (arg.equals("insert"))
 {
    String newArtist = JOptionPane.showInputDialog(null, "Please enter the Artist");
    String newAlbum = JOptionPane.showInputDialog(null, "Please enter the Album for" + newArtist);
    String newGenre = JOptionPane.showInputDialog(null, "Please enter the Genre for" + newArtist);
    String newHit = JOptionPane.showInputDialog(null, "Please enter the Hit for" + newArtist);
    String newLable = JOptionPane.showInputDialog(null, "Please enter the Record Lable for " + newArtist);

     //Enlarge arrays
     artist = enlargeArray(artist);
     album = enlargeArray(album);
     genre = enlargeArray(genre);
     hit = enlargeArray(hit);
     lable = enlargeArray(lable);

     //add to arrys
     artist[artist.length-1] = newArtist;
     album[album.length-1] = newAlbum;
     genre[genre.length-1] = newGenre;
     hit[hit.length-1] = newHit;
     lable[lable.length-1] = newLable;

     //call to sort method
     sort(artist);
   //        mnuSort.setSelectedIndex(0);

 }//end if




   }//end action meth

   //Method  to enlarge an arry by 1
   public String[] enlargeArray(String[]currentArray)
   {
String[]newArray=new String [currentArray.length +1];
for(int i = 0; i<currentArray.length;i++)
    newArray[i]=currentArray[i];
return newArray;
   }//end enlarge arry method

   //method to sort arrays
   public void sort(String tempArray[])
   {
//loop to control number of passes
for(int pass = 1;pass<tempArray.length;pass++)
{
    for(int element =0 ; element<tempArray.length -1 ;element++)
        if (tempArray[element].compareTo(tempArray[element+1])>0)
        {
            swap(artist,element,element+1);
            swap(album,element, element+1);
            swap(genre,element, element+1);
            swap(hit,element, element+1);
            swap(lable,element, element+1);

        }//end if
}//end of loop
addTextToTextPane();
   }//end of sort method



  //method to swap two elements of an array
   public void swap(String swapArray[], int first, int second)
   {
String hold;//temp area to hold for swap
hold = swapArray[first];
swapArray[first] = swapArray[second];
swapArray[second] = hold;

   } //end swap method


public static void main(String args[])
{
    JFrame.setDefaultLookAndFeelDecorated(true);
    YourMusic f =new YourMusic();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setJMenuBar(f.createMenuBar());
    f.setContentPane(f.createContentPane());
    f.setSize(800,700);
    f.setVisible(true);
}//end main method


  }//End class

3 个答案:

答案 0 :(得分:4)

不要将数据保存在5个单独的数组中。创建一个自定义对象(可能称为音乐),其中包含5个属性(艺术家,专辑,流派,匹配和标签)。

然后,您需要创建一个自定义Comparator来对要排序的属性进行排序。

以下是您自定义的简单示例:

/*
**  Use the Collections API to sort a List for you.
**
**  When your class has a "natural" sort order you can implement
**  the Comparable interface.
**
**  You can use an alternate sort order when you implement
**  a Comparator for your class.
*/
import java.util.*;

public class Person implements Comparable<Person>
{
    String name;
    int age;

    public Person(String name, int age)
    {
        this.name = name;
        this.age = age;
    }

    public String getName()
    {
        return name;
    }

    public int getAge()
    {
        return age;
    }

    public String toString()
    {
        return name + " : " + age;
    }

    /*
    **  Implement the natural order for this class
    */
    public int compareTo(Person p)
    {
        return getName().compareTo(p.getName());
    }

    static class AgeComparator implements Comparator<Person>
    {
        public int compare(Person p1, Person p2)
        {
            return p1.getAge() - p2.getAge();
        }
    }

    public static void main(String[] args)
    {
        List<Person> people = new ArrayList<Person>();
        people.add( new Person("Homer", 38) );
        people.add( new Person("Marge", 35) );
        people.add( new Person("Bart", 15) );
        people.add( new Person("Lisa", 13) );

        // Sort by natural order

        Collections.sort(people);
        System.out.println("Sort by Natural order");
        System.out.println("\t" + people);

        // Sort by reverse natural order

        Collections.sort(people, Collections.reverseOrder());
        System.out.println("Sort by reverse natural order");
        System.out.println("\t" + people);

        //  Use a Comparator to sort by age

        Collections.sort(people, new Person.AgeComparator());
        System.out.println("Sort using Age Comparator");
        System.out.println("\t" + people);

        //  Use a Comparator to sort by descending age

        Collections.sort(people, Collections.reverseOrder(new Person.AgeComparator()));
        System.out.println("Sort using Reverse Age Comparator");
        System.out.println("\t" + people);
    }
}

答案 1 :(得分:2)

嗯,正如其他人的答案所建议的那样,你应该瞄准的目标是什么(有很多值得改进的事情):

import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import javax.swing.*;
import javax.swing.text.*;

public class YourMusic extends JFrame implements ActionListener {

//construct components
JTextPane textPane = new JTextPane();

//initalize data in arrays
ArrayList<SongData> songs = new ArrayList<SongData> ();


//construct an instance of YourMusic
public YourMusic() {
    super("Your Music");
    songs.add(new SongData("Eminem", "Eminem Show", "Rap", "Lose Yourself", "Interscope"));
    songs.add(new SongData("Britney S", "Her Album", "Pop", "Toxic", "Britney Bith"));
    songs.add(new SongData("Dre", "Cronic", "Hip-hop", "D.R.E", "Aftermath"));
}

//create the menu system
public JMenuBar createMenuBar()
{
    ///create instance of menu bar
    JMenuBar mnuBar =new JMenuBar();
    setJMenuBar(mnuBar);

    //Construct and Populate the File menu
    JMenu mnuFile = new JMenu("File",true);
    mnuFile.setMnemonic(KeyEvent.VK_F);
    mnuFile.setDisplayedMnemonicIndex(0);
    mnuBar.add(mnuFile);

    JMenuItem mnuFileExit =new JMenuItem("Exit");
    mnuFileExit.setMnemonic(KeyEvent.VK_E);
    mnuFileExit.setDisplayedMnemonicIndex(1);
    //mnuBar.add(mnuFileExit);
    mnuFile.add(mnuFileExit);
    mnuFileExit.setActionCommand("Exit");
    mnuFileExit.addActionListener(this);

    //construct and pop the edit menu
    JMenu mnuEdit = new JMenu("Edit",true);
    mnuEdit.setMnemonic(KeyEvent.VK_E);
    mnuEdit.setDisplayedMnemonicIndex(0);
    mnuBar.add(mnuEdit);

    JMenuItem mnuEditInsert = new JMenuItem("Insert New Song");
    mnuEditInsert.setMnemonic(KeyEvent.VK_I);
    mnuEditInsert.setDisplayedMnemonicIndex(1);
    mnuEdit.add(mnuEditInsert);
    mnuEditInsert.setActionCommand("insert");
    mnuEditInsert.addActionListener(this);


    //sort menu
    JMenu mnuSort = new JMenu("Sort",true);
    mnuSort.setMnemonic(KeyEvent.VK_S);
    mnuSort.setDisplayedMnemonicIndex(0);
    mnuBar.add(mnuSort);

    //These are the items id like to sort by

    JMenuItem mnuSortArtist =new JMenuItem("by Artist");
    mnuSortArtist.setMnemonic(KeyEvent.VK_E);
    mnuSortArtist.setDisplayedMnemonicIndex(1);

    mnuSort.add(mnuSortArtist);
    mnuSortArtist.setActionCommand("artist");
    mnuSortArtist.addActionListener(this);

    JMenuItem mnuSortAlbum =new JMenuItem("by album");
    mnuSortAlbum.setMnemonic(KeyEvent.VK_M);
    mnuSortAlbum.setDisplayedMnemonicIndex(1);
    mnuSort.add(mnuSortAlbum);
    mnuSortAlbum.setActionCommand("album");
    mnuSortAlbum.addActionListener(this);

    JMenuItem mnuSortGenre = new JMenuItem("by Genre");
    mnuSortGenre.setMnemonic(KeyEvent.VK_G);
    mnuSortGenre.setDisplayedMnemonicIndex(1);
    mnuSort.add(mnuSortGenre);
    mnuSortGenre.setActionCommand("genre");
    mnuSortGenre.addActionListener(this);

    JMenuItem mnuSortHit =new JMenuItem("by Hit");
    mnuSortHit.setMnemonic(KeyEvent.VK_H);
    mnuSortHit.setDisplayedMnemonicIndex(1);
    mnuSort.add(mnuSortHit);
    mnuSortHit.setActionCommand("hit");
    mnuSortHit.addActionListener(this);

    JMenuItem mnuSortLable =new JMenuItem("by Lable");
    mnuSortLable.setMnemonic(KeyEvent.VK_L);
    mnuSortLable.setDisplayedMnemonicIndex(1);
    mnuSort.add(mnuSortLable);
    mnuSortLable.setActionCommand("lable");
    mnuSortLable.addActionListener(this);


    return mnuBar;
}//End menu contructor


//Create the conetnt pane
public Container createContentPane() {
    //construct and populate the north panel
    JPanel northPanel = new JPanel();
    northPanel.setLayout(new FlowLayout());

    //Create the JTextPane  and center Panel
    JPanel centerPanel = new JPanel();
    setTabsAndStyles(textPane);
    textPane = addTextToTextPane();
    JScrollPane scrollPane = new JScrollPane(textPane);
    scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    scrollPane.setPreferredSize(new Dimension(600, 300));
    centerPanel.add(scrollPane);

    //create container and set attributes
    Container c =  getContentPane();
    c.setLayout(new BorderLayout(10,10));
    c.add(northPanel,BorderLayout.NORTH);
    c.add(centerPanel,BorderLayout.CENTER);

    return c;

}//end create container method


//method to create the tab stops and set fontstyles
protected void setTabsAndStyles(JTextPane textPane)
{
    //create Tab Stops
    TabStop[] tabs = new TabStop[4];
    tabs[0] = new TabStop(100, TabStop.ALIGN_LEFT,TabStop.LEAD_NONE);
    tabs[1] = new TabStop(200, TabStop.ALIGN_LEFT,TabStop.LEAD_NONE);
    tabs[2] = new TabStop(300, TabStop.ALIGN_LEFT,TabStop.LEAD_NONE);
    tabs[3] = new TabStop(400, TabStop.ALIGN_LEFT,TabStop.LEAD_NONE);
    TabSet tabset = new TabSet(tabs);

    //set tab style
    StyleContext tabStyle = StyleContext.getDefaultStyleContext();
    AttributeSet aset=
            tabStyle.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.TabSet,tabset);
    textPane.setParagraphAttributes(aset, false);

    //set Font Style
    Style fontStyle =
            StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);

    Style regular = textPane.addStyle("regular", fontStyle);
    StyleConstants.setFontFamily(fontStyle, "sansSerif");

    Style s = textPane .addStyle("italic",regular);
    StyleConstants.setItalic(s,true);

    s = textPane .addStyle("blod",regular);
    StyleConstants.setBold(s,true);

    s = textPane .addStyle("large",regular);
    StyleConstants.setFontSize(s,16);

}//method to ad text to textpane

public JTextPane addTextToTextPane()
{
    Document doc = textPane.getDocument();
    try
    {
        //clear previous text
        doc.remove(0, doc.getLength());

        //Insert title
        doc.insertString(0,"Artist\tAlbum\tGernre\tGreatest Hit\tRecord Lable\n",textPane.getStyle("large"));

        //insert detail
        for(int j=0;j<songs.size();j++)
        {
            doc.insertString(doc.getLength(),songs.get(j).getArtist() + "\t",textPane.getStyle("bold"));
            doc.insertString(doc.getLength(),songs.get(j).getAlbum() + "\t",textPane.getStyle("bold"));
            doc.insertString(doc.getLength(),songs.get(j).getGenre() + "\t",textPane.getStyle("bold"));
            doc.insertString(doc.getLength(),songs.get(j).getHit() + "\t",textPane.getStyle("italic"));
            doc.insertString(doc.getLength(),songs.get(j).getLable() + "\n",textPane.getStyle("regular"));
        }//end loop
    } //end try
    catch (BadLocationException ble)
    {
        System.err.println("Couldnlt Insert Text");
    }//end catch
    return textPane;
}// end addtexttotextpane method

public void actionPerformed(ActionEvent e) {
    String arg = e.getActionCommand();
    System.out.println(arg);
    if (arg.equals("artist") || arg.equals("album") || arg.equals("genre") || arg.equals("hit") || arg.equals("lable")) {
        this.sort(arg);
    }
    //user clicks exit on file menu
    else if (arg.equals("Exit"))
        System.exit(0);
    //user clicks insert new dvd on edit menu
    else if (arg.equals("insert")) {
        String newArtist = JOptionPane.showInputDialog(null, "Please enter the Artist");
        String newAlbum = JOptionPane.showInputDialog(null, "Please enter the Album for " + newArtist);
        String newGenre = JOptionPane.showInputDialog(null, "Please enter the Genre for " + newArtist);
        String newHit = JOptionPane.showInputDialog(null, "Please enter the Hit for " + newArtist);
        String newLable = JOptionPane.showInputDialog(null, "Please enter the Record Lable for " + newArtist);

        //Enlarge arrays
        songs.add(new SongData(newArtist, newAlbum, newGenre, newHit, newLable));
    }//end if
}//end action meth


//method to sort arrays
public void sort(final String criteria) {
    Collections.sort(songs, new Comparator<SongData> () {
        @Override
        public int compare(SongData song1, SongData song2) {
            switch (criteria) {
            case "artist":  return song1.getArtist().compareTo(song2.getArtist());
            case "album":   return song1.getAlbum().compareTo(song2.getAlbum());
            case "genre":   return song1.getGenre().compareTo(song2.getGenre());
            case "hit":     return song1.getHit().compareTo(song2.getHit());
            case "lable":   return song1.getLable().compareTo(song2.getLable());
            default:        return 0;
            }
        }
    });
    addTextToTextPane();
}//end of sort method


public static void main(String args[]) {
    JFrame.setDefaultLookAndFeelDecorated(true);
    YourMusic f =new YourMusic();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setJMenuBar(f.createMenuBar());
    f.setContentPane(f.createContentPane());
    f.setSize(800,700);
    f.setVisible(true);
}//end main method


}//End class

稍微好一些,现在,就SongData而言,我保持简单(eclipse生成的getter和setter,没有别的):

public class SongData {

private String artist, album, genre, hit, lable;

public SongData(String artist, String album, String genre, String hit, String lable) {
    setArtist(artist);
    setAlbum(album);
    setGenre(genre);
    setHit(hit);
    setLable(lable);
}

public String getArtist() {
    return artist;
}

public void setArtist(String artist) {
    this.artist = artist;
}

public String getAlbum() {
    return album;
}

public void setAlbum(String album) {
    this.album = album;
}

public String getGenre() {
    return genre;
}

public void setGenre(String genre) {
    this.genre = genre;
}

public String getHit() {
    return hit;
}

public void setHit(String hit) {
    this.hit = hit;
}

public String getLable() {
    return lable;
}

public void setLable(String lable) {
    this.lable = lable;
}

public String toString() {
    String data = "";
    data = getArtist() + ", " + getAlbum() + ", " + getGenre() + ", " + getHit() + ", " + getLable();
    return data;
}

}

这很有效,但是,对于空值,切换案例......应该做很多修复......但是现在你没有处理多个数组,而是有一个特殊对象的列表相当容易排序

答案 2 :(得分:1)

你应该明确地接受@camickr的建议并使用一个类来包含这些数据。但是听起来你也很难让你的排序方法被调用。我在您的代码中发现了一些错误


1.您在JMenuItem

上设置了错误的属性
JMenuItem mnuSortAlbum =new JMenuItem("by album");
    mnuSort.setMnemonic(KeyEvent.VK_M);
    mnuSort.setDisplayedMnemonicIndex(1);
    mnuSort.add(mnuSortAlbum);
    mnuSort.setActionCommand("album");
    mnuSort.addActionListener(this);

我认为应该阅读

JMenuItem mnuSortAlbum =new JMenuItem("by album");
    mnuSortAlbum.setMnemonic(KeyEvent.VK_M);
    mnuSortAlbum.setDisplayedMnemonicIndex(1);
    mnuSortAlbum.setActionCommand("album");
    mnuSortAlbum.addActionListener(this);
    mnuSort.add(mnuSortAlbum);

<小时/> 你实际上已经在actionPerformed中对排序进行了评论。我认为这就是你的问题所在。你几乎就在那里,你只需要使用放在变量ActionCommand中的arg

以下是如何使用该操作命令调用排序的示例。

String arg = e.getActionCommand();
switch(arg) {
 case "artist":
     sort(artist);
     break;
 case "album":
     sort(album);
     break;
}

此外,您的拼写标签标签