Need a little help

  • Thread starter richard.glisson
  • Start date
R

richard.glisson

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 = currentArray;
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[])

}
 
K

Knute Johnson

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 = currentArray;
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[])

}


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);
}
 
R

richard.glisson

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


This needs to be:

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

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.
 
K

Knute Johnson

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?
 
J

John T

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?
 
R

richard.glisson

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?- Hide quoted text -

- 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.
 
V

voorth

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()...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top