Can't figure out NullPointerException error - java

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

Related

Java Swing: 'java.awt.AWTEventMulticaster.mouseMoved' error

I have been trying to create a 'catch me if you can' game: when I start it, it randomly chooses where to allocate a 'click me' button. I am not supposed to be able to click the button, the text should be re-assigned to another button before I am able to do that.
It works for a while but then it throws the following error: "java.awt.AWTEventMulticaster.mouseMoved".
I have been trying to fix the problem with removeListener() method but I don't seem to be able to find a solution. Any comments?
Here's my code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.lang.*;
public class Game extends JFrame {
//Panels
private JPanel mainPanel = new JPanel();
// Buttons
private JButton[] buttons = new JButton[9];
private JButton theChosenButton = new JButton();
// other
private int random = 0;
public Game() {
this.setTitle("Catch me if you can");
mainPanel.setLayout(new GridLayout(3, 3));
// creates buttons
for(int i = 0; i < 9 ; i++) {
buttons[i] = new JButton();
mainPanel.add(buttons[i]);
}
// Add everything to frame
this.getContentPane().add(mainPanel);
this.setSize(400, 400);
this.setVisible(true);
}
// generates random number between 1 and 9 to be used
public int clickMeGenerator(){
random = (int) Math.floor(Math.random() * 9);
return random;
}
// randomly assigns clickMeGenerator to a button
// add mouseMoved listener to the chosen button
public void assign(){
int randomButton = this.clickMeGenerator();
theChosenButton = buttons[randomButton];
theChosenButton.addMouseMotionListener(new MouseHover());
theChosenButton.setText("Click me");
}
public void removeListener() {
theChosenButton.removeMouseMotionListener(new MouseHover());
//}
}
// inner class
class MouseHover implements MouseMotionListener {
public void mouseMoved(MouseEvent e) {
theChosenButton.setText("");
Game.this.assign();
}
public void mouseDragged(MouseEvent e) {
}
}
} // end of class
Test class:
public class GameTest {
public static void main (String args[]) {
Game myGame = new Game();
myGame.assign();
}
}
Thank you so much for your help!
Just for clarity, the "actual" error is ...
Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError
at java.desktop/java.awt.AWTEventMulticaster.mouseMoved(AWTEventMulticaster.java:337)
at java.desktop/java.awt.AWTEventMulticaster.mouseMoved(AWTEventMulticaster.java:337)
So looking through the code...
public void assign() {
int randomButton = this.clickMeGenerator();
theChosenButton = buttons[randomButton];
theChosenButton.addMouseMotionListener(new MouseHover());
theChosenButton.setText("Click me");
}
You are repeatedly add a new MouseMotionListener to you buttons, over and over again, and...
public void removeListener() {
theChosenButton.removeMouseMotionListener(new MouseHover());
//}
}
is pointless, as you're trying to remove a new instance of MouseHover from the button, but it will never have been applied in the first place.
The first thing I would do is create an instance of MouseHover as an instance field in Game
private MouseHover mouseHover = new MouseHover();
and use it when calling addMouseMotionListener and removeMouseMotionListener.
I would then, remove the listener from the "currently" active button before adding it to the next one.
Personally, I would do this in the assign method
public void assign() {
int randomButton = this.clickMeGenerator();
if (theChosenButton != null) {
theChosenButton.removeMouseMotionListener(mouseHover);
}
theChosenButton = buttons[randomButton];
theChosenButton.addMouseMotionListener(mouseHover);
theChosenButton.setText("Click me");
}
I would also ensure that assign is called from within the Event Dispatching Thread when the class is first created, as the UI has been realised by the end of the constructor of Game, meaning the first call to assign is outside of the context of the EDT, which is not recommended.
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Game myGame = new Game();
myGame.assign();
}
});
}

ActionListener class keeps repeating when swing Timer is started

