I've been trying to code a music player (using java and JFugue) in Eclipse Mars, however, everytime I run the program it terminates after a few seconds with no output. Additionally, when I go to the "run as" drop down menu, there are no options. I feel like the problem is probably glaringly obvious, but I'm a bit new to java so without an error message I'm lost.
This is the main class
import java.util.Scanner;
import java.awt.*;
import java.awt.event.*;
import javax.sound.midi.MidiUnavailableException;
import javax.swing.*;
import java.io.IOException;
import org.jfugue.player.Player;
import org.jfugue.pattern.Pattern;
public class MusicPlayerMain
{
public static String songTitle;
public static JButton play = new JButton("play");
public static JButton back = new JButton("back");
public static JButton pause = new JButton("pause");
public static JButton forward = new JButton("forward");
public static JLabel label;
public static JComboBox dropDown;
public static JButton repeat = new JButton("repeat");
public static JButton selector;
public static void main(String[] args)
{
//-----------------------------------------------------------------
//starts up window
JFrame frame = new JFrame ("MusicPlayer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(3 , 1, 0, 50));
JPanel panelTop = new JPanel(new GridLayout(2, 2, 20, 50));
panelTop.add(new JLabel("Welcome to MusicPlayer!" + "\n" + "Please select a song!"));
String [] songs = {"WinterTime Ladybug Dance", "Song2", "Song3", "Song4", "Song5", "Song6", "Song7", "Song8", "Song9", "Song10"};
dropDown = new JComboBox();
for (int count1 = 0; count1 < 10; count1++)
{
dropDown.addItem(songs[count1]);
}
panelTop.add(dropDown);
selector = new JButton("Select");
panelTop.add(selector);
JPanel panelMiddle = new JPanel(new GridLayout(2, 1, 20, 50));
panelMiddle.setSize(500,200);
JPanel panelBottom = new JPanel(new GridLayout(1, 4, 20, 50));
panelBottom.setSize(500,200);
JPanel panelBottom2 = new JPanel(new GridLayout(1,1,20,50));
panelBottom2.setSize(500,100);
frame.add(panelTop);
frame.add(panelMiddle);
frame.add(panelBottom);
frame.add(panelBottom2);
//-----------------------------------------------------------------
//sets an action for the select button (displays song menu and plays song)
selector.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
label = new JLabel();
//make it so that label changes to song title
String titleOfSong = (String)dropDown.getSelectedItem();
label.setText(titleOfSong);
panelMiddle.add(label);
JProgressBar songProgress = new JProgressBar();
panelMiddle.add(songProgress); //shows progress of song with timer to show duration of song
panelBottom.add(back);//the song's array list index -1
panelBottom.add(play);//a player class
panelBottom.add(pause);//ManagedPlayer class
panelBottom.add(forward);//the song's array list index +1
panelBottom2.add(repeat);//repeats a playlist, song, or returns to normal
Music musical = new Music(selector, dropDown, back, play, pause, forward, label, repeat, songTitle);
try
{
musical.PutSongsIntoArrayList();
}
catch(IOException ioe)
{
System.out.println("No music found!");
}
frame.pack();
musical.playTheMusic(dropDown, songTitle);
}
});
//-----------------------------------------------------------------------
//navigates the music
play.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
Music musical = new Music(selector, dropDown, back, play, pause, forward, label, repeat, songTitle);
musical.playTheMusic(dropDown, songTitle);
}
});
pause.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
try
{
Music musical = new Music(selector, dropDown, back, play, pause, forward, label, repeat, songTitle);
musical.pauseTheMusic(play);
}
catch(MidiUnavailableException md)
{
System.out.println("no song found!");
}
}
});
back.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
Music musical = new Music(selector, dropDown, back, play, pause, forward, label, repeat, songTitle);
musical.goBack();
}
});
forward.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
Music musical = new Music(selector, dropDown, back, play, pause, forward, label,repeat,songTitle);
musical.goForward();
}
});
Music musical = new Music(selector, dropDown, back, play, pause, forward, label, repeat, songTitle);
musical.keepGoing();
repeat.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
Music musical = new Music(selector, dropDown, back, play, pause, forward, label,repeat,songTitle);
musical.setToRepeat();
}
});
}
}
This is the class that supplies the methods to navigate the music
import java.awt.*;
import javax.swing.*;
import org.jfugue.player.*;
import org.jfugue.pattern.*;
import javax.sound.midi.MidiUnavailableException;
import java.util.Scanner;
import java.io.File;
import java.util.ArrayList;
import java.io.IOException;
import java.util.Iterator;
public class Music
{
//take out the ones I don't need later
private JButton slctr;
private JComboBox drpDwn;
private JButton bck;
private JButton ply;
private JButton pse;
private JButton frwrd;
private JButton rpt;
private JLabel lbl;
private String title;
String tokens;
//declaring classes
ArrayList <String> TheTokens = new <String> ArrayList();
File musicFile = new File("Tokens.txt");
Pattern pat = new Pattern(tokens);
Player plays = new Player();
public Music(JButton s, JComboBox d, JButton b, JButton p, JButton ps, JButton f, JLabel l, JButton r, String t) //constructor
{
slctr = s;
drpDwn = d;
bck = b;
ply = p;
pse = ps;
frwrd = f;
lbl = l;
rpt = r;
title = t;
}
public void PutSongsIntoArrayList() throws IOException //puts the song tokens into an ArrayList so it can be manipulated
{
Scanner fileScanner = new Scanner(musicFile);
while(fileScanner.hasNext())
{
String readIt = fileScanner.nextLine();
Scanner scanLine = new Scanner(readIt);
scanLine.useDelimiter(",");
title = scanLine.next();
tokens = scanLine.nextLine();
TheTokens.add(title);
TheTokens.add(tokens);
scanLine.close();
}
fileScanner.close();
}
public void playTheMusic(JComboBox d, String title)//used for when song is selected, also when song is stopped and must be played again
{
String selectedSong = (String)d.getSelectedItem();
Iterator itr = TheTokens.iterator();
while(itr.hasNext())
{
if (selectedSong.equals(title))
{
plays.play(pat);
}
}
}
public void pauseTheMusic(JButton ply) throws MidiUnavailableException //pauses the currently playing song
{
plays.getManagedPlayer().pause();
while(!ply.getModel().isPressed()) //allows the method to pause the song indefinitely. Will only end once the song is resumed
{
if(ply.getModel().isPressed())
{
plays.getManagedPlayer().resume(); //resumes the song
}
}
}
public void goBack() //allows the user to listen to the previous song mid-song
{
int index = TheTokens.indexOf(title)-1;
TheTokens.get(index);
plays.play(pat);
}
public void goForward() //allows the user to listen to the next song mid-song
{
int index = TheTokens.indexOf(title)+1;
TheTokens.get(index);
plays.play(pat);
}
public void keepGoing() //causes the next song to play after the first one finishes.
//NOTE: is similar to musical.goForward() but instead of proceeding to next song when a button is pressed,
//this method proceeds to the next song after the first song finishes
{
boolean NextSong = plays.getManagedPlayer().isFinished();
if(NextSong == true)
{
int index = TheTokens.indexOf(title)+1;
TheTokens.get(index);
plays.delayPlay(2000, pat);
plays.play(pat);
}
}
public void setToRepeat()//cycles through repeat playlist, repeat song, and normal
//in main class, pressing button will change text on button to show what part of cycle player is in
{
Iterator itr = TheTokens.iterator();
while(!rpt.getModel().isPressed())
{
if(!itr.hasNext())
{
String inDEX = TheTokens.get(0);
}
if(rpt.getModel().isPressed())
{
while(!rpt.getModel().isPressed())
{
pat.repeat(1);
plays.play(pat);
if(rpt.getModel().isPressed())
{
break;
}
}
}
}
}
}
Try adding frame.setVisible(true) at the end of your main method.
Related
I have a rectangle, and I am trying to grow it like a graph of some sorts, but it does not show it growing in real time, it just has a white screen then I see a rectangle. Any help would be appreciated, thanks. The code I am having a problem with is under the ¨Animates the bar¨ comment.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Main extends JPanel {
static String[] mainArr;
static int start;
static boolean done = false;
static double datapoint1;
static double datapoint2;
static int jPlaceholder;
public static void main(String[] args) throws Exception {
// Creating the window
JFrame panel = new JFrame();
panel.setSize(450,250);
// Creating the window that shows the animation
JFrame drawingFrame = new JFrame();
drawingFrame.setSize(450,250);
JPanel jp = new JPanel();
jp.setLayout(null);
jp.setBackground(Color.red);
drawingFrame.add(jp);
// Creating all the text fields
JTextField dataTypesTextField = new JTextField("This box is currently not in use. Please do not type anything into this box");
dataTypesTextField.setBounds(50,50, 400,30);
panel.add(dataTypesTextField);
JTextField yearStartTextField = new JTextField("Type in this box what year your data starts in:");
yearStartTextField.setBounds(50,100, 400,30);
panel.add(yearStartTextField);
JTextField yearEndTextField = new JTextField("Type in this box what year your data ends in:");
yearEndTextField.setBounds(50,150, 400,30);
panel.add(yearEndTextField);
// Creating the button to submit the data
JButton enterButton = new JButton("Enter");
enterButton.setBounds(50,200, 100, 30);
panel.add(enterButton);
// =================================== ActionListener for enter button ========================================
enterButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (done==false) {
// Creating the variables to store the data the user just inputted
start = Integer.parseInt(yearStartTextField.getText());
int end = Integer.parseInt(yearEndTextField.getText());
mainArr = new String[end-start+1];
// Gets the data points
dataTypesTextField.setText("Datapoints you will use in order, space between each: ");
done = true;
} else {
// Getting all the data needed
mainArr = dataTypesTextField.getText().split(" ");
double[] datapoints = new double[mainArr.length];
for (int i=0; i<datapoints.length; i++) {
datapoints[i] = Double.parseDouble(mainArr[i]);
}
under here is where I had my problems I am pretty sure, but I could have screwed up somewhere else.
// Animates the bar
for (int i=0; i<datapoints.length-1; i++) {
// Getting all the datapoints
datapoint1 = datapoints[i];
datapoint2 = datapoints[i+1];
int j = 0;
while(j<50) {
j++;
int width = (int) (datapoint1+((datapoint2-datapoint1)/50)*j);
JPanel rectangle = new JPanel();
rectangle.setBackground(Color.black);
rectangle.setBounds(50, 50, width, 30);
jp.add(rectangle);
drawingFrame.setVisible(true);
rectangle.repaint();
System.out.println("The width is: "+width);
at first I thought it was because there was no pause between each ¨frame¨ but it still just shows a white screen, then it shows the rectangle.
try {
Thread.sleep(20);
} catch (Exception exp) {
}
}
}
}
}
});
// =====================================================================================================
// Finishes up both the windows
panel.setLayout(null);
panel.setVisible(true);
}
}
I'm a beginner working on a little drum machine project based off of Head First Java's code in Chapter 13.
At present, the code creates a sequence based on my input on the checkbox grid that the code draws to the GUI.
However I want the program to function like a real drum machine where I can add or subtract hits while the sequence plays.
My idea was to have all channels play on every tick of the sequence per default, and have the checkboxes unmute the channel at that specific tick. However I'm having a hard time figuring out how to implement that.
Is it possible? Is there an easier or better method that I'm not seeing to achieve what I'm aiming for?
import java.awt.*;
import javax.swing.*;
import javax.sound.midi.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.util.*;
import java.awt.event.*;
public class BeatBox {
JPanel mainPanel;
ArrayList<JCheckBox> checkboxList;
Sequencer sequencer;
Sequence sequence;
Track track;
JFrame theFrame;
String[] instrumentNames = {"Bass Drum", "Closed Hi-Hat", "Open Hi-Hat","Acoustic Snare",
"Crash Cymbal", "Hand Clap", "High Tom", "Hi Bongo", "Maracas", "Whistle", "Low Conga", "Cowbell",
"Vibraslap", "Low-mid Tom", "High Agogo", "Open Hi Conga" };
int[]instruments={35,42,46,38,49,39,50,60,70,72,64,56,58,47,67,63};
public static void main(String[]args){
new BeatBox().buildGUI();
}
public void buildGUI(){
theFrame=new JFrame("Cyber BeatBox");
theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BorderLayout layout=new BorderLayout();
JPanel background=new JPanel(layout);
background.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
//Build tempo slider
JSlider slider = new JSlider();
slider.setOrientation(JSlider.HORIZONTAL);
slider.setMinimum(50);
slider.setMaximum(200);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.setMajorTickSpacing(10);
slider.setMinorTickSpacing(1);
slider.setValue(120);
JLabel label = new JLabel();
label.setText("Tempo: " + slider.getValue());
slider.addChangeListener(e -> {
JSlider source = (JSlider) e.getSource();
//float tempoFactor=sequencer.getTempoFactor();
sequencer.setTempoFactor((float)source.getValue()/100);
label.setText("Tempo: " + String.valueOf(source.getValue()));
});
checkboxList=new ArrayList<JCheckBox>();
Box buttonBox=new Box(BoxLayout.X_AXIS);
JButton start=new JButton("Start");
start.addActionListener(new MyStartListener());
buttonBox.add(start);
JButton stop=new JButton("Stop");
stop.addActionListener(new MyStopListener());
buttonBox.add(stop);
JButton resetButton = new JButton("Reset Patch");
resetButton.addActionListener(new MyResetListener());
buttonBox.add(resetButton);
Box nameBox=new Box(BoxLayout.Y_AXIS);
for(int i=0;i< 16;i++){
nameBox.add(new Label(instrumentNames[i]));
}
background.add(BorderLayout.NORTH,buttonBox);
background.add(BorderLayout.WEST,nameBox);
theFrame.getContentPane().add(background);
background.add(BorderLayout.SOUTH, slider);
buttonBox.add(BorderLayout.EAST, label);
GridLayout grid=new GridLayout(16,16);grid.setVgap(1);
grid.setHgap(2);
mainPanel=new JPanel(grid);
background.add(BorderLayout.CENTER,mainPanel);
for(int i=0;i< 256;i++){
JCheckBox c=new JCheckBox();
c.setSelected(false);
checkboxList.add(c);
mainPanel.add(c);
} // end loop
setUpMidi();
theFrame.setBounds(50,50,300,300);
theFrame.pack();
theFrame.setVisible(true);
} // close method
public void setUpMidi(){
try{
sequencer=MidiSystem.getSequencer();
sequencer.open();
sequence=new Sequence(Sequence.PPQ,4);
track=sequence.createTrack();
sequencer.setTempoInBPM(120);
}catch(Exception e){ e.printStackTrace(); }
} // close method
public void buildTrackAndStart(){
int[]trackList=null;
sequence.deleteTrack(track);
track=sequence.createTrack();
sequencer.setTickPosition(0);
for(int i=0;i<16;i++){
trackList=new int[16];
int key=instruments[i];
for(int j=0;j<16;j++){
JCheckBox jc=(JCheckBox)checkboxList.get(j+(16*i));
if(!jc.isSelected()){
trackList[j]=key;
} /*else{
trackList[j]=0;
}*/
} // close inner loop
makeTracks(trackList);
track.add(makeEvent(176,1,127,0,16));
} // close outer
track.add(makeEvent(192,9,1,0,15));
try{
sequencer.setSequence(sequence);
sequencer.setLoopCount(sequencer.LOOP_CONTINUOUSLY);
sequencer.setMasterSyncMode(Sequencer.SyncMode.MIDI_SYNC);
sequencer.start();
sequencer.setTempoInBPM(120);
}catch(Exception e){
e.printStackTrace();
}
} // close buildTrackAndStart method
//Inner Classes
public class MyStartListener implements ActionListener{
public void actionPerformed(ActionEvent a){
buildTrackAndStart(); }
} // close inner class
public class MyStopListener implements ActionListener{
public void actionPerformed(ActionEvent a){
sequencer.stop();
sequencer.setTickPosition(0);}
} // close inner class
public class MyUpTempoListener implements ActionListener{
public void actionPerformed(ActionEvent a){
float tempoFactor=sequencer.getTempoFactor();
sequencer.setTempoFactor((float)(tempoFactor*1.03));
}
} // close inner class
public class MyDownTempoListener implements ActionListener{
public void actionPerformed(ActionEvent a){
float tempoFactor=sequencer.getTempoFactor();
sequencer.setTempoFactor((float)(tempoFactor*.97));
}
} // close inner class
public class MyResetListener implements ActionListener{
public void actionPerformed(ActionEvent a){
for(int i = 0; i<256; i++){
JCheckBox loopBox = checkboxList.get(i);
loopBox.setSelected(false);
}
}
} // close inner class
//Makers
public void makeTracks(int[]list){
for(int i=0;i<16;i++){
int key=list[i];
if(key!=0){
track.add(makeEvent(144,9,key,100,i));
track.add(makeEvent(128,9,key,100,i+1));
}
}
}
public MidiEvent makeEvent(int comd,int chan,int one,int two,int tick){
MidiEvent event=null;
try{
ShortMessage a=new ShortMessage();
a.setMessage(comd,chan,one,two);
event=new MidiEvent(a,tick);
}catch(Exception e){
e.printStackTrace();}
return event;
}
}
I have a Java program below which should ask the user to input a number in the applet window and process further on the basis of given. But the problem is that i am not able to run this java code through cmd
i know my main method is empty but i dont know what to put in it?
CODE
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
public class Table extends Applet {
private Label msg;
TextField number;
public void init()
{
setLayout(new FlowLayout());
Label heading = new Label("Multiplication Table");
number = new TextField(10);
Button button = new Button(" Press ");
msg = new Label("");
add(heading);
add(number);
add(button);
add(msg);
button.addActionListener(new ButtonListener());
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String str=" ";
int n = Integer.parseInt(number.getText());
if(n%2==0 && n>=11 && n<=90)
{
for(int i=1;i<=10;i++){
str = str+ n*i+" ";
}
}
else {
str = "Try Again! Number must be even and between 11-90";
}
msg.setText(str);
}
}
public static void main(String[] args) { }
}
I have a program which uses 3 radiobuttons to switch between 3 incrementing values for a counter, here time.
I want to change status when a radiobutton is pressed, and it does so, but only for a fraction. When launching the program will keep printing
0
Normal
2
Normal
4
Normal
6
etc. When I press the button slow it prints CHANGE Slow once but keeps incrementing with 2 and still prints Normal every time.
How can I have this permenently switch to a different value for status, and a different increment, until I choose another radiobutton again?
package daynightcycle;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
/**
* Day/night cycle with visuals. Adjustable speed and time inserts.
* Optional date or daycounter later
* #author rogie
*/
public class DayNightCycle extends JFrame implements Runnable{
//JFrame entities
private JPanel animationPanel;
public JRadioButton button;
public JRadioButton button2;
public JRadioButton button3;
public int time = 0;
public String status = "Normal";
public static void main(String[] args) {
DayNightCycle frame = new DayNightCycle();
frame.setSize(2000, 1300);
frame.setLocation(1000,350);
frame.createGUI();
frame.setVisible(true);
frame.setTitle("Day/Night Cycle, Rogier");
(new Thread(new DayNightCycle())).start();
}
private void createGUI() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container window = getContentPane();
window.setLayout(new FlowLayout() );
animationPanel = new JPanel();
animationPanel.setPreferredSize(new Dimension(2000, 900));
animationPanel.setBackground(Color.black);
window.add(animationPanel);
JRadioButton option1 = new JRadioButton("Slow");
JRadioButton option2 = new JRadioButton("Normal", true);
JRadioButton option3 = new JRadioButton("Fast");
option1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.out.println("CHANGE");
status = "Slow";
System.out.println(status);
}
});
option2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
status = "Normal";
}
});
option2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
status = "Fast";
}
});
//option2.setFont(new java.awt.Font("Tahoma", Font.BOLD, 30));
//option2.putClientProperty("JComponent.sizeVariant", "huge"); //doesn't work
ButtonGroup group = new ButtonGroup();
group.add(option1);
group.add(option2);
group.add(option3);
add(option1);
add(option2);
add(option3);
pack();
}
public void run() {
while(true){
System.out.println(time);
System.out.println(status);
try
{
Thread.sleep(500);
if (status.equals("Slow")) {
time += 1;
}
else if (status.equals("Normal")){
time += 2;
}
else {
time += 3;
}
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
}
}
}
You are creating to DayNightCycle-Objects, the first shows the GUI and the second prints on the console.
Change the line
(new Thread(new DayNightCycle())).start();
to
(new Thread(frame)).start();
public static void main(String[] args) {
final DayNightCycle frame = new DayNightCycle();
frame.setSize(2000, 1300);
frame.setLocation(1000,350);
frame.createGUI();
frame.setTitle("Day/Night Cycle, Rogier");
And then
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
frame.setVisible(true);
}
});
Or in java 8:
EventQueue.invokeLater(() -> frame.setVisible(true));
}
You in effect created a second DayNightCycle.
EDIT: resolved
on a side note, how do i pause an audio stream? is there a way, or can i only kill the player?
this school project i am doing, it's a music player, it is in BlueJ.
the requirements were to have a form displayed with a combo box, play buttons,etc.
i managed to get my playlist of audio into the playlist, but trying to change the SelectedIndex is giving me issues.
for example, there are two play buttons.
one is a play button- you play the first song in the playlist.
for this, i need to use the method GetSelectedIndex() to get me the index to play the song. the items in the combo box are in the same order as the files are listed.
the other button is a play random button, once pressed, it will play a random song in the given library. this button works, but when it plays the song, it needs to display which song it is playing in the combobox. using the SetSelectedIndex() method.
both are giving me the java.lang.NullPointerException error.
being int values, i can't seem to figure out how to make the "object" instanced- this is what other answers were saying. (on other questions)
random button constructor: (the other button is very similar to this)
private JButton ranbutton;
ranbutton = new JButton();
ranbutton.setMargin(new Insets(0,0,0,0));
ranbutton.setText("ran");
ranbutton.addActionListener(sl);
ranbutton.setBounds(150,220,35,30);
ShuffleListener sl= new ShuffleListener();
Action Listener of random button:
private class ShuffleListener implements ActionListener
{
public void actionPerformed(ActionEvent t)
{
org.playrandom();
playlist.setSelectedIndex(1); **THIS GIVES ME THE ERROR**
System.out.println("Z");
}
because it gives me a null error at the set selected index, "Z" never gets printed.
the other play button, is defined the same, and the action listener is the same except for the one difference:
int w= playlist.getSelectedIndex();**THIS GIVES ME THE ERROR**
code for the JComboBox "playlist" note: this code works. it is moldable to the number of files in the audio folder. note#2: org is the instance of the organizer class - which controls everything and it works.
public JComboBox playlist;
Integer[] nums;
x= org.getNumberOfTracks();
nums = new Integer[x];
String item[] = new String[x];
for(int i = 0 ; i < x; i++) {
item[i]= ((org.getName(i)));
}
JComboBox playlist = new JComboBox(item);
playlist.setBounds(50,50,250,50);
Now, something interesting, if i put
playlist.setSelectedIndex(4);
in the bottom of the constructor, and run the program, the combo box will be set to index 4 (item 5)
i have messed around a bit, isolating the code when it is called, and using System.Out.println() to see if the code is going through.
but i cannot figure out why it will call in the constructor but not in the ActionListener class.
Here is all of the code, excuse the formatting:
import java.util.ArrayList;
import java.util.Random;
import java.util.Iterator;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Insets;
import java.lang.Integer;
public class GUI extends JFrame
{
private int x;
private int r;
private int p;
private String l;
private int n=0;
private JButton playbutton;
private JButton ranbutton;
private JButton prevbutton;
private JButton skipbutton;
private JButton stopbutton;
private JButton repeatbutton;
private static MusicOrganizer org;
public JComboBox playlist;
public boolean looper=false;
public static void main(String[] args)
{
new GUI();
}
public GUI()
{
org= new MusicOrganizer();
this.setSize(400,300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Awesome Music Player");
this.setLocation(600,300);
JPanel panel= new JPanel();
panel.setLayout(null);
ButtonListener blp = new ButtonListener();
ShuffleListener sl= new ShuffleListener();
StopListener pl= new StopListener();
RepListener rp = new RepListener();
playbutton= new JButton();
playbutton.setMargin(new Insets(0,0,0,0));
playbutton.setText("►");
playbutton.addActionListener(blp);
playbutton.setBounds(35,215,40,40);
repeatbutton= new JButton();
repeatbutton.setMargin(new Insets(0,0,0,0));
repeatbutton.setText("○");
repeatbutton.addActionListener(rp);
repeatbutton.setBounds(190,220,35,30);
skipbutton = new JButton();
skipbutton.setMargin(new Insets(0,0,0,0));
skipbutton.setText(">>|");
skipbutton.setBounds(75,220,30,30);
prevbutton = new JButton();
prevbutton.setMargin(new Insets(0,0,0,0));
prevbutton.setText("|<<");
prevbutton.setBounds(5,220,30,30);
ranbutton = new JButton();
ranbutton.setMargin(new Insets(0,0,0,0));
ranbutton.setText("ran");
ranbutton.addActionListener(sl);
ranbutton.setBounds(150,220,35,30);
stopbutton= new JButton();
stopbutton.setMargin(new Insets(0,0,0,0));
stopbutton.setText("■");
stopbutton.addActionListener(pl);
stopbutton.setBounds(110,220,35,30);
Integer[] nums;
x= org.getNumberOfTracks();
nums = new Integer[x];
String item[] = new String[x];
for(int i = 0 ; i < x; i++)
{
item[i]= ((org.getName(i)));
}
JComboBox playlist = new JComboBox(item);
playlist.setBounds(50,50,250,50);
panel.add(skipbutton);
panel.add(prevbutton);
panel.add(playbutton);
panel.add(ranbutton);
panel.add(playlist);
panel.add(stopbutton);
panel.add(repeatbutton);
this.add(panel);
this.setVisible(true);
//playlist.setSelectedIndex(4);(the code that will work....)
}
public void u()
{
playlist.setSelectedIndex(1);//( temp testing)
}
public void q()
{
n=(int)playlist.getSelectedIndex();//( temp testing)
System.out.println(n);
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (x==1)
{
playbutton.setText("| |");
int w= playlist.getSelectedIndex(); //THIS GIVES ERROR
System.out.println(w);
x=0;
}
else
{
playbutton.setText("►");
x=1;
}
}
}
private class ShuffleListener implements ActionListener
{
public void actionPerformed(ActionEvent t)
{
org.playrandom();
u();//-> method is playlist.setSelectedIndex(1); gives me the error
System.out.println("I");
}
}
private class StopListener implements ActionListener
{
public void actionPerformed(ActionEvent c)
{
org.stopPlaying();
}
}
}
The playlist you set in GUI constructor is a local variable within the constructor, not the field. The field is never initialized. In the statement JComboBox playlist = new JComboBox(item); remove the first JComboBox making it not a declaration of a new variable but a reference. The line should read playlist = new JComboBox(item);