Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / February 2007

Tip: Looking for answers? Try searching our database.

Need a little help

Thread view: 
richard.glisson@keesler.af.mil - 05 Feb 2007 16:29 GMT
I am just learning java and need a tiny bit of help.  The code below
is a project that I had to create.  It works except for one small
part.  When I click on the Edit menu and select Insert I am prompted
for the information to add to the arrays.  After that it should add
the new record to the JTextPane in order sorted by the artist.  For
some reason no matter how I try to sort this it always sorts only the
original data and leaves any new entries at the bottom.  Can you see
where I wnet wrong and point me in the right direction to make the
sort work correctly?  Thanks.

Rich

/*
    Chapter 7:  Programming Assignment 2
    Programmer: Richard Glisson
    Date:       4 February 2007
    Filename:   MyMusic.java
    Purpose:    Sample program to show data about musical artists
*/

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

public class MyMusic extends JFrame implements ActionListener
{
    //construct components
    JLabel sortPrompt = new JLabel("Sort by:");
    JComboBox fieldCombo = new JComboBox();
    JTextPane textPane = new JTextPane();

    //initialize data in the arrays
    String artist[] = {"Chris Tomlin", "David Crowder Band", "Selah",
"Casting Crowns", "Third Day"};
    String genre[] = {"Contemporary Christian", "Contemporary Christian",
"Contemporary Christian", "Contemporary Christian", "Contemporary
Christian"};
    String greatest[] = {"Holy is the Lord", "Here is our King", "All My
Praise", "Voice of Truth", "You Are Mine"};
    String recordLabel[] = {"EMI CMG Publishing", "EMI CMG Publishing",
"BMG Songs", "Club Zoo", "EMI CMG Publishing"};

    //construct an instance of MyMusic
    public MyMusic()
    {
        super("Favorite Music");
    }

    //create the menu system
    public JMenuBar createMenuBar()
    {
        //create an instance of the 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_X);
            mnuFileExit.setDisplayedMnemonicIndex(1);
            mnuFile.add(mnuFileExit);
            mnuFileExit.setActionCommand("Exit");
            mnuFileExit.addActionListener(this);

        //construct and populate 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 Artist");
            mnuEditInsert.setMnemonic(KeyEvent.VK_I);
            mnuEditInsert.setDisplayedMnemonicIndex(0);
            mnuEdit.add(mnuEditInsert);
            mnuEditInsert.setActionCommand("Insert");
            mnuEditInsert.addActionListener(this);

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

        JMenuItem mnuSortArtist = new JMenuItem("Sort by Artist");
            mnuSortArtist.setMnemonic(KeyEvent.VK_A);
            mnuSortArtist.setDisplayedMnemonicIndex(0);
            mnuSort.add(mnuSortArtist);
            mnuSortArtist.setActionCommand("SortArtist");
            mnuSortArtist.addActionListener(this);

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

        JMenuItem mnuSortGreatest = new JMenuItem("Sort by Greatest Hit");
            mnuSortGreatest.setMnemonic(KeyEvent.VK_H);
            mnuSortGreatest.setDisplayedMnemonicIndex(2);
            mnuSort.add(mnuSortGreatest);
            mnuSortGreatest.setActionCommand("SortGreatest");
            mnuSortGreatest.addActionListener(this);

        JMenuItem mnuSortLabel = new JMenuItem("Sort by Record Label");
            mnuSortLabel.setMnemonic(KeyEvent.VK_L);
            mnuSortLabel.setDisplayedMnemonicIndex(3);
            mnuSort.add(mnuSortLabel);
            mnuSortLabel.setActionCommand("SortLabel");
            mnuSortLabel.addActionListener(this);

        return mnuBar;
    }//end public JMenuBar createMenuBar()

    //create the content pane
    public Container createContentPane()
    {
        //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(900, 200));
            centerPanel.add(scrollPane);

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

        return c;

    }//end public Container createContentPane()

    //method to create tab stops and set font styles
    protected void setTabsAndStyles(JTextPane textPane)
    {
        //create Tab Stops
        TabStop[] tabs = new TabStop[4];
            tabs[0] = new TabStop(200, TabStop.ALIGN_LEFT, TabStop.LEAD_NONE);
            tabs[1] = new TabStop(350, TabStop.ALIGN_LEFT, TabStop.LEAD_NONE);
            tabs[2] = new TabStop(500, TabStop.ALIGN_LEFT, TabStop.LEAD_NONE);
            tabs[3] = new TabStop(700, 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);
        textPane.setEditable(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("bold", regular);
        StyleConstants.setBold(s, true);

        s = textPane.addStyle("large", regular);
        StyleConstants.setFontSize(s, 16);
    }//end protected void setTabsAndStyles(JTextPane textPane)

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

            //insert title
            doc.insertString(0, "ARTIST\tGENRE\tGREATEST HIT\tRECORD LABEL\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(), genre[j] + "\t",
textPane.getStyle("regular"));
                doc.insertString(doc.getLength(), greatest[j] + "\t",
textPane.getStyle("regular"));
                doc.insertString(doc.getLength(), recordLabel[j] + "\n",
textPane.getStyle("regular"));
            }
        }//end try
        catch (BadLocationException ble)
        {
            System.err.println("Couldn't insert text.");
        }
        return textPane;
    }