I am trying to develop a very basic "Simon says" simulator using Java GUI. I have a method that generates and returns an int[] array; for each element in the array, the Timer computer should start, call the doClick() method for the specified JButton, and wait for 1/2 a second. Each JButton is connected to an ActionListener() that changes the color of the specific button to white, activates another Timer timer, and changes the button back to its original color.
Every time I call computer.start(); within the for-loop it runs the code within ComputerListener(), but it repeats endlessly. I have added print statements so that I can see what is going on via the output on Netbeans. I have looked at similar issues on the forum, but nothing has provided a viable solution.
My question: why is my ComputerListener class repeating when computer.start(); is called within the for-loop?
package simon;
// #jagged_prospect
import java.util.Random;
import java.util.Arrays;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.ButtonUI;
import javax.swing.plaf.basic.BasicButtonUI;
public class SIMONPanel extends JPanel{
private static final int PANEL_W=300,PANEL_H=300;
private static final int PREF_W=500,PREF_H=500;
private static final String[] CARD_LABELS={"main","info","game"};
private final JPanel gameCard,infoCard,splashCard;
private final JButton rButton,yButton,gButton,bButton;
private final int lives=3;
private CardLayout cardlayout=new CardLayout();
private JPanel cards=new JPanel(cardlayout);
private Action[] actions={new ShowMainAction(),new ShowInfoAction(),
new ShowGameAction()};
private Object source;
private Timer timer,computer;
public SIMONPanel(){
setBackground(Color.BLACK);
setLayout(new BorderLayout());
gameCard=new JPanel();
infoCard=new JPanel();
splashCard=new JPanel();
// game card panel
gameCard.setLayout(new BorderLayout());
gameCard.setPreferredSize(new Dimension(PANEL_W,PANEL_H));
JPanel gameButtonPanel=new JPanel();
gameButtonPanel.setLayout(new GridLayout(2,2));
JButton startButton=new JButton("Start");
startButton.addActionListener(new StartListener());
rButton=new JButton("red");
rButton.addActionListener(new ColorButtonListener());
rButton.setSize(50,50);
rButton.setUI((ButtonUI)BasicButtonUI.createUI(rButton));
rButton.setBackground(Color.RED);
rButton.setForeground(Color.WHITE);
yButton=new JButton("yellow");
yButton.addActionListener(new ColorButtonListener());
yButton.setSize(50,50);
yButton.setUI((ButtonUI)BasicButtonUI.createUI(yButton));
yButton.setBackground(Color.YELLOW);
gButton=new JButton("green");
gButton.addActionListener(new ColorButtonListener());
gButton.setSize(50,50);
gButton.setUI((ButtonUI)BasicButtonUI.createUI(gButton));
gButton.setBackground(Color.GREEN);
bButton=new JButton("blue");
bButton.addActionListener(new ColorButtonListener());
bButton.setSize(50,50);
bButton.setUI((ButtonUI)BasicButtonUI.createUI(bButton));
bButton.setBackground(Color.BLUE);
bButton.setForeground(Color.WHITE);
gameButtonPanel.add(gButton);
gameButtonPanel.add(rButton);
gameButtonPanel.add(yButton);
gameButtonPanel.add(bButton);
gameCard.add(gameButtonPanel,BorderLayout.CENTER);
gameCard.add(startButton,BorderLayout.SOUTH);
// splash card panel
splashCard.setLayout(new BorderLayout());
splashCard.setPreferredSize(new Dimension(PANEL_W,PANEL_H));
splashCard.setBackground(Color.BLACK);
JLabel titleLabel=new JLabel("S I M O N",SwingConstants.CENTER);
titleLabel.setFont(new Font("Niagara Solid",Font.BOLD,84));
titleLabel.setForeground(Color.WHITE);
splashCard.add(titleLabel,BorderLayout.CENTER);
// info card panel
// nothing here yet
JPanel buttonPanel=new JPanel(new GridLayout(1,0,5,0));
for(Action action : actions){
buttonPanel.add(new JButton(action));
buttonPanel.setBackground(Color.BLACK);
}
cards.add(splashCard,CARD_LABELS[0]);
cards.add(infoCard,CARD_LABELS[1]);
cards.add(gameCard,CARD_LABELS[2]);
add(cards,BorderLayout.CENTER);
add(buttonPanel,BorderLayout.SOUTH);
}
// sets uniform panel size
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
// shows the Main Menu card
private class ShowMainAction extends AbstractAction {
public ShowMainAction() {
super("Main");
}
#Override
public void actionPerformed(ActionEvent e) {
cardlayout.show(cards,CARD_LABELS[0]);
}
}
// shows the Info card
private class ShowInfoAction extends AbstractAction {
public ShowInfoAction() {
super("Info");
}
#Override
public void actionPerformed(ActionEvent e) {
cardlayout.show(cards,CARD_LABELS[1]);
}
}
// show the Game card
private class ShowGameAction extends AbstractAction {
public ShowGameAction() {
super("Game");
}
#Override
public void actionPerformed(ActionEvent e) {
cardlayout.show(cards,CARD_LABELS[2]);
}
}
private class TimerListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent event){
if(source==gButton){
gButton.setBackground(Color.GREEN);
}
else if(source==rButton){
rButton.setBackground(Color.RED);
rButton.setForeground(Color.WHITE);
}
else if(source==yButton){
yButton.setBackground(Color.YELLOW);
}
else if(source==bButton){
bButton.setBackground(Color.BLUE);
bButton.setForeground(Color.WHITE);
}
}
}
private class ColorButtonListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent event){
source=event.getSource();
int delay=300;
timer=new Timer(delay,new TimerListener());
if(source==gButton){
gButton.setBackground(Color.WHITE);
timer.setRepeats(false);
timer.start();
}
else if(source==rButton){
rButton.setBackground(Color.WHITE);
rButton.setForeground(Color.BLACK);
timer.setRepeats(false);
timer.start();
}
else if(source==yButton){
yButton.setBackground(Color.WHITE);
timer.setRepeats(false);
timer.start();
}
else if(source==bButton){
bButton.setBackground(Color.WHITE);
bButton.setForeground(Color.BLACK);
timer.setRepeats(false);
timer.start();
}
}
}
private class StartListener implements ActionListener{
public void actionPerformed(ActionEvent event){
// calls generateSequence() to make pattern for player to replicate
// for debugging in output
System.out.println(Arrays.toString(generateSequence()));
}
}
public int[] generateSequence(){
Random ran=new Random();
ComputerListener cpu=new ComputerListener();
computer=new javax.swing.Timer(500,cpu);
int seqLen=4;
int[] gameSequence=new int[seqLen];
for(int x=0;x<seqLen;x++){
int assign=ran.nextInt(4)+1;
gameSequence[x]=assign;
}
for(int y=0;y<seqLen;y++){ // print and wait 1/2 second, repeat 3 times
computer.start();
}
//computer.stop(); // should stop ComputerListener()???
return gameSequence;
}
private class ComputerListener implements ActionListener{
public void actionPerformed(ActionEvent event){
// for debugging in output
System.out.println("it worked");
}
}
}
You're calling the computer Swing Timer's start button multiple times in a for loop, and that is not what you want to do, and in fact, the whole purpose of the timer is to help you get rid of the for loop. Instead the Timer repeats an action, and changes a state, and keeps going until its done. Consider using an int array or better an ArrayList to hold the colors that the timer should iterate through, and within that ActionListener, do the action and advance a pointer to the next position in the array or List, using that pointer to decide what action to do next. Then when the pointer is completely through the collection, stop the Timer.
For an example of exactly what I'm describing, please check out my Timer's ActionListener for an incomplete Simon game here: Method keeps window from closing
The Timer's ActionListener, annotated, is below:
private class TimerListener implements ActionListener {
private SimonPanel simonPanel; // the Simon JPanel
private int colorListIndex = 0; // index into the ArrayList of MyColor objects
private int sliceCount = 0;
private List<MyColor> myColorList; // the MyColor ArrayList -- the random colors to press
private int maxCount;
public TimerListener(SimonPanel simonPanel, List<MyColor> myColorList) {
// pass in the key fields into the program via constructor parameter
this.simonPanel = simonPanel;
this.myColorList = myColorList; // again the ArrayList that holds random MyColor objects
maxCount = myColorList.size(); // size of my list
}
#Override
public void actionPerformed(ActionEvent evt) {
// if index at the end of the list -- get out and clean up
if (colorListIndex == maxCount) {
// clear the display of "pressed" colors
for (MyColor myColor : MyColor.values()) {
simonPanel.setMyColorPressed(myColor, false);
}
// stop this timer
((Timer) evt.getSource()).stop();
return;
}
// the listener is a little complex since it must turn on colors and turn them off
// which is why I use a sliceCount int counter variable here
if (sliceCount == 0) {
// turn on the next color in the list (using the index)
MyColor myColor = myColorList.get(colorListIndex);
simonPanel.setMyColorPressed(myColor, true);
sliceCount++;
} else if (sliceCount < TIME_SLICES - 1) {
sliceCount++;
return;
} else if (sliceCount == TIME_SLICES - 1) {
sliceCount = 0;
MyColor myColor = myColorList.get(colorListIndex);
simonPanel.setMyColorPressed(myColor, false); // turn off the color
colorListIndex++; // and increment the index
return;
}
}
}

