Sorry for thee length but i have seven classes for this program.
I took several functions and modified them to create a gui interface. I created a JFrame with 4 tabs that contain text only, then i have a 5th tab that has functional JButtons that when selected should prompt the user for input. Inside this 5th tab everything is formatted using a border layout. The jbuttons allows a list to be modified in specific ways. The list will display in a grid format in this tab as well. I think the problem is that Java has no idea where to display the user input boxes because i'm using the border layout???
Right now i'm just trying to get the main buttons to work, before i add in the remaining buttons,
any help would be GREATLY appreciated - i've been trying to figure this out for days
import javax.swing.*;
public class TunesLayout
{
//create a frame that contains a 3 tabbed pane.
public static void main (String[] args)
{
JFrame frame = new JFrame ("The Java Jukebox");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
JTabbedPane tp = new JTabbedPane();
tp.addTab ("About", new AboutPanel());
tp.addTab ("Feedback", new FeedbackPanel());
tp.addTab ("Donate", new DonatePanel());
tp.addTab ("Jukebox", new JukeboxPanel());
frame.getContentPane().add(tp);
frame.pack();
frame.setVisible(true);
}
}
import java.awt.*;
import javax.swing.*;
public class AboutPanel extends JPanel
{
//define the panel and its labels
public AboutPanel()
{
Color color = new Color(245,222,179);
setBackground (color);
JLabel l1 = new JLabel ("Welcome to the beta version of the Java Jukebox.");
JLabel l2 = new JLabel ("Choose the Feedback tab to find out how to contact me. " +
"Your comments are appreciated.");
JLabel l3 = new JLabel ("Choose the Donate tab to find out how to contribute to the cause.");
JLabel l4 = new JLabel ("Choose the Jukebox tab to find out about our cd collection.");
add (l1);
add (l2);
add (l3);
add (l4);
}
}
import java.awt.*;
import javax.swing.*;
public class DonatePanel extends JPanel
{
//define the panel and its labels
public DonatePanel()
{
Color color = new Color(250,128,114);
setBackground (color);
JLabel l1 = new JLabel ("Hey! We're just struggling students trying to start a business.");
JLabel l2 = new JLabel ("We need cash to stay afloat. Send money ASAP to:");
JLabel l3 = new JLabel ("911 Java Lane, Syracuse, NY 13202.");
JLabel l4 = new JLabel ("The staff of one at Java Jukebox thanks you for your generosity.");
add (l1);
add (l2);
add (l3);
add (l4);
}
}
import java.awt.*;
import javax.swing.*;
public class FeedbackPanel extends JPanel
{
//define the panel and its labels
public FeedbackPanel()
{
Color color = new Color(255,239,213);
setBackground (color);
JLabel l1 = new JLabel ("We'd love to know what you think of our product.");
JLabel l2 = new JLabel ("If you like our product email us at loveJB@hotmail.com.");
JLabel l3 = new JLabel ("If you don't like us please reference the DONATE tab for instructions");
JLabel l4 = new JLabel ("Maybe if you donate a little cash we can make it better.");
add (l1);
add (l2);
add (l3);
add (l4);
}
}
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.table.DefaultTableModel;
public class JukeboxPanel extends JPanel
{
JLabel lTitle;
JButton addCD, delCD, updCD, artistSort, titleSort, searchCD, readFileCD, writeFileCD, appendFileCD;
JTable table;
JScrollPane scrollPane;
CDCollection music;
//define the panel and its labels
public JukeboxPanel()
{
ActionListener listener = new buttonListener();
Color color = new Color(220,220,220);
setBackground (color);
//adding elements to the jpanel; title and buttons
JLabel lTitle = new JLabel ("THE JAVA JUKEBOX");
JButton addCD = new JButton ("Add a CD");
JButton updCD = new JButton ("Modify a CD");
JButton delCD = new JButton ("Delete a CD");
JButton titleSort = new JButton ("Sort by Title");
JButton artistSort = new JButton ("Sort by Artist");
//location for elements
add (lTitle, BorderLayout.NORTH);
add (addCD, BorderLayout.SOUTH);
add (updCD, BorderLayout.SOUTH);
add (delCD, BorderLayout.SOUTH);
add (titleSort, BorderLayout.SOUTH);
add (artistSort, BorderLayout.SOUTH);
//listener
addCD.addActionListener(listener);
updCD.addActionListener(listener);
delCD.addActionListener(listener);
titleSort.addActionListener(listener);
artistSort.addActionListener(listener);
music = new CDCollection();
//---------------------
// Create the Jtable
table = new JTable()
{
public boolean isCellEditable(int row, int column)
{
return false;
}
};
table.setPreferredScrollableViewportSize(new Dimension(700, 200));
table.setFillsViewportHeight(true);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//Create the scroll pane and add the table to it.
scrollPane = new JScrollPane(table);
//Add the scroll pane to this panel.
add(scrollPane, BorderLayout.CENTER);
}
private class buttonListener implements ActionListener
{
//--------------------------------------------------------------
// Performs the conversion when the enter key is pressed in
// the text field.
//--------------------------------------------------------------
public void actionPerformed (ActionEvent event)
{
String title = null, artist = null, tracks = null, value = null;
String[] selection = new String[4];
CD found = new CD();
int row = table.getSelectedRow();
Object source = event.getSource();
int flag = 0;
Object[][] data;
// These functions only work if there is a selection
if (row != -1)
{
// Get the selection data
selection[0] = table.getModel().getValueAt(row, 0).toString();
selection[1] = table.getModel().getValueAt(row, 1).toString();
selection[2] = table.getModel().getValueAt(row, 2).toString();
selection[3] = table.getModel().getValueAt(row, 3).toString();
if (source == delCD)
{
music.delCD(selection[2]);
}
else if (source == updCD)
{
title = JOptionPane.showInputDialog ("Enter the title: ", selection[2]);
if (title != null)
artist = JOptionPane.showInputDialog ("Enter the artist: ", selection[3]);
if (artist != null)
value = JOptionPane.showInputDialog ("Enter the price: ", selection[0]);
if (value != null)
tracks = JOptionPane.showInputDialog ("Enter the number of tracks: ", selection[1]);
if (tracks != null)
music.updCD (selection[2], title, artist, Double.parseDouble(value), Integer.parseInt(tracks));
}
}
// These functions don't need a selection
if (source == addCD)
{
title = JOptionPane.showInputDialog ("Enter the title: ");
if (title != null)
artist = JOptionPane.showInputDialog ("Enter the artist: ");
if (artist != null)
value = JOptionPane.showInputDialog ("Enter the price: ");
if (value != null)
tracks = JOptionPane.showInputDialog ("Enter the number of tracks: ");
if (tracks != null)
music.addCD (title, artist, Double.parseDouble(value), Integer.parseInt(tracks));
}
else if (source == titleSort)
{
music.sortByTitle();
}
else if (source == artistSort)
{
music.sortByArtist();
}
else if (source == searchCD)
{
title = JOptionPane.showInputDialog ("Enter the name of the CD: ");
if (title.equals(""))
System.out.println("Search failed");
else
found = music.binarySearch(title);
if (found != null)
flag = 1;
else
JOptionPane.showMessageDialog (null, "Sorry, we don't have that one.");
}
else if (source == readFileCD)
{
music.readFile();
}
else if (source == writeFileCD)
{
music.writeToFile(false);
}
else if (source == appendFileCD)
{
music.writeToFile(true);
}
// This refreshes the table by updating the TableModel
if (flag == 1)
{
data = new Object[1][4];
data[0][0] = found.getValue();
data[0][1] = found.getTracks();
data[0][2] = found.getTitle();
data[0][3] = found.getArtist();
}
else
{
data = music.getArray();
}
String[] columnNames = {"Price", "Title", "Artist"};
//MODIFY String[] columnNames = {"Price", "# Tracks", "Title", "Artist"};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table.setModel(model);
}
}
}
import java.text.NumberFormat;
import java.io.*;
import java.util.StringTokenizer;
public class CDCollection
{
private CD[] collection;
private int count;
private double totalValue;
private int currentSize;
//-----------------------------------------------------------------
// Constructor: Creates an initially empty collection.
//-----------------------------------------------------------------
public CDCollection ()
{
currentSize = 100;
collection = new CD[currentSize];
count = 0;
totalValue = 0.0;
}
//-----------------------------------------------------------------
// Adds a CD to the collection, increasing the size of the
// collection if necessary.
//-----------------------------------------------------------------
public void addCD (String title, String artist, double value, int tracks)
{
if (count == currentSize)
increaseSize();
collection[count] = new CD (title, artist, value, tracks);
totalValue += value;
count++;
}
//-----------------------------------------------------------------
// Returns a report describing the CD collection.
//-----------------------------------------------------------------
public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
String report = "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
report += "My CD Collection\n\n";
report += "Number of CDs: " + count + "\n";
report += "Total cost: " + fmt.format(totalValue) + "\n";
report += "Average cost: " + fmt.format(totalValue/count);
report += "\n\nCD List:\n\n";
for (int cd = 0; cd < count; cd++)
report += collection[cd].toString() + "\n";
return report;
}
//-----------------------------------------------------------------
// Deletes a CD from the collection
//-----------------------------------------------------------------
public void delCD(String title)
{
// j will count the number of CD's in the newly sized collection
int j = 0;
// i will count the current number of CD's
int i;
// create a temporary array of CD objects
// which will become the newly sized collection
CD [] temp = new CD[currentSize];
for(i=0; i<count; i++)
{
// look for a match
if(title.compareTo(collection[i].getTitle()) != 0)
{
// if there is no match, copy from the old to the new
temp[j] = collection[i];
j++;
}
else
{
// if there is a match, do not copy from the old to the new
// but update the total value
totalValue -= collection[i].getValue();
}
}
// check to see if there was a match and a deletion from the collection
if (i != j)
{
count--;
System.out.println("\nCD deleted\n");
collection = temp;
}
else
System.out.println("\nCD not found\n");
}
//-----------------------------------------------------------------
// Updates a CD from the collection
//-----------------------------------------------------------------
public void updCD(String oldTitle, String newTitle, String artist, double value, int tracks)
{
// i will count the number of CD's in the collection
int i;
// flag will tell if a match has been found
int flag = 0;
// temp will become the new CD collection
CD [] temp = new CD[currentSize];
for(i=0; i<count; i++)
{
// look for a match
if(oldTitle.compareTo(collection[i].getTitle()) != 0)
{
// if there is no match, copy from the old to the new
temp[i] = collection[i];
}
else
{
// if there is a match, replace the current CD
// with the updated fields and correct the value
temp[i] = new CD (newTitle, artist, value, tracks);
totalValue -= collection[i].getValue();
totalValue += value;
// set the flag which indicates a change has happened
flag = 1;
}
}
// check if an update has taken place
if (flag == 1)
{
System.out.println("\nCollection Updated\n");
collection = temp;
}
else
System.out.println("\nCD not found\n");
}
//-----------------------------------------------------------------
// Sorts the CD's by title
//-----------------------------------------------------------------
public void sortByTitle()
{
int i, j;
CD temp;
for (i = 0; i < count-1; i++)
{
for (j = i+1; j < count; j++)
{
if (collection[i].getTitle().compareTo(collection[j].getTitle()) > 0)
{
temp = collection[i];
collection[i] = collection[j];
collection[j] = temp;
}
}
}
}
//-----------------------------------------------------------------------------
// insertion sort used to sort an integer array: a[0] a[1] a[2] a[3] a[4] a[5]
//-----------------------------------------------------------------------------
public void sortByArtist ()
{
// Create akey CD
CD key = new CD();
// Outside loop starts from CD[0] and goes to CD[count-1]
for (int index = 1; index < count; index++)
{
// initialize key as the number in the current outside loop position
key = collection[index];
// initialize position as the current outside loop position
int position = index;
// Inside loop moves smaller numbers left and larger ones right
while (position > 0 && key.getLastName().compareTo(collection[position-1].getLastName()) < 0)
{
// replace smaller number on right by larger number on its left
collection[position] = collection[position-1];
// move back one position
position--;
}
// after inside loop is complete, place key where it belongs in sequence
collection[position] = key;
}
}
//-----------------------------------------------------------------
// Writes CD collection to disk file
// Overlay any existing data
// Create a new file if one does not exist and then write to it
//-----------------------------------------------------------------
public void writeToFile(boolean append)
{
// Try to write to a file
try
{
// create a file writer object called fw which will overlay any existing data
FileWriter fw = new FileWriter("CDCollection.txt", append);
// create a file buffered writer object called w
// in which to place what will be written to the disc
BufferedWriter w = new BufferedWriter (fw);
// String s will contain one CD
String s;
for(int i=0; i<count; i++)
{
// create a string s composed of fields separated by | character
s = "";
s += collection[i].getTitle() + "|";
s += collection[i].getArtist() + "|";
s += collection[i].getValue() + "|";
s += collection[i].getTracks() + "\r\n";
// write the string containing one CD object to the write buffer
w.write (s);
}
// Transfer a partially filled buffer to the disc
w.flush();
// Close the file (also empties the buffer)
w.close();
System.out.println("\nWrite to file is complete\n");
}
// If there is an file IO error, display why it occurred
catch(IOException e)
{
e.printStackTrace();
}
}
//-----------------------------------------------------------------
// Increases the capacity of the collection by creating a
// larger array and copying the existing collection into it.
//-----------------------------------------------------------------
public void readFile()
{
// Try to read a file
try
{
// create a file read object called fr which will read from a disc file
FileReader fr = new FileReader("CDCollection.txt");
// create a file buffered reader object called r
// in which to place what is read from the disc
BufferedReader r = new BufferedReader (fr);
// create a StringTokenizer object t to separate the fields of the CD
StringTokenizer t;
// create the working data items
String s, title, artist;
double value;
int tracks;
count = 0;
totalValue =0;
// outside loop to read consecutive CD's until all are read
while((s=r.readLine()) != null)
{
// get first token - title and then the second - artist, etc
// each separated from the other by the | character
t = new StringTokenizer(s,"|");
title = t.nextToken();
artist = t.nextToken();
value = Double.parseDouble(t.nextToken());
tracks = Integer.parseInt(t.nextToken());
// create a CD object composed of the tokens just read
collection[count] = new CD (title, artist, value, tracks);
// update the totalValue and count
totalValue += value;
count++;
}
if (currentSize == 0)
currentSize = 100;
if (count >= currentSize)
increaseSize();
r.close();
}
// If there is an file IO error, display why it occurred
catch(IOException e)
{
e.printStackTrace();
}
}
//-----------------------------------------------------------------
// Use a binary search to find a specific CD
//-----------------------------------------------------------------
public CD binarySearch(String targetTitle)
{
int min=0; // lowest position for search range
int max=count; // highest position for search range
int mid=0; // middle position for search range
boolean found = false; // boolean variable tells if title found
// Make sure the array is sorted
sortByTitle();
// loop looks for a match or min > max
while (!found && min <= max)
{
// calculate middle position in the range
mid = (min+max)/2;
// compare the title entered to the title of the mid position CD
if(collection[mid].getTitle().compareTo(targetTitle) == 0)
found = true; // we have a match - found is true
else if (collection[mid].getTitle().compareTo(targetTitle) > 0)
max = mid-1; // too high, use max 1 lower than mid
else
min = mid+1; // too low, use min 1 higher than mid
}
// determine if there was a match
if (found) return collection[mid]; // if so, return the CD that matches
else return null; // if not, return an empty CD object
}
//-----------------------------------------------------------------
// Increases the capacity of the collection by creating a
// larger array and copying the existing collection into it.
//-----------------------------------------------------------------
public Object[][] getArray()
{
Object[][] data = new Object[count][4];
for (int count = 0; count < this.count; count++)
{
data[count][0] = collection[count].getValue();
data[count][1] = collection[count].getTracks();
data[count][2] = collection[count].getTitle();
data[count][3] = collection[count].getArtist();
}
return data;
}
//-----------------------------------------------------------------
// Increases the capacity of the collection by creating a
// larger array and copying the existing collection into it.
//-----------------------------------------------------------------
private void increaseSize ()
{
CD[] temp = new CD[collection.length * 2];
for (int cd = 0; cd < collection.length; cd++)
temp[cd] = collection[cd];
collection = temp;
}
}
import java.text.NumberFormat;
public class CD
{
private String title, artist, artistFirstName, artistLastName;
private double value;
private int tracks;
//-----------------------------------------------------------------
// Creates a default CD
//-----------------------------------------------------------------
public CD ()
{
title = "";
artist = "";
value = 0.0;
tracks = 0;
artistFirstName = "";
artistLastName = "";
}
//-----------------------------------------------------------------
// Creates a new CD with the specified information.
//-----------------------------------------------------------------
public CD (String name, String singer, double price, int numTracks)
{
title = name;
artist = singer;
value = price;
tracks = numTracks;
int blank = 0;
for (int j=0; j < artist.length(); j++)
if (artist.charAt(j) == ' ')
{
blank = j;
break;
}
if (blank == 0)
{
artistFirstName = "";
artistLastName = artist;
}
else
{
artistFirstName = artist.substring(0,blank);
artistLastName = artist.substring(blank+1,artist.length());
}
}
//-----------------------------------------------------------------
// Returns the title of this CD
//-----------------------------------------------------------------
public String getTitle()
{
return title;
}
//-----------------------------------------------------------------
// Returns the artist of this CD
//-----------------------------------------------------------------
public String getArtist()
{
return artist;
}
//-----------------------------------------------------------------
// Returns the price of this CD
//-----------------------------------------------------------------
public double getValue()
{
return value;
}
//-----------------------------------------------------------------
// Returns the number of tracks in this CD
//-----------------------------------------------------------------
public int getTracks()
{
return tracks;
}
//-----------------------------------------------------------------
// Returns the artist's first name
//-----------------------------------------------------------------
public String getFirstName()
{
return artistFirstName;
}
//-----------------------------------------------------------------
// Returns the artist's last name
//-----------------------------------------------------------------
public String getLastName()
{
return artistLastName;
}
//-----------------------------------------------------------------
// Sets the name of this CD
//-----------------------------------------------------------------
public void setTitle(String name)
{
title = name;
}
//-----------------------------------------------------------------
// Sets the artist of this CD
//-----------------------------------------------------------------
public void setArtist(String singer)
{
artist = singer;
}
//-----------------------------------------------------------------
// Sets the price of this CD
//-----------------------------------------------------------------
public void getValue(double price)
{
value = price;
}
//-----------------------------------------------------------------
// Sets the number of tracks on this CD
//-----------------------------------------------------------------
public void setTracks(int numTracks)
{
tracks = numTracks;
}
//-----------------------------------------------------------------
// Returns a string description of this CD.
//-----------------------------------------------------------------
public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
String description;
description = fmt.format(value) + "\t" + tracks + "\t";
description += title + "\t" + artist;
return description;
}
}