Question

Objectives: GUI Tasks: In Lab 4, you have completed a typical function of music player --...

Objectives:

  • GUI

Tasks:

In Lab 4, you have completed a typical function of music player -- sorting song lists. In this assignment, you are asked to design a graphic user interface (GUI) for this function. To start, create a Java project named CS235A4_YourName. Then, copy the class Singer and class Song from finished Lab 4 and paste into the created project (src folder).

Define another class TestSongGUI to implement a GUI application of sorting songs. Your application must provide the above three ways to sorting songs. Use the completed classes Singer and Song from Lab 4 to support this function. Give users some test data (existing song lists) and allow users to directly see different sorting results by clicking their mouse on GUI components (i.e, button, radio button, menu, etc.). You have freedom (and are encouraged) to design your own GUI by using components and other elements (i.e., layout, color, font, etc.) learned from /not from the lectures. Remember, make sure that your application includes at least the following GUI components:

  • Label
  • Text Area (for song lists)
  • Button (for different sorting options)

----Class Singer---

package songs;

public class Singer {

      

       private String lastName; //singer's last name

       private String firstName; //singer's first name

      

       public Singer(String last, String first)

       {

             lastName = last;

             firstName = first;

       }

       public String getLastName() {

             return lastName;

       }

       public void setLastName(String lastName) {

             this.lastName = lastName;

       }

      

       public String getFirstName() {

             return firstName;

       }

       public void setFirstName(String firstName) {

             this.firstName = firstName;

       }

      

       public String toString()

       {

             return firstName + " " + lastName;

       }

}

---Class Song---

package songs;

import java.util.Comparator;

@SuppressWarnings("rawtypes")

public class Song implements Comparable{

       //instance variables

       private String title;

       private int secLength;

       private Singer artist;

       //constructors

       public Song(String title, int secLength, Singer artist)

       {

             this.title = title;

             this.secLength = secLength;

             this.artist = artist;

       }

       public Song(String title, int secLength, String artistLName, String artistFName)

       {

             this.title = title;

             this.secLength = secLength;

             this.artist = new Singer (artistLName, artistFName);

       }

       //toString method

       public String toString()

       {

             String info = title + " " + artist + " " + secLength + " seconds.";

             return info;

       }

       //Return the first name of the artist who sings this song

       public String getArtistFirstName()

       {

             return artist.getFirstName();

       }

       //Return the last name of the artist who sings this song

       public String getArtistLastName()

       {

             return artist.getLastName();

       }

       //getters and setters

       public String getTitle() {

             return title;

       }

       public void setTitle(String title) {

             this.title = title;

       }

       public int getLength() {

             return secLength;

       }

       public void setLength(int length) {

             this.secLength = length;

       }

       public Singer getArtist() {

             return artist;

       }

       public void setSinger(Singer artist) {

             this.artist = artist;

       }

       @Override

       public int compareTo(Object o) {

             Song s1 = (Song)this;

             Song s2 = (Song)o;

             return s1.getTitle().compareTo(s2.getTitle());

       }

       // This is the comparator for comparing the songs by seclenght

       public static Comparator lengthComparator = new Comparator(){

             @Override

             public int compare(Object arg0, Object arg1) {

                    // taking two songs object

                    Song s1 = (Song)arg0;

                    Song s2 = (Song)arg1;

                    // comparing on the basis of sec length

                    return s2.secLength - s1.secLength;

             }     

       };