Error when adding event handler into a JButton to repaint the image inJava GUI

I've created 2 JButtons.One of them has the function of a button and the other handles an image.I want that image to change when this button is clicked.So inserted the method repaint() and added a listener to the first JButton to change the image.When trying to add the listener or the event handler to the first JButton nothing happens.So the image doesn't change.Can anyone show me how can I insert this listener in a way that it works(changes the image when the button is clicked)?Here is my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.*;
import java.util.Random;
public class Back extends JFrame{
private Random ran;
private int value;
private JButton r;
private JButton c;
public Back(){
super("title");
ran = new Random();
value = nextValue();
setLayout(new FlowLayout());
r=new JButton("ROLL");
add(r);
Icon i=new ImageIcon(getClass().getResource("1.png"));
Icon img=new ImageIcon(getClass().getResource("2.png"));
c= new JButton(i);
if (value==1){
c= new JButton(i);
}
else if(value==2){
c= new JButton(img);
}
add(c);
thehandler hand=new thehandler(this);//konstruktori i handler merr nje instance te Background
r.addActionListener(hand);
c.addActionListener(hand);
}
private int nextValue() {
return Math.abs(ran.nextInt()) % 6 + 1 ;
}
public void roll() {
value = nextValue() ;
repaint() ;
}
public int getValue() {
return value ;
}
private class thehandler implements ActionListener{
private Back d;
thehandler(Back thisone) {
d = thisone ; }
public void actionPerformed(ActionEvent event) {
d.roll() ;
}
}
public static void main(String[] args) {
Back d = new Back() ;
d.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
d.getContentPane().setBackground(Color.GREEN);
d.setSize(700,500);
d.setVisible(true);
}
}
So, basically, all your code comes down to here...
public void roll() {
value = nextValue();
repaint();
}
This calculates a new random value and calls repaint. But nothing in your code is effected by value at the point in time it's called.
Instead, you need to update the state of some control, maybe something more like...
public void roll() {
value = nextValue();
Icon i = new ImageIcon(getClass().getResource("1.png"));
Icon img = new ImageIcon(getClass().getResource("2.png"));
if (value == 1) {
c.setIcon(i);
} else if (value == 2) {
c.setIcon(img);
}
}
The next thing I would do is store all your images in some kind of array or List to make it easier to access, then you could simply do something
like...
public void roll() {
value = nextValue();
c.setIcon(listOfImages.get(value - 1));
}
Maybe have a look at Java Swing Timer and Animation: how to put it together for a more detailed example

