Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Head Start java Beatbox serialization/deserializatoin  RSS feed

 
Jamie Laurent
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have looked around online and found no answer to solving the JFilechooser change to the Beatbox program. I can get it to save the file with the save dialog, and the read/load of the pattern seemed to have worked but did not effect the GUI. Someone mentioned in a different thread to add something like reader.read().... which did not help me at all as I do not know what it is that would/should do and the compiler did not like it.

My code



If someone could show me what I am missing exactly instead of hinting at it that would be great. I have spent too much time trying to do it alone. 4 years of java in college and that hasn't helped me either due to not so wonderful professors.. this book has taught me more/better than they did in under 2 weeks.
 
Jamie Laurent
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is anyone going to help me?
 
Greg Charles
Sheriff
Posts: 3014
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jamie, and welcome to the Ranch!

Unfortunately, long code listings with little accompanying information often don't get answered. In this case, you've asked a question about JFileChooser, but your code doesn't have a JFileChooser in it. Also, that sounds like a GUI question, and you've posted to the I/O forum. You do seem to be serializing your file, so maybe you're in the right place. As far as I can tell though, your serialization/deserialization is working fine. That's great, but what is it that you need from us?
 
Jamie Laurent
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, i found code from others that could get me to the point of saving the file (rhythm) to whatever name I wanted, but could not get it to load said file back into the Beatbox. The original worked only for Checkbox.ser . I am not sure what to do with Jfilechooser to get it to save, then reload the pattern into the GUI. After a lot of frustration i went back to the original code and tried to start over from the working version. That is why it does not show up in the above code.

Any help getting it to serialize/deserialize would be great. They never taught this in college and nowhere have i found an answer online or on this forum. the closest thing i found was someone saying to use READ to interact with the GUI but that was not very helpful to me.

Thanks
 
Greg Charles
Sheriff
Posts: 3014
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Using READ to interact with the GUI doesn't make sense to me either. In concept, the JFileChooser just lets you pick a file to save to, and after that everything should be the same as what you're doing now. JFileChooser itself doesn't save anything, but it can fire an event telling you that a file has been selected. You can register a listener to run your save code. You can also just display the JFileChooser when the user hits your Serialize button, and then call fc.getSelectedFile() on it. There's an example here: http://www.exampledepot.com/egs/javax.swing.filechooser/CreateDlg.html

The thing with programing is that you can't let frustration overrule your logic. If things aren't working, they aren't working for a reason and if you don't give in to frustration, you have a much better chance of sussing out that reason. Take baby steps. Don't try to write your entire program in one go. Get a part working, then enhance it. Or get components working separately, then merge them. Use debugging tools, or at least print statements. Set up experiments and analyze the results.
 
Jamie Laurent
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yea, i know not to let frustration foil things.. well i had jfilechooser working but why doesnt it bring back the saved file version into the GUI? is there something missing after i get it to save using JFileChooser that needs to be added? I had it to the point where it picked a filed and tried to bring it back with the restore button, but it did not do anything visually, so I am unsure if it was working to that point or not. i kind of took a break waiting for an answer so I guess I will have to get a fresh look at it and see what I can make of it and post my findings sometime this week.

thanks
 
Jamie Laurent
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So any suggestions to fix this so it restores properly to the GUI?
 
Greg Charles
Sheriff
Posts: 3014
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jamie,

The last we heard from you, you were going to try to integrate in the JFileChooser. I don't think we can help you fix it until you've actually done that. Try to make a small example that demonstrates the problem, but removes any irrelevant details. For example, just an example that reads data from a file and displays it on a GUI. If you get that working, but still can't get it to restore your files to your GUI, then close in on it step by step until (or if) you reach an impasse. At that point, post your code and we'll see if we can spot the problem.
 