       public static Comparator singerTitleComparator = new Comparator() {

             @Override

             public int compare(Object o1, Object o2) {

                    Song s1 = (Song)o1;

                    Song s2 = (Song)o2;

                    int compareVal = s1.getArtistLastName().compareTo(s2.getArtistLastName());

                    if(compareVal!=0) {

                           return compareVal;

                    }else {

                           return s1.getTitle().compareTo(s2.getTitle());

                    }

             }

       };

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Singer.java

public class Singer {

private String lastName; //singer's last names
private String firstName; //singer's first name

public Singer(String last, String first) {
lastName = last;
firstName = first;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String toString() {
return firstName + " " + lastName;
}
}

Song.java

import java.util.Comparator;

@SuppressWarnings("rawtypes")
public class Song implements Comparable {
//instance variables
private String title;
private int secLength;
private Singer artist;

//constructors
public Song(String title, int secLength, Singer artist) {
this.title = title;
this.secLength = secLength;
this.artist = artist;
}

public Song(String title, int secLength, String artistLName, String artistFName) {
this.title = title;
this.secLength = secLength;
this.artist = new Singer(artistLName, artistFName);
}

//toString method
public String toString() {
String info = title + " " + artist + " " + secLength + " seconds.";
return info;
}

//Return the first name of the artist who sings this song
public String getArtistFirstName() {
return artist.getFirstName();
}

//Return the last name of the artist who sings this song
public String getArtistLastName() {
return artist.getLastName();
}

//getters and setters
public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public int getLength() {
return secLength;
}

public void setLength(int length) {
this.secLength = length;
}

public Singer getArtist() {
return artist;
}

public void setSinger(Singer artist) {
this.artist = artist;
}

@Override
public int compareTo(Object o) {
Song s1 = (Song) this;
Song s2 = (Song) o;
return s1.getTitle().compareTo(s2.getTitle());
}

// This is the comparator for comparing the songs by seclenght
public static Comparator lengthComparator = new Comparator() {
@Override
public int compare(Object arg0, Object arg1) {
// taking two songs object
Song s1 = (Song) arg0;
Song s2 = (Song) arg1;

// comparing on the basis of sec length
return s2.secLength - s1.secLength;
}
};

public static Comparator singerTitleComparator = new Comparator() {
@Override
public int compare(Object o1, Object o2) {
Song s1 = (Song) o1;
Song s2 = (Song) o2;
int compareVal = s1.getArtistLastName().compareTo(s2.getArtistLastName());
if (compareVal != 0)
{
return compareVal;
}
else
{
return s1.getTitle().compareTo(s2.getTitle());
}
}
};
}

TestSongGUI.java (Main class)

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;

public class TestSongGUI {
  
private static JFrame mainFrame;
private static JPanel mainPanel, inputPanel, buttonPanel, resPanel;
private static JLabel fileNameLabel;
private static JTextField fileNameField;
private static JButton loadDataButton, sortBySongTitleButton, sortBySongLengthButton, sortBySingerTitleButton;
private static JTextArea resArea;
  
private static ArrayList<Song> songs = new ArrayList<>();
  
public static void main(String[] args)
{
mainFrame = new JFrame("Song Sorter");
mainPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
  
inputPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
fileNameLabel = new JLabel("Enter file name containing song data: ");
fileNameField = new JTextField(20);
loadDataButton = new JButton("Load Songs");
inputPanel.add(fileNameLabel);
inputPanel.add(fileNameField);
inputPanel.add(loadDataButton);
  
buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
sortBySongTitleButton = new JButton("Sort by Song Title");
sortBySongLengthButton = new JButton("Sort by Song Length");
sortBySingerTitleButton = new JButton("Sort by Singer Title");
buttonPanel.add(sortBySongTitleButton);
buttonPanel.add(sortBySongLengthButton);
buttonPanel.add(sortBySingerTitleButton);
  
resPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
resArea = new JTextArea(10, 50);
resArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(resArea);
scrollPane.setBounds(10,60,780,500);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
resPanel.add(scrollPane);
  
mainPanel.add(inputPanel);
mainPanel.add(buttonPanel);
mainPanel.add(resPanel);
  
mainFrame.add(mainPanel);
mainFrame.setSize(600, 300);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
  
// initially the 3 sorting buttons are disabled
// they will be activate once the loading songs is successful
sortBySongTitleButton.setEnabled(false);
sortBySongLengthButton.setEnabled(false);
sortBySingerTitleButton.setEnabled(false);
  
// action listener for load button
loadDataButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(fileNameField.getText().equals(""))
{
JOptionPane.showMessageDialog(null, "Please enter the song datafile name!");
return;
}
  
String filename = fileNameField.getText().trim();
songs = loadSongs(filename);
  
// data loaded, the 3 sorting buttons are enabled
// and, the filename field and the load button are disabled
sortBySongTitleButton.setEnabled(true);
sortBySongLengthButton.setEnabled(true);
sortBySingerTitleButton.setEnabled(true);
  
fileNameField.setEditable(false);
loadDataButton.setEnabled(false);
}
});
  
// action listener for the sort by song title button
sortBySongTitleButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(songs.isEmpty())
{
JOptionPane.showMessageDialog(null, "No songs to sort!");
return;
}
  
ArrayList<Song> temp = songs;
Collections.sort(temp);
  
// clear the text area
resArea.setText("");
  
// display the sorted songs
resArea.append("SORT BY SONG TITLE:\n--------------------------------------\n");
for(Song s : temp)
{
resArea.append(s + "\n");
}
}
});
  