Java program in Eclipse Mars, immediately terminates with no output?

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.

Add to array with actionlistener

I am a beginner with java and has got a problem that I just cant solve.
I am trying to add strings to my array, I have tested my array so that work. But my problem is that I have created an actionlistener and trying to get the text from another class and then add it to the array.
My Buttonlistener:
public class ButtonListener extends AddToLibrary implements ActionListener {
public void actionPerformed(ActionEvent e) {
Database dt = new Database();
dt.add(textType, textTitle, textSort, textDesc);
} }
I got a friend who told me that I am creating a new database every time I pushes the button, but how do I do if I just want to "load" it? Can clear that database is the classname for my array.
The more "funny" part of this is that when I run it in eclipse it goes to debugger without showing me anything clear that is wrong, and because of my limited knowledge in java this is too much to me.
My buttonlistener is geting the information from AddToLibrary and it looks like this:
public class AddToLibrary extends JPanel{
public String textTitle;
public String textSort;
public String textDesc;
public String textType;
public AddToLibrary() {
// Förklarande text
JLabel titel = new JLabel("Titel");
JLabel sort = new JLabel("Genre");
JLabel desc = new JLabel("Beskriving");
// Textrutor
JTextField textTitel = new JTextField(null, 20);
textTitel.setToolTipText("ex. Flickan som lekte med elden");
JTextField textSort = new JTextField(null, 10);
textSort.setToolTipText("ex. Skräck, Action");
JTextField textDesc = new JTextField(null, 15);
textDesc.setToolTipText("ex. Stieg Larsson");
// Knappar
JButton addButton = new JButton("Lägg till");
addButton.addActionListener(new ButtonListener()); //Lyssna på knapp
// Combobox
JComboBox comboBox = new JComboBox();
comboBox.addItem("Film");
comboBox.addItem("CD");
comboBox.addItem("Bok");
comboBox.addItem("Annat");
// Lägg till i panelen
add(titel);
add(textTitel);
add(sort);
add(textSort);
add(desc);
add(textDesc);
add(comboBox);
add(addButton);
}
public String getTitelText(JTextField titelText) {
textTitle = "" + titelText.getText();
return textTitle;
}
public String getDescText(JTextField descText) {
textDesc = "" + descText.getText();
return textDesc;
}
public String getSortText(JTextField sortText) {
textSort = "" + sortText.getText();
return textSort;
}
public String getTypeText(JComboBox comboBox) {
return textType = "" + (String) comboBox.getSelectedItem() + ".png";
}
}
But it do not work and I cant understand why it isnt working, so if anyone has some time over to help me I would be pleased.
Thanks!
One fault is here:
public class ButtonListener extends AddToLibrary implements ActionListener {
extending AddToLibrary creates a weird inheritance problem.
The simple solution is to define the ButtonListener inline:
final Database dt = new Database();
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dt.add(getTypeText(comboBox), getTitelText(textTitel), getSortText(textSort), getDescText(textDesc));
}
}); // Lyssna på knapp
One important change is to create one instance of Database to which the strings are added (as Amit Kumar already pointed out).
There were a lot of problems with your code, mostly illegal constructions. My advice is to get a good Java tutorial/book and take notice of how they solve the problems. Also if you use Eclipse (or another modern IDE) it will notify you of any illegal constructions and will try to propose solutions.
One last note, the public Strings and the JTextFields have the same name, this creates a problem for the computer as it does not know which one you are referring to (this is called shadowing). Define unique names for each variable within a class so you do not confuse the compiler or yourself.
=====================================
I have done a little work on your code and I arrived at the following. (It may be improved even further, but this is at least a lot better in terms of legality and readability)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class AddToLibrary extends JPanel {
private static final long serialVersionUID = 1L;
private Database database = new Database();
private JComboBox comboBox = new JComboBox(new String[]{"Film", "CD", "Bok", "Annat"});
private JButton addButton = new JButton("Lägg till");
private JTextField textTitel = new JTextField(null, 20);
private JTextField textSort = new JTextField(null, 10);
private JTextField textDesc = new JTextField(null, 15);
private JLabel titel = new JLabel("Titel");
private JLabel sort = new JLabel("Genre");
private JLabel desc = new JLabel("Beskriving");
public AddToLibrary() {
textTitel.setToolTipText("ex. Flickan som lekte med elden");
textSort.setToolTipText("ex. Skräck, Action");
textDesc.setToolTipText("ex. Stieg Larsson");
addButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
database.add(comboBox.getSelectedItem() + ".png",
textTitel.getText(),
textSort.getText(),
textDesc.getText()
)
}
}); // Lyssna på knapp
// Lägg till i panelen
add(titel);
add(textTitel);
add(sort);
add(textSort);
add(desc);
add(textDesc);
add(comboBox);
add(addButton);
}
}
public class ButtonListener extends AddToLibrary implements ActionListener {
private Database dt = new Database();
public void actionPerformed(ActionEvent e) {
dt.add(textType, textTitle, textSort, textDesc);
}
}
should work. Or better, the database should be created in AddToLibrary and passed to ButtonListener in its constructor. Sorry I do not have the time to check the code for you, but if this does not work, you can notify.

Categories