Jamie Laurent
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As i said before, I had it saving the files using JFileChooser, but not restoring. I do not have the time currently to make up a random GUI and mess with it, i just want to get this little addition done that the book suggests I do but gives no instruction on how to do so. I am currently moving, and have a job to find.. this will have to wait if noone can just tell me the exact code to add to serialize it then restore it to the GUI. it could take me a year to figure it out on my own.. I dont just magically come up with code answers.. half the stuff in this book was NOT taught during my 4 YEARS of college with JAVA being the main language.. on top of that it was one of the professors who liked to have you do it on your own with little instruction which let to crappy learning for me. My frustration with code is already at a high due to this.. so i just want something nice and easy so i can just move on from this stupid problem.
 
R Marquez
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jamie. Really do think you would benefit from looking at the Javadocs for JFileChooser (http://download.oracle.com/javase/6/docs/api/javax/swing/JFileChooser.html). You are/were so close to getting the Beatbox GUI to drive where the notes are stored and retrieved.

I attached your code with a few of my own changes. I am new to code ranch as a contributor, can you forward a link to the original problem statement?
 
R Marquez
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
// the code didn't attach:

package com.beats.tools;

import java.awt.*;
import javax.swing.*;
import javax.sound.midi.*;
import java.util.*;
import java.awt.event.*;
import java.io.*;

public class Beatbox {
JPanel mainpanel;
ArrayList<JCheckBox> checkboxList;
Sequencer sequencer;
Sequence sequence;
Track track;
JFrame theFrame;

private JFileChooser chooser;

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();
}// end main

public void buildGUI() {
chooser = new JFileChooser( new File( System.getProperty("user.home") ));

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

checkboxList = new ArrayList<JCheckBox>();
Box buttonBox = new Box(BoxLayout.Y_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 uptempo = new JButton("Tempo up");
uptempo.addActionListener(new Myuptempolistener());
buttonBox.add(uptempo);

JButton downtempo = new JButton("Tempo down");
downtempo.addActionListener(new Mydowntempolistener());
buttonBox.add(downtempo);

JButton serialize = new JButton("Serialize");
serialize.addActionListener(new MySendListener());
buttonBox.add(serialize);

JButton restore = new JButton("Restore");
restore.addActionListener(new MyReadInListener());
buttonBox.add(restore);

Box nameBox = new Box(BoxLayout.Y_AXIS);

for (int i = 0; i < 16; i++) {
nameBox.add(new Label(instrumentNames[i]));
}// end for loop

background.add(BorderLayout.EAST, buttonBox);
background.add(BorderLayout.WEST, nameBox);

theFrame.getContentPane().add(background);

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 for loop

setUpMidi();

theFrame.setBounds(50, 50, 300, 300);
theFrame.pack();
theFrame.setVisible(true);
}// end buildgui

public void setUpMidi() {
try {
sequencer = MidiSystem.getSequencer();
sequencer.open();
sequence = new Sequence(Sequence.PPQ, 4);
track = sequence.createTrack();
sequencer.setTempoInBPM(120);
}// end try
catch (Exception e) {
e.printStackTrace();
}// end catch
}// end setupmidi

public void buildTrackandStart() {
int[] trackList = null;
sequence.deleteTrack(track);
track = sequence.createTrack();
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;
}// end if
else {
trackList[j] = 0;
}// end else
}// end inner for loop

makeTracks(trackList);
track.add(makeEvent(176, 1, 127, 0, 16));
}// end outer for loop

track.add(makeEvent(192, 9, 1, 0, 15));

try {
sequencer.setSequence(sequence);
sequencer.setLoopCount(sequencer.LOOP_CONTINUOUSLY);
sequencer.start();
sequencer.setTempoInBPM(120);
}// end try
catch (Exception e) {
e.printStackTrace();
}// end catch
}// end buildtrackandstart

public class Mystartlistener implements ActionListener {
public void actionPerformed(ActionEvent a) {
buildTrackandStart();
}// end actionperformed
}// end inner class start

public class Mystoplistener implements ActionListener {
public void actionPerformed(ActionEvent a) {
sequencer.stop();
}// end actionperformed
}// end inner class stop