// action listener for sort by song length
sortBySongLengthButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(songs.isEmpty())
{
JOptionPane.showMessageDialog(null, "No songs to sort!");
return;
}
  
ArrayList<Song> temp = songs;
Collections.sort(temp, Song.lengthComparator);
  
// display the sorted songs
resArea.append("SORT BY SONG LENGTH:\n--------------------------------------\n");
for(Song s : temp)
{
resArea.append(s + "\n");
}
}
});
  
// action listener for sort by singer title
sortBySingerTitleButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(songs.isEmpty())
{
JOptionPane.showMessageDialog(null, "No songs to sort!");
return;
}
  
ArrayList<Song> temp = songs;
Collections.sort(temp, Song.singerTitleComparator);
  
// display the sorted songs
resArea.append("SORT BY SINGER TITLE:\n--------------------------------------\n");
for(Song s : temp)
{
resArea.append(s + "\n");
}
}
});
}
  
private static ArrayList<Song> loadSongs(String filename)
{
ArrayList<Song> songs = new ArrayList<>();
Scanner fileReader;
  
try
{
fileReader = new Scanner(new File(filename));
while(fileReader.hasNextLine())
{
String line = fileReader.nextLine().trim();
String[] data = line.split(",");
// title, length, artLastName, artFirstName
String title = data[0];
int length = Integer.parseInt(data[1]);
String artistLName = data[2];
String artistFName = data[3];
  
songs.add(new Song(title, length, artistLName, artistFName));
}
fileReader.close();
}catch(FileNotFoundException fnfe){
JOptionPane.showMessageDialog(null, filename + " couldn't be found! Exiting...");
System.exit(0);
}
return songs;
}
}

************************************************************** SCREEENSHOT ***********************************************************

INPUT FILE (songdata.txt) - This file needs to be created before running the code. Also, the fields in the file need to be separated by commas.

GUI OUTPUT