    //event to process user clicks
    public void actionPerformed(ActionEvent e)
    {
        String arg = e.getActionCommand();

        //user clicks Exit on the File Menu
        if (arg == "Exit")
            System.exit(0);

        //user clicks Insert New Artist on the Edit Menu
        if (arg == "Insert")
        {
            //accept new data
            String newArtist = JOptionPane.showInputDialog(null, "Please enter
the new Artist's name");
            String newGenre = JOptionPane.showInputDialog(null, "Please enter
the genre");
            String newGreatest = JOptionPane.showInputDialog(null, "Please
enter " + newArtist + "'s greatest hit");
            String newRecordLabel = JOptionPane.showInputDialog(null, "Please
enter " + newArtist + "'s record label");

            //enlarge arrays
            artist = enlargeArray(artist);
            genre = enlargeArray(genre);
            greatest = enlargeArray(greatest);
            recordLabel = enlargeArray(recordLabel);

            //add new data to arrays
            artist[artist.length-1] = newArtist;
            genre[genre.length-1] = newGenre;
            greatest[greatest.length-1] = newGreatest;
            recordLabel[recordLabel.length-1] = newRecordLabel;

            //call sort method
            sort(artist);
        }

        if (arg == "SortArtist")
        {
            sort(artist);
        }

        if (arg == "SortGenre")
        {
            sort(genre);
        }

        if (arg == "SortGreatest")
        {
            sort(greatest);
        }

        if (arg == "SortLabel")
        {
            sort(recordLabel);
        }

    }//end public void actionPerformed(ActionEvent e)

    //method to enlarge an array 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 public String[] enlargeArray(String[] currentArray)

    //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(genre, element, element + 1);
                    swap(greatest, element, element + 1);
                    swap(recordLabel, element, element + 1);
                }//end if
            }//end for (int element = 0; element < tempArray.length - 1; element
++)
        }//end for (int pass = 1; pass < tempArray.length; pass++)
        textPane = addTextToTextPane();//add the new text to the JTextPane

    }//end public void sort(String tempArray[])

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

    //main method executes at run time
    public static void main(String args[])
    {
        JFrame.setDefaultLookAndFeelDecorated(false);
        MyMusic f = new MyMusic();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setJMenuBar(f.createMenuBar());
        f.setContentPane(f.createContentPane());
        f.setSize(900, 375);
        f.setVisible(true);
    }//end public static void main(String args[])

}
Knute Johnson - 05 Feb 2007 16:59 GMT
> I am just learning java and need a tiny bit of help.  The code below
> is a project that I had to create.  It works except for one small
[quoted text clipped - 320 lines]
>
> }

To compare Strings for equality you need to use String.equals not ==:

>         if (arg == "SortArtist")
>         {
>             sort(artist);
>         }

This needs to be:

    if (arg.equals("SortArtist")) {
        sort(artist);
    }

Signature

Knute Johnson
email s/nospam/knute/

richard.glisson@keesler.af.mil - 05 Feb 2007 18:45 GMT
> To compare Strings for equality you need to use String.equals not ==:
>
[quoted text clipped - 13 lines]
> Knute Johnson
> email s/nospam/knute/

That part actually works both ways but even changing it to this way
the added text stiil remains at the bottom and the original is sorted.
Knute Johnson - 05 Feb 2007 20:11 GMT
>> To compare Strings for equality you need to use String.equals not ==:
>>
[quoted text clipped - 16 lines]
> That part actually works both ways but even changing it to this way
> the added text stiil remains at the bottom and the original is sorted.

I guarantee you that you will have problems if you don't use .equals in
the future.

As to your other problem I don't see it when I run it here.  It works
just fine.  Is the code you are using different than what you posted?

Signature

Knute Johnson
email s/nospam/knute/

John T - 06 Feb 2007 00:00 GMT
>> To compare Strings for equality you need to use String.equals not ==:
>>
[quoted text clipped - 16 lines]
> That part actually works both ways but even changing it to this way
> the added text stiil remains at the bottom and the original is sorted.

I tried your program..very cool.  I added Rich Mullins to the list after
I sorted it in Artist Order and he went into the right place.
You are aware that there is no duplicate checking right?
richard.glisson@keesler.af.mil - 06 Feb 2007 13:19 GMT
> > That part actually works both ways but even changing it to this way
> > the added text stiil remains at the bottom and the original is sorted.
[quoted text clipped - 4 lines]
>
> - Show quoted text -

I feel stupid now...lol.  There is not an error.  If I put the entries
in beginning with a CAPITAL letter then the program does what it is
supposed to do.  Lower case letters are always placed at the bottom.
Thanks for the help.
voorth - 06 Feb 2007 14:26 GMT
On Feb 6, 2:19 pm, richard.glis...@keesler.af.mil wrote:

> I feel stupid now...lol.  There is not an error.  If I put the entries
> in beginning with a CAPITAL letter then the program does what it is
> supposed to do.  Lower case letters are always placed at the bottom.
> Thanks for the help.

In that case, you might want to check out String.equalsIgnoreCase()...
Oliver Wong - 07 Feb 2007 18:35 GMT
> On Feb 6, 2:19 pm, richard.glis...@keesler.af.mil wrote:
>
[quoted text clipped - 4 lines]
>
> In that case, you might want to check out String.equalsIgnoreCase()...

Also:

http://java.sun.com/j2se/1.4.2/docs/api/java/text/Collator.html
<quote>
The Collator class performs locale-sensitive String comparison. You use this
class to build searching and sorting routines for natural language text.
</quote>

   - Oliver


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.