public class Myuptempolistener implements ActionListener {
public void actionPerformed(ActionEvent a) {
float tempoFactor = sequencer.getTempoFactor();
sequencer.setTempoFactor((float) (tempoFactor * 1.03));
}// end actionperformed
}// end inner class uptempo

public class Mydowntempolistener implements ActionListener {
public void actionPerformed(ActionEvent a) {
float tempoFactor = sequencer.getTempoFactor();
sequencer.setTempoFactor((float) (tempoFactor * .97));
}// end actionperformed
}// end innerclass downtempo

public class MySendListener implements ActionListener {
public void actionPerformed(ActionEvent a) {
boolean[] checkboxState = new boolean[256];

for (int i = 0; i < 256; i++) {
JCheckBox check = (JCheckBox) checkboxList.get(i);
if (check.isSelected()) {
checkboxState[i] = true;
}// end if
}// end for loop

try {
int result = chooser.showSaveDialog(Beatbox.this.theFrame);
if(result == JFileChooser.APPROVE_OPTION)
{
FileOutputStream fileStream = new FileOutputStream( chooser.getSelectedFile()
// new File( "Checkbox.ser")
);
ObjectOutputStream os = new ObjectOutputStream(fileStream);
os.writeObject(checkboxState);
}

}// end try
catch (Exception ex) {
ex.printStackTrace();
}// end catch
}// end actionperformed
}// end innerclass mysendlistener

public class MyReadInListener implements ActionListener {
public void actionPerformed(ActionEvent a) {
boolean[] checkboxState = null;
try {
int result = chooser.showOpenDialog(Beatbox.this.theFrame);
if(result == JFileChooser.APPROVE_OPTION)
{
FileInputStream filein = new FileInputStream(
chooser.getSelectedFile()
// new File( "Checkbox.ser")
);
ObjectInputStream is = new ObjectInputStream(filein);
checkboxState = (boolean[]) is.readObject();
}
}// end try
catch (Exception ex) {
ex.printStackTrace();
}// end catch

for (int i = 0; i < 256; i++) {
JCheckBox check = (JCheckBox) checkboxList.get(i);
if (checkboxState[i]) {
check.setSelected(true);
}// end if
else {
check.setSelected(false);
}// end else
}// end for loop

sequencer.stop();

}// end actionperformed
}// end innerclass

public void loadFile(File file) {
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
reader.close();
}// end try
catch (IOException ex) {
System.out.println("Couldn't read the file");
ex.printStackTrace();
}// end catch
}// end loadfile

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));
}// end if
}// end for loop
}// end maketracks

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);
}// end try
catch (Exception e) {
e.printStackTrace();
}// end catch

return event;

}// end makeevent
}// end class beatbox
 
Jamie Laurent
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you so much. I will in fact look into the javadocs to read more. i will try the code posted here and then analyze it further and adapt it to my own code. now i can finally move on to the next items in the book. wont be on much due to im moving shortly.
 
Jamie Laurent
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have tested the code given and it works. I again thank you so much for this help. Now i can move on and learn from this. I am in the process of adapting it to my code as everyone codes a little differently. If any questions arise i will ask here. in all other cases this is resolved and after any questions that come up are answered i will revolve and close this thread in whatever way i can.
 
Cory Hansen
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I am actually working on the same project, but I am having a hard time getting the serialization to occur. When I click the button to save my beatbox, it doesn't come up with any errors, but the checkbox.ser file doesn't get created. (Please see 1st post, my code is exactly the same, I checked everything). I'm not trying to implement the part where it has a filechooser, just trying to get it to save and load to the "checkbox.ser" file. I'm not getting any errors, but the file doesn't save or load. Does anyone know why that might happen?

Thank you,

Cory
 
Cory Hansen
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Cory Hansen wrote: Does anyone know why that might happen?

Thank you,

Cory


Nevermind, I figured it out! Thanks.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!