Add a comment
Know the answer?
Add Answer to:
Objectives: GUI Tasks: In Lab 4, you have completed a typical function of music player --...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I have currently a functional Java progam with a gui. Its a simple table of contacts...

    I have currently a functional Java progam with a gui. Its a simple table of contacts with 3 buttons: add, remove, and edit. Right now the buttons are in the program but they do not work yet. I need the buttons to actually be able to add, remove, or edit things on the table. Thanks so much. Here is the working code so far: //PersonTableModel.java import java.util.List; import javax.swing.table.AbstractTableModel; public class PersonTableModel extends AbstractTableModel {     private static final int...

  • For Java please.Artwork. javaimport java.util.Scanner;public class ArtworkLabel {public static void main(String[] args)...

     Given main(). define the Artist class (in file Artist java) with constructors to initialize an artist's information, get methods, and a printlnfo() method. The default constructor should initialize the artist's name to "None' and the years of birth and death to 0. printinfo() should display Artist Name, born XXXX if the year of death is -1 or Artist Name (XXXX-YYYY) otherwise. Define the Artwork class (in file Artwork.java) with constructors to initialize an artwork's information, get methods, and a printinfo() method. The constructor should...

  • Task #3 Arrays of Objects 1. Copy the files Song java (see Code Listing 7.1), Compact...

    Task #3 Arrays of Objects 1. Copy the files Song java (see Code Listing 7.1), Compact Disc.java (see Code Listing 7.2) and Classics.txt (see Code Listing 7.3) from the Student Files or as directed by your instructor. Song.java is complete and will not be edited. Classics.txt is the data file that will be used by Compact Disc.java, the file you will be editing. 2. In Compact Disc.java, there are comments indicating where the missing code is to be placed. Declare...

  • public class Song { private String title; private String artist; private int duration; public Song() {...

    public class Song { private String title; private String artist; private int duration; public Song() { this("", "", 0, 0); } public Song(String t, String a, int m, int s) { title = t; artist = a; duration = m * 60 + s; } public String getTitle() { return title; } public String getArtist() { return artist; } public int getDuration() { return duration; } public int getMinutes() { return duration / 60; } public int getSeconds() { return...

  • JAVA The Comparable interface is defined as follows: public interface Comparable<T> {         int compareTo(T other);...

    JAVA The Comparable interface is defined as follows: public interface Comparable<T> {         int compareTo(T other); } A Film class is defined as public class Film {      private String title;      private int yearOfRelease;           public Film(String title, int yearOfRelease) {           super();           this.title = title;           this.yearOfRelease = yearOfRelease;      }           public void display()      { System.out.println("Title " + title +". Release" + yearOfRelease);      } } Rewrite the Film class so that it...

  • FOR JAVA: Summary: Create a program that adds students to the class list (see below). The...

    FOR JAVA: Summary: Create a program that adds students to the class list (see below). The solution should be named Roster402_v2.java. Allow the user to control the number of students added to the roster. Ask if the user would like to see their new roster to confirm additions. If yes, then display contents of the file, if no, end the program. ------------------------------------------------------------------------------------- List of student names and IDs for class (this will be your separate text file): Jones, Jim,45 Hicks,...

  • java With the incredible royalties on your Jukebox-management code, to become a DJ. You realize that you can adap...

    java With the incredible royalties on your Jukebox-management code, to become a DJ. You realize that you can adapt the Jukebox code to create some sophistica software for your new career. Consider the slightly simplified versio As a DJ, you are mainly interested in the BPM (beats per minute) and rating of the songs. you decide to indulge your dream n of the book's Song class below. public class Song private String title private String artist; private int rating private...

  • Introduction In this final programming exercise, you'll get a chance to put together many of the...

    Introduction In this final programming exercise, you'll get a chance to put together many of the techniques used during this semester while incorporating OOP techniques to develop a simple song playlist class. This playlist class allows a user to add, remove and display songs in a playlist. The Base Class, Derived Class and Test Client Unlike the other PAs you completed in zyLabs, for this PA you will be creating THREE Java files in IntelliJ to submit. You will need...

  • PLEASE COMPLETE THE CODES. package javaprogram; import java.io.PrintStream; import java.util.ArrayList; import java.util.Scanner; /** * Movie class...

    PLEASE COMPLETE THE CODES. package javaprogram; import java.io.PrintStream; import java.util.ArrayList; import java.util.Scanner; /** * Movie class definition. * * @author David Brown * @version 2019-01-22 */ public class Movie implements Comparable { // Constants public static final int FIRST_YEAR = 1888; public static final String[] GENRES = { "science fiction", "fantasy", "drama", "romance", "comedy", "zombie", "action", "historical", "horror", "war" }; public static final int MAX_RATING = 10; public static final int MIN_RATING = 0; /** * Converts a string of...

  • JAVA PROGRAMMING Given main(), complete the SongNode class to include the printSongInfo() method. Then write the...

    JAVA PROGRAMMING Given main(), complete the SongNode class to include the printSongInfo() method. Then write the Playlist class' printPlaylist() method to print all songs in the playlist. DO NOT print the dummy head node. Ex: If the input is: Stomp! 380 The Brothers Johnson The Dude 337 Quincy Jones You Don't Own Me 151 Lesley Gore -1 the output is: LIST OF SONGS ------------- Title: Stomp! Length: 380 Artist: The Brothers Johnson Title: The Dude Length: 337 Artist: Quincy Jones...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT