How to transmit sound from Synthesizer to sequencer - java

Okay, this is my first question here so go easy on me guys. I'm trying to generate sound on the fly using the noteOn in the MidiChannel class with the internal Java Synthesizer. It produces sound perfectly. My problem is outputing that sound to my sequencer so I can save it to a midi file. At the moment, my program creates the file but its empty. The disconnect occurs with my transmitter/receiver setup. When I try to get the synth's transmitter, it produces the lovely MidiUnavailbleException.
I have a crapload of code in here so I'll just give you the highlights. The complete class will be at the very bottom.
public Piano()
{
try
{
//previous code not shown//
sequence = new Sequence(Sequence.PPQ, 4); //I know. Just let it be.
sequence.createTrack();
sequencer = MidiSystem.getSequencer();
sequencer.open();
sequencer.setSequence(sequence);
sequencer.recordEnable(sequencer.getSequence().getTracks()[0], 1);
receiver = sequencer.getReceiver();
transmitter = synth.getTransmitter();
transmitter.setReceiver(receiver);
}
catch (Exception e)
{
e.printStackTrace();
}
}
When it hits the transmitter = synth.getTransmitter();, I get the MidiUnavailableException. Any ideas on how to get the MidiEvents from my synth to the sequencer?
//Complete Class - Warning: May Cause Headaches and/or Hysteria
package main;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import java.lang.reflect.Method;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.List;
import javax.imageio.ImageIO;
import javax.sound.midi.*;
import javax.sound.midi.MidiDevice.Info;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.Mixer;
import javax.sound.sampled.TargetDataLine;
import javax.swing.*;
import org.jfugue.DeviceThatWillReceiveMidi;
import org.jfugue.DeviceThatWillTransmitMidi;
public class Piano implements ActionListener
![enter image description here][2]{
KeyEventDispatcher dispatcher = new KeyEventDispatcher()
{
public boolean dispatchKeyEvent(KeyEvent e)
{
if(e.getID()==401)
{
if(e.getKeyCode()==KeyEvent.VK_SPACE)
{
sustain();
}
if(e.getKeyCode()==KeyEvent.VK_PERIOD)
{
octaveUp();
}
if(e.getKeyCode()==KeyEvent.VK_COMMA)
{
octaveDown();
}
if(e.getKeyCode()==KeyEvent.VK_A)
{
start(freq);
}
if(e.getKeyCode()==KeyEvent.VK_W)
{
start(freq+1);
}
if(e.getKeyCode()==KeyEvent.VK_S)
{
start(freq+2);
}
if(e.getKeyCode()==KeyEvent.VK_E)
{
start(freq+3);
}
if(e.getKeyCode()==KeyEvent.VK_D)
{
start(freq+4);
}
if(e.getKeyCode()==KeyEvent.VK_F)
{
start(freq+5);
}
if(e.getKeyCode()==KeyEvent.VK_T)
{
start(freq+6);
}
if(e.getKeyCode()==KeyEvent.VK_G)
{
start(freq+7);
}
if(e.getKeyCode()==KeyEvent.VK_Y)
{
start(freq+8);
}
if(e.getKeyCode()==KeyEvent.VK_H)
{
start(freq+9);
}
if(e.getKeyCode()==KeyEvent.VK_U)
{
start(freq+10);
}
if(e.getKeyCode()==KeyEvent.VK_J)
{
start(freq+11);
}
if(e.getKeyCode()==KeyEvent.VK_K)
{
start(freq+12);
}
if(e.getKeyCode()==KeyEvent.VK_O)
{
start(freq+13);
}
if(e.getKeyCode()==KeyEvent.VK_L)
{
start(freq+14);
}
if(e.getKeyCode()==KeyEvent.VK_P)
{
start(freq+15);
}
if(e.getKeyCode()==KeyEvent.VK_SEMICOLON)
{
start(freq+16);
}
}
if(e.getID()==402)
{
if(!sustain)
{
if(e.getKeyCode()==KeyEvent.VK_A)
{
end(freq);
}
if(e.getKeyCode()==KeyEvent.VK_W)
{
end(freq+1);
}
if(e.getKeyCode()==KeyEvent.VK_S)
{
end(freq+2);
}
if(e.getKeyCode()==KeyEvent.VK_E)
{
end(freq+3);
}
if(e.getKeyCode()==KeyEvent.VK_D)
{
end(freq+4);
}
if(e.getKeyCode()==KeyEvent.VK_F)
{
end(freq+5);
}
if(e.getKeyCode()==KeyEvent.VK_T)
{
end(freq+6);
}
if(e.getKeyCode()==KeyEvent.VK_G)
{
end(freq+7);
}
if(e.getKeyCode()==KeyEvent.VK_Y)
{
end(freq+8);
}
if(e.getKeyCode()==KeyEvent.VK_H)
{
end(freq+9);
}
if(e.getKeyCode()==KeyEvent.VK_U)
{
end(freq+10);
}
if(e.getKeyCode()==KeyEvent.VK_J)
{
end(freq+11);
}
if(e.getKeyCode()==KeyEvent.VK_K)
{
end(freq+12);
}
if(e.getKeyCode()==KeyEvent.VK_O)
{
end(freq+13);
}
if(e.getKeyCode()==KeyEvent.VK_L)
{
end(freq+14);
}
if(e.getKeyCode()==KeyEvent.VK_P)
{
end(freq+15);
}
if(e.getKeyCode()==KeyEvent.VK_SEMICOLON)
{
end(freq+16);
}
}
else
{
if(e.getKeyCode()==KeyEvent.VK_A)
{
endSoft(freq);
}
if(e.getKeyCode()==KeyEvent.VK_W)
{
endSoft(freq+1);
}
if(e.getKeyCode()==KeyEvent.VK_S)
{
endSoft(freq+2);
}
if(e.getKeyCode()==KeyEvent.VK_E)
{
endSoft(freq+3);
}
if(e.getKeyCode()==KeyEvent.VK_D)
{
endSoft(freq+4);
}
if(e.getKeyCode()==KeyEvent.VK_F)
{
endSoft(freq+5);
}
if(e.getKeyCode()==KeyEvent.VK_T)
{
endSoft(freq+6);
}
if(e.getKeyCode()==KeyEvent.VK_G)
{
endSoft(freq+7);
}
if(e.getKeyCode()==KeyEvent.VK_Y)
{
endSoft(freq+8);
}
if(e.getKeyCode()==KeyEvent.VK_H)
{
endSoft(freq+9);
}
if(e.getKeyCode()==KeyEvent.VK_U)
{
endSoft(freq+10);
}
if(e.getKeyCode()==KeyEvent.VK_J)
{
endSoft(freq+11);
}
if(e.getKeyCode()==KeyEvent.VK_K)
{
endSoft(freq+12);
}
if(e.getKeyCode()==KeyEvent.VK_O)
{
endSoft(freq+13);
}
if(e.getKeyCode()==KeyEvent.VK_L)
{
endSoft(freq+14);
}
if(e.getKeyCode()==KeyEvent.VK_P)
{
endSoft(freq+15);
}
if(e.getKeyCode()==KeyEvent.VK_SEMICOLON)
{
endSoft(freq+16);
}
}
}
return false;
}
};
final int VOLUME_MAX = 120;
int freq = 60;
int volume = VOLUME_MAX;
int instr;
int delay = 1000;
int velocity = 1000;
int count = 0;
boolean sustain = false;
boolean recording = false;
DecimalFormat df;
List<Icon> icons;
AnimatedIcon aIcon;
Synthesizer synth;
Sequence sequence;
Sequencer sequencer;
MidiChannel[] mc;
Instrument[] instruments;
Instrument instrument;
Transmitter transmitter;
Receiver receiver;
File file;
JFrame mainFrame;
JPanel mainPanel;
ImagePanel iPanel;
JButton rec;
JButton stop;
JButton load;
JButton sustainB;
JButton octave;
JButton up;
JButton down;
JButton volumeB;
JButton vUp;
JButton vDown;
OctavePanel oPanel;
VolumePanel vPanel;
GridBagLayout gridBag;
GridBagConstraints c;
Image redCir;
Image greenCir;
Image recCir;
public Piano()
{
DefaultKeyboardFocusManager.getCurrentKeyboardFocusManager().
addKeyEventDispatcher(dispatcher);
InputMap im = (InputMap)UIManager.get("Button.focusInputMap");
im.put(KeyStroke.getKeyStroke("pressed SPACE"), "none");
im.put(KeyStroke.getKeyStroke("released SPACE"), "none");
try
{
synth = MidiSystem.getSynthesizer();
synth.open();
FileInputStream stream = new FileInputStream(this.getClass().getResource("resources/soundbank1.gm").toString().substring(6));
Soundbank sBank = MidiSystem.getSoundbank(stream);
instruments = sBank.getInstruments();
synth.loadAllInstruments(sBank);
mc = synth.getChannels();
instrument = (Instrument)JOptionPane.showInputDialog(null, "Choose an instrument", "", JOptionPane.PLAIN_MESSAGE, null, instruments, instruments[0]);
mc[0].programChange(instrument.getPatch().getProgram());
greenCir = ImageIO.read(getClass().getResource("resources/greenCir.gif"));
redCir = ImageIO.read(getClass().getResource("resources/redCir.gif"));
recCir = ImageIO.read(getClass().getResource("resources/rec.gif"));
sequence = new Sequence(Sequence.PPQ, 4);
sequence.createTrack();
sequencer = MidiSystem.getSequencer();
sequencer.open();
sequencer.setSequence(sequence);
sequencer.recordEnable(sequencer.getSequence().getTracks()[0], 1);
df = new DecimalFormat("000");
receiver = sequencer.getReceiver();
transmitter = synth.getTransmitter();
transmitter.setReceiver(receiver);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void sustain()
{
sustain = !sustain;
if(sustain)
{
sustainB.setIcon(new ImageIcon(greenCir));
}
else
{
sustainB.setIcon(new ImageIcon(redCir));
}
}
public void octaveUp()
{
freq += 12;
octave.setText("Octave: " + (freq-60)/12);
}
public void octaveDown()
{
freq -= 12;
octave.setText("Octave: " + (freq-60)/12);
}
public void vUp()
{
if(volume < 120)
volume += 12;
volumeB.setText(setVText(volume));
}
public void vDown()
{
if(volume > 0)
volume -= 12;
volumeB.setText(setVText(volume));
}
public void resetVolume()
{
volume = VOLUME_MAX;
volumeB.setText(setVText(volume));
}
public String setVText(int v)
{
return "Volume " + volume/12 * 10 + "%";
}
public void selectInstrument()
{
instrument = (Instrument)JOptionPane.showInputDialog(null, "Choose an instrument", "", JOptionPane.PLAIN_MESSAGE, null, instruments, instruments[0]);
mc[0].programChange(instrument.getPatch().getProgram());
}
public BufferedImage getPiano()
{
URL url = this.getClass().getResource("piano.gif");
try
{
BufferedImage buffImage = ImageIO.read(url);
return buffImage;
}
catch (IOException e)
{
System.out.println("Error");
return null;
}
}
public void start(int note)
{
mc[0].noteOn(note, volume);
}
public void end(int note)
{
mc[0].noteOff(note);
}
public void endSoft(int note)
{
//mc[0].noteOff(note, velocity);
}
public void createAndShowGUI()
{
mainFrame = new JFrame("Piano Maestro");
mainFrame.setDefaultCloseOperation(0);
mainFrame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e) {System.exit(0);}
});
setupFrame(mainFrame.getContentPane());
mainFrame.pack();
mainFrame.setMinimumSize(new Dimension(500, 300));
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
mainFrame.setMinimumSize(new Dimension(iPanel.getWidth()+20, mainFrame.getHeight()));
mainFrame.setResizable(false);
}
public void setupFrame(Container pane)
{
gridBag = new GridBagLayout();
pane.setLayout(gridBag);
c = new GridBagConstraints();
sustainB = new JButton("Sustain");
sustainB.addActionListener(this);
sustainB.setActionCommand("sustain");
up = new JButton();
up.addActionListener(this);
up.setActionCommand("up");
down = new JButton();
down.addActionListener(this);
down.setActionCommand("down");
octave = new JButton("Octave: 0");
octave.addActionListener(this);
octave.setActionCommand("resetOctave");
stop = new JButton("Stop");
stop.addActionListener(this);
stop.setActionCommand("stop");
rec = new JButton("rec");
rec.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){rec();}});
load = new JButton("Load Instr.");
load.addActionListener(this);
load.setActionCommand("load");
volumeB = new JButton(setVText(volume));
volumeB.addActionListener(this);
volumeB.setActionCommand("resetVolume");
vUp = new JButton();
vUp.addActionListener(this);
vUp.setActionCommand("vUp");
vDown = new JButton();
vDown.addActionListener(this);
vDown.setActionCommand("vDown");
c.gridx = 0;
c.gridy = 0;
c.weightx = 1;
c.ipady = 10;
vPanel = new VolumePanel(vDown,volumeB,vUp);
pane.add(vPanel,c);
c.gridy = 1;
oPanel = new OctavePanel(down,octave,up);
pane.add(oPanel,c);
c.gridx = 1;
c.gridy = 0;
pane.add(sustainB,c);
c.gridx = 2;
pane.add(rec,c);
c.gridx = 1;
c.gridy = 1;
pane.add(load,c);
c.gridx = 2;
pane.add(stop,c);
c.gridy = 2;
c.gridx = 0;
c.gridwidth = 3;
try
{
sustainB.setIcon(new ImageIcon(ImageIO.read(getClass().getResource("resources/redCir.gif"))));
up.setIcon(new ImageIcon(ImageIO.read(getClass().getResource("resources/up.gif"))));
vUp.setIcon(new ImageIcon(ImageIO.read(getClass().getResource("resources/up.gif"))));
down.setIcon(new ImageIcon(ImageIO.read(getClass().getResource("resources/down.gif"))));
vDown.setIcon(new ImageIcon(ImageIO.read(getClass().getResource("resources/down.gif"))));
stop.setIcon(new ImageIcon(ImageIO.read(getClass().getResource("resources/square.gif"))));
rec.setIcon(new ImageIcon(ImageIO.read(getClass().getResource("resources/rec.gif"))));
iPanel = new ImagePanel("resources/piano.gif");
pane.add(iPanel,c);
}
catch (Exception e)
{
e.printStackTrace();
}
aIcon = new AnimatedIcon(rec,750,1,new ImageIcon(this.getClass().getResource("resources/recOn.gif")),new ImageIcon(this.getClass().getResource("resources/recOff.gif")));
load.setPreferredSize(sustainB.getPreferredSize());
rec.setPreferredSize(stop.getPreferredSize());
octave.setPreferredSize(volumeB.getPreferredSize());
volumeB.setPreferredSize(volumeB.getPreferredSize());
volumeB.setText(setVText(volume));
}
public void rec()
{
recording = true;
rec.setIcon(aIcon);
aIcon.start();
sequencer.startRecording();
}
public void stop()
{
if(recording)
{
aIcon.stop();
rec.setIcon(new ImageIcon(recCir));
sequencer.stop();
if(sequence!=null)
{
file = new File("Song" + df.format(count) + ".midi");
while(file.exists())
{
count++;
file = new File("Song" + df.format(count) + ".midi");
}
try
{
MidiSystem.write(sequence, 1, file);
}
catch (IOException e)
{
JOptionPane.showMessageDialog(null, "Your system is unable to write files.","Error",2);
}
}
else
{
JOptionPane.showMessageDialog(null, "Your system is unable to write files.","Error",2);
}
}
mc[0].allNotesOff();
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("sustain"))
{
sustain();
}
if(e.getActionCommand().equals("up"))
{
octaveUp();
}
if(e.getActionCommand().equals("down"))
{
octaveDown();
}
if(e.getActionCommand().equals("resetOctave"))
{
freq = 60;
octave.setText("Octave: " + (freq-60)/12);
}
if(e.getActionCommand().equals("load"))
{
this.selectInstrument();
}
if(e.getActionCommand().equals("piano"))
{
mc[0].programChange(instruments[0].getPatch().getProgram());
}
if(e.getActionCommand().equals("stop"))
{
stop();
}
if(e.getActionCommand().equals("vUp"))
{
vUp();
}
if(e.getActionCommand().equals("vDown"))
{
vDown();
}
if(e.getActionCommand().equals("resetVolume"))
{
resetVolume();
}
}
}

Related

How could I make my Simulator buttons appear?

The buttons originally do appear in my original code (which I have not refactored):
package oose.vcs;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import javax.swing.Timer;
import javax.swing.UIManager;
import vehicle.types.Airplane;
import vehicle.types.Bicycle;
import vehicle.types.Boat;
import vehicle.types.Bus;
import vehicle.types.Car;
import vehicle.types.Helicopter;
import vehicle.types.Motorcycle;
import vehicle.types.Ship;
import vehicle.types.Train;
import vehicle.types.Tram;
import vehicle.types.Truck;
import vehicle.types.Vehicle;
public class Controller {
private Vehicle vehicle;
private String[] vehicles = { "Boat", "Ship", "Truck", "Motorcycle", "Bus", "Car", "Bicycle", "Helicopter", "Airplane", "Tram", "Train"};
private Simulator simulationPane;
private JLabel speedlabel;
private JButton button1;
private JButton button2;
private JButton button3;
private JButton button4;
private JButton button5;
private JComboBox<String> combobox;
private JFrame frame;
private boolean accelerate, decelerate, cruise,stop;
int currentvelocity = 1;
int maximumvelocity = 300;
public static void main(String args[]) {
new Controller();
}
public Controller() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName() );
} catch (Exception e) {
e.printStackTrace();
}
frame = new JFrame("Vehicle Control System");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
combobox = new JComboBox<String>(vehicles);
combobox.setSelectedIndex(6);
combobox.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
int selectedIndex = combobox.getSelectedIndex();
String vehicleName = vehicles[selectedIndex];
initialiseVehicle(vehicleName);
}
});
speedlabel = new JLabel(" ");
configStart();
configAccelerate();
configDecelerate();
configCruise();
configStop();
JToolBar toolBar =new JToolBar();
toolBar.setRollover(true);
toolBar.add(combobox);
toolBar.add(speedlabel);
toolBar.add(button1);
toolBar.add(button2);
toolBar.add(button3);
toolBar.add(button4);
toolBar.add(button5);
frame.add(toolBar,BorderLayout.NORTH);
frame.setPreferredSize(new Dimension(800,200));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
private void configStart() {
button1 = new JButton("start");
button1.setBackground(Color.lightGray);
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(vehicle == null) {
int selectedIndex = combobox.getSelectedIndex();
String vehicleName = vehicles[selectedIndex];
initialiseVehicle(vehicleName);
speedlabel.setText(vehicle.printSpeed());
}
if(simulationPane !=null) {
frame.remove(simulationPane);
}
accelerate = false;
decelerate = false;
cruise = false;
stop = false;
button1.setBackground(Color.GREEN);
button2.setBackground(Color.lightGray);
button3.setBackground(Color.lightGray);
button4.setBackground(Color.lightGray);
button5.setBackground(Color.lightGray);
simulationPane = new Simulator();
frame.add(simulationPane,BorderLayout.CENTER);
frame.revalidate();
frame.repaint();
}
});
}
private void configAccelerate() {
button2 = new JButton("accelerate");
button2.setBackground(Color.lightGray);
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
accelerate = true;
decelerate = false;
cruise = false;
stop = false;
button1.setBackground(Color.lightGray);
button2.setBackground(Color.green);
button3.setBackground(Color.lightGray);
button4.setBackground(Color.lightGray);
button5.setBackground(Color.lightGray);
Thread thread = new Thread(){
public void run(){
try {
while(accelerate) {
Thread.sleep(2 * 1000);
if(currentvelocity<=maximumvelocity) {
currentvelocity = currentvelocity +1;
vehicle.setCurrentSpeed(currentvelocity);
speedlabel.setText(vehicle.printSpeed());
simulationPane.updateTimer();
}
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}
});
}
private void configCruise() {
button3 = new JButton("cruise");
button3.setBackground(Color.lightGray);
button3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
accelerate = false;
decelerate = false;
cruise = true;
stop = false;
button1.setBackground(Color.lightGray);
button2.setBackground(Color.lightGray);
button3.setBackground(Color.green);
button4.setBackground(Color.lightGray);
button5.setBackground(Color.lightGray);
}
});
}
private void configDecelerate() {
button4 = new JButton("decelerate");
button4.setBackground(Color.lightGray);
button4.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
accelerate = false;
decelerate = true;
cruise = false;
stop = false;
button1.setBackground(Color.lightGray);
button2.setBackground(Color.lightGray);
button3.setBackground(Color.lightGray);
button4.setBackground(Color.green);
button5.setBackground(Color.lightGray);
Thread thread = new Thread(){
public void run(){
try {
while(decelerate) {
Thread.sleep(2 * 1000);
if(currentvelocity >1) {
currentvelocity = currentvelocity -1;
vehicle.setCurrentSpeed(currentvelocity);
speedlabel.setText(vehicle.printSpeed());
simulationPane.updateTimer();
}
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}
});
}
private void configStop() {
button5 = new JButton("stop");
button5.setBackground(Color.lightGray);
button5.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
accelerate = false;
decelerate = false;
cruise = false;
stop = true;
button1.setBackground(Color.lightGray);
button2.setBackground(Color.lightGray);
button3.setBackground(Color.lightGray);
button4.setBackground(Color.lightGray);
button5.setBackground(Color.green);
currentvelocity = 1;
vehicle.setCurrentSpeed(currentvelocity);
speedlabel.setText(vehicle.printSpeed());
simulationPane.updateTimer();
}
});
}
private void initialiseVehicle(String vehicleName) {
if(vehicleName.equals("Boat")) {
vehicle = new Boat("Apollo ");
}
else if(vehicleName.equals("Ship")) {
vehicle = new Ship("Cruizz");
}
else if(vehicleName.equals("Truck")) {
vehicle = new Truck("Ford F-650");
}
else if(vehicleName.equals("Motorcycle")) {
vehicle = new Motorcycle("Suzuki");
}
else if(vehicleName.equals("Bus")) {
vehicle = new Bus("Aero");
}
else if(vehicleName.equals("Car")) {
vehicle = new Car("BMW");
}
else if(vehicleName.equals("Bicycle")) {
vehicle = new Bicycle("A-bike");
}
else if(vehicleName.equals("Helicopter")) {
vehicle = new Helicopter("Eurocopter");
}
else if(vehicleName.equals("Airplane")) {
vehicle = new Airplane("BA");
}
else if(vehicleName.equals("Tram")) {
vehicle = new Tram("EdinburghTram");
}
else if(vehicleName.equals("Train")) {
vehicle = new Train("Virgin",4);
}
}
public class Simulator extends JPanel {
private BufferedImage boat;
private int xPos = 0;
private int direction = 1;
private File file;
private Timer timer;
public Simulator() {
setDisplayObject();
try {
boat = ImageIO.read(file);
timer = new Timer(maximumvelocity/currentvelocity, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
xPos += direction;
if (xPos + boat.getWidth() > getWidth()) {
xPos = 0;
direction *= -1;
} else if (xPos < 0) {
xPos = 0;
direction *= -1;
}
repaint();
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void updateTimer() {
timer.setDelay(maximumvelocity/currentvelocity);
}
private void setDisplayObject() {
if(vehicle instanceof Boat) {
file = new File(System.getProperty("user.dir")+"/img/boat.png");
}
else if(vehicle instanceof Ship) {
file = new File(System.getProperty("user.dir")+"/img/ship.png");
}
else if(vehicle instanceof Truck) {
file = new File(System.getProperty("user.dir")+"/img/truck.png");
}
else if(vehicle instanceof Motorcycle) {
file = new File(System.getProperty("user.dir")+"/img/motorcycle.png");
}
else if(vehicle instanceof Bus) {
file = new File(System.getProperty("user.dir")+"/img/bus.png");
}
else if(vehicle instanceof Car) {
file = new File(System.getProperty("user.dir")+"/img/car.png");
}
else if(vehicle instanceof Bicycle) {
file = new File(System.getProperty("user.dir")+"/img/bicycle.png");
}
else if(vehicle instanceof Helicopter) {
file = new File(System.getProperty("user.dir")+"/img/helicopter.png");
}
else if(vehicle instanceof Airplane) {
file = new File(System.getProperty("user.dir")+"/img/airplane.png");
}
else if(vehicle instanceof Tram) {
file = new File(System.getProperty("user.dir")+"/img/tram.png");
}
else if(vehicle instanceof Train) {
file = new File(System.getProperty("user.dir")+"/img/train.png");
}
}
#Override
public Dimension getPreferredSize() {
return boat == null ? super.getPreferredSize() : new Dimension(boat.getWidth() * 4, boat.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int y = getHeight() - boat.getHeight();
g.drawImage(boat, xPos, y, this);
}
}
}
However, after refactoring the buttons, they no longer appear on the simulator:
package oose.vcs;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import javax.swing.Timer;
import javax.swing.UIManager;
import vehicle.types.Airplane;
import vehicle.types.Bicycle;
import vehicle.types.Boat;
import vehicle.types.Bus;
import vehicle.types.Car;
import vehicle.types.Helicopter;
import vehicle.types.Motorcycle;
import vehicle.types.Ship;
import vehicle.types.Train;
import vehicle.types.Tram;
import vehicle.types.Truck;
import vehicle.types.Vehicle;
import java.util.HashMap;
import java.util.Map;
public class Controller {
enum ButtonState {
Start,
Accelerate,
Cruise,
Decelerate,
Stop;
}
static Vehicle vehicle;
static String[] vehicles = { "Boat", "Ship", "Truck", "Motorcycle", "Bus", "Car", "Bicycle", "Helicopter", "Airplane", "Tram", "Train"};
private Simulator simulationPane;
private JLabel speedlabel;
private JComboBox<String> combobox;
private JFrame frame;
private JButton[] buttons;
private ButtonState state;
private boolean accelerate, decelerate;
static int currentvelocity = 1;
static int maximumvelocity = 300;
static String vehicleName;
static int selectedIndex;
public static void main(String args[]) {
new Controller();
}
public Controller() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName() );
} catch (Exception e) {
e.printStackTrace();
}
frame = new JFrame("Vehicle Control System");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
combobox = new JComboBox<String>(vehicles);
combobox.setSelectedIndex(6);
combobox.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
int selectedIndex = combobox.getSelectedIndex();
vehicleName = vehicles[selectedIndex];
initialiseVehicle(vehicleName);
}
});
speedlabel = new JLabel(" ");
configButtons();
JToolBar toolBar =new JToolBar();
toolBar.setRollover(true);
toolBar.add(combobox);
toolBar.add(speedlabel);
frame.add(toolBar,BorderLayout.NORTH);
frame.setPreferredSize(new Dimension(800,200));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
private void setState(ButtonState state) {
this.buttons[this.state.ordinal()].setBackground(Color.lightGray);
this.buttons[state.ordinal()].setBackground(Color.green);
this.state = state;
}
private void configButtons() {
this.buttons = new JButton[ButtonState.values().length];
for (ButtonState state : ButtonState.values()) {
JButton button = new JButton(state.name().toLowerCase());
button.setBackground(Color.lightGray);
switch(state) {
case Start:
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
start(e);
}
});
break;
case Accelerate:
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
accelerate(e);
}
});
break;
case Cruise:
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cruise(e);
}
});
break;
case Decelerate:
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
decelerate(e);
}
});
break;
case Stop:
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
stop(e);
}
});
break;
}
this.buttons[state.ordinal()] = button;
}
}
private void start(ActionEvent e) {
if(vehicle == null) {
selectedIndex = combobox.getSelectedIndex();
String vehicleName = vehicles[selectedIndex];
initialiseVehicle(vehicleName);
speedlabel.setText(vehicle.printSpeed());
}
if(simulationPane !=null) {
frame.remove(simulationPane);
}
this.setState(ButtonState.Start);
simulationPane = new Simulator();
frame.add(simulationPane,BorderLayout.CENTER);
frame.revalidate();
frame.repaint();
}
private void accelerate(ActionEvent e) {
this.setState(ButtonState.Accelerate);
Thread thread = new Thread(){
public void run(){
try {
while(accelerate) {
Thread.sleep(2 * 1000);
if(currentvelocity<=maximumvelocity) {
currentvelocity = currentvelocity +1;
vehicle.setCurrentSpeed(currentvelocity);
speedlabel.setText(vehicle.printSpeed());
simulationPane.updateTimer();
}
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}
private void cruise(ActionEvent e) {
this.setState(ButtonState.Cruise);
}
private void decelerate(ActionEvent e) {
this.setState(ButtonState.Decelerate);
Thread thread = new Thread(){
public void run(){
try {
while(decelerate) {
Thread.sleep(2 * 1000);
if(currentvelocity >1) {
currentvelocity = currentvelocity -1;
vehicle.setCurrentSpeed(currentvelocity);
speedlabel.setText(vehicle.printSpeed());
simulationPane.updateTimer();
}
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}
private void stop(ActionEvent e) {
this.setState(ButtonState.Stop);
currentvelocity = 1;
vehicle.setCurrentSpeed(currentvelocity);
speedlabel.setText(vehicle.printSpeed());
simulationPane.updateTimer();
}
public void initialiseVehicle(String vehicleName){
// Create a hashmap with key value pairs
Map<String,Vehicle> objectMap = new HashMap<String, Vehicle>();
// Add all the items into this map
objectMap.put("Airplane",new Airplane("BA"));
objectMap.put("Tram",new Tram("EdinburghTram"));
objectMap.put("Train",new Train("Virgin",4));
objectMap.put("Helicopter",new Helicopter("Eurocopter"));
objectMap.put("Bicycle",new Bicycle("A-bike"));
objectMap.put("Car",new Car("BMW"));
objectMap.put("Bus",new Bus("Aero"));
objectMap.put("Motorcycle",new Motorcycle("Suzuki"));
objectMap.put("Truck",new Truck("Ford F-650"));
objectMap.put("Ship",new Ship("Cruizz"));
objectMap.put("Boat", new Boat("Apollo"));
// checks if the item exist in the map
if(objectMap.containsKey(vehicleName)){
vehicle = objectMap.get(vehicleName);
}
}
private class Simulator extends JPanel {
private static final long serialVersionUID = 8809852587026347126L;
private BufferedImage boat;
private int xPos = 0;
private int direction = 1;
protected File file;
private Timer timer;
public Simulator() {
setDisplayObject();
try {
boat = ImageIO.read(file);
timer = new Timer(Controller.maximumvelocity/Controller.currentvelocity, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
xPos += direction;
if (xPos + boat.getWidth() > getWidth()) {
xPos = 0;
direction *= -1;
} else if (xPos < 0) {
xPos = 0;
direction *= -1;
}
repaint();
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void updateTimer() {
timer.setDelay(Controller.maximumvelocity/Controller.currentvelocity);
}
private void setDisplayObject() {
if(vehicle instanceof Boat) {
file = new File(System.getProperty("user.dir")+"/img/boat.png");
}
else if(vehicle instanceof Ship) {
file = new File(System.getProperty("user.dir")+"/img/ship.png");
}
else if(vehicle instanceof Truck) {
file = new File(System.getProperty("user.dir")+"/img/truck.png");
}
else if(vehicle instanceof Motorcycle) {
file = new File(System.getProperty("user.dir")+"/img/motorcycle.png");
}
else if(vehicle instanceof Bus) {
file = new File(System.getProperty("user.dir")+"/img/bus.png");
}
else if(vehicle instanceof Car) {
file = new File(System.getProperty("user.dir")+"/img/car.png");
}
else if(vehicle instanceof Bicycle) {
file = new File(System.getProperty("user.dir")+"/img/bicycle.png");
}
else if(vehicle instanceof Helicopter) {
file = new File(System.getProperty("user.dir")+"/img/helicopter.png");
}
else if(vehicle instanceof Airplane) {
file = new File(System.getProperty("user.dir")+"/img/airplane.png");
}
else if(vehicle instanceof Tram) {
file = new File(System.getProperty("user.dir")+"/img/tram.png");
}
else if(vehicle instanceof Train) {
file = new File(System.getProperty("user.dir")+"/img/train.png");
}
}
#Override
public Dimension getPreferredSize() {
return boat == null ? super.getPreferredSize() : new Dimension(boat.getWidth() * 4, boat.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int y = getHeight() - boat.getHeight();
g.drawImage(boat, xPos, y, this);
}
}
}
May I ask what could have gone wrong and how I could modify my refactored code?
Here are example of what the vehicle classes look like (essentially getters and setters):
package vehicle.types;
public abstract class Aircraft extends Vehicle{
private double steering;
public Aircraft(String name) {
setName(name);
setType(Type.SKIED);
}
#Override
public void streer(double degree, double speed) {
setCurrentSpeed(speed);
setSteering(degree);
}
#Override
public String printSpeed() {
return getCurrentSpeed()+"km/hr";
}
public double getSteering() {
return steering;
}
public void setSteering(double degrees) {
this.steering = degrees;
}
}
package vehicle.types;
public class Airplane extends Aircraft {
public Airplane(String name) {
super(name);
}
}
In the original code you were adding the buttons to the toolbar
toolBar.add(button1);
toolBar.add(button2);
toolBar.add(button3);
...
But in the refactored code you don't do that anymore. I guess you could add them in configButtons() while you are looping through them.

How to calculate a total depending on what a user seletcs in the combobox?

I want the user to select options from a combo box and based on what they select the output field will calculate the price in it.
For example if they select Intel Core i5 it will add $50 to the calculated price
They error I have is that my output box is adding only the highest/last values together.
My three combo boxes are name Processor, Memory, Disk
the box I want the price to calculate in is named Output
i mainly just need help with how to select the options in my combo boxes in the if statements
private void calculateButtonActionPerformed(java.awt.event.ActionEvent evt) {
double price; //initilize variable
double windowsUpgrade; //Initilize variable
double processorPrice;
double memoryPrice;
double diskPrice;
if(Processor.getSelectedItem().equals("Intel Core i3"));
{
processorPrice = 0;
}
if(Processor.getSelectedItem().equals("Intel Core i5"));
{
processorPrice = 50;
}
if(Processor.getSelectedItem().equals("Intel Core i7"));
{
processorPrice = 150;
}
if(Memory.getSelectedItem().equals("4GB"));
{
memoryPrice = 0;
}
if(Memory.getSelectedItem().equals("8GB"));
{
memoryPrice = 50;
}
if(Memory.getSelectedItem().equals("16GB"));
{
memoryPrice = 100;
}
if(Memory.getSelectedItem().equals("32GB"));
{
memoryPrice = 150;
}
if(Disk.getSelectedItem().equals("1TB"));
{
diskPrice = 0;
}
if(Disk.getSelectedItem().equals("2TB"));
{
diskPrice = 50;
}
if(Disk.getSelectedItem().equals("512GB SSD"));
{
diskPrice = 150;
}
double calculation;
calculation = processorPrice + memoryPrice + diskPrice;
NumberFormat currency = NumberFormat.getCurrencyInstance();
String message =
currency.format(calculation);
Output.setText(message);
}
Here is the code.
You could use listener which react on your selection.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
class ComboBoxTest
{
//A reference to the UI class where you initialize the buttons,
//combo box etc
private ComboBoxUI _ui;
private double _processorPrice;
private double _memoryPrice;
private double _diskPrice;
public ComboBoxTest()
{
_processorPrice = 0;
_memoryPrice = 0;
_diskPrice = 0;
_ui = new ComboBoxUI();
registerListener();
}
//Register three different comboBoxes and a button for
//the calculation to listener
private void registerListener()
{
_ui.getProcessorBox().addItemListener(new ItemListener()
{
#Override
public void itemStateChanged(ItemEvent e)
{
if (e.getItem().equals("Intel Core i3"))
{
_processorPrice = 0;
}
else if (e.getItem().equals("Intel Core i5"))
{
_processorPrice = 50;
}
else if (e.getItem().equals("Intel Core i7"))
{
_processorPrice = 150;
}
}
});
_ui.getMemoryBox().addItemListener(new ItemListener()
{
#Override
public void itemStateChanged(ItemEvent e)
{
if (e.getItem().equals("4GB"))
{
_memoryPrice = 0;
}
else if (e.getItem().equals("8GB"))
{
_memoryPrice = 50;
}
else if (e.getItem().equals("16GB"))
{
_memoryPrice = 100;
}
else if (e.getItem().equals("32GB"))
{
_memoryPrice = 150;
}
}
});
_ui.getDiscBox().addItemListener(new ItemListener()
{
#Override
public void itemStateChanged(ItemEvent e)
{
if (e.getItem().equals("1TB"))
{
_diskPrice = 0;
}
else if (e.getItem().equals("2TB"))
{
_diskPrice = 50;
}
else if (e.getItem().equals("512GB SSD"))
{
_diskPrice = 150;
}
}
});
//getCalcButton() is a new Button that calcualtes the price
_ui.getCalcButton().addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.out.println(_processorPrice + _memoryPrice + _diskPrice);
}
});
}
}
With my example you need a UI class of your components. Something like this :)
import java.awt.BorderLayout;
import javax.swing.*;
public class ComboBoxUI
{
JFrame _frame;
JPanel _componentPanel;
JButton _calcButton;
JComboBox _procBox;
JComboBox _memBox;
JComboBox _discBox;
ComboBoxUI()
{
initFrame();
initComponenentPanel();
showGui();
}
//initialize a new JFrame with BorderLayout in this example
private void initFrame()
{
_frame = new JFrame("Title");
_frame.setLayout(new BorderLayout());
}
//initialize a new JPanel with your components like comboBox, buttons...
private void initComponenentPanel()
{
_componentPanel = new JPanel();
String[] proc = { "Intel Core i3", "Intel Core i5", "Intel Core i7"};
_procBox = new JComboBox(proc);
String[] memory = { "4GB", "8GB", "16GB", "32GB"};
_memBox = new JComboBox(memory);
String[] disc = { "1TB", "2TB", "512GB SSD"};
_discBox = new JComboBox(disc);
_calcButton = new JButton("Calculate");
_componentPanel.add(_procBox);
_componentPanel.add(_memBox);
_componentPanel.add(_discBox);
_componentPanel.add(_calcButton);
_frame.add(_componentPanel, BorderLayout.NORTH);
}
//Set the size of your JFrame and make it visible
private void showGui()
{
_frame.setSize(500, 200);
_frame.setVisible(true);
_frame.setDefaultCloseOperation(_frame.EXIT_ON_CLOSE);
}
public JComboBox getProcessorBox()
{
return _procBox;
}
public JComboBox getMemoryBox()
{
return _memBox;
}
public JComboBox getDiscBox()
{
return _discBox;
}
public JButton getCalcButton()
{
return _calcButton;
}
}

Why wont my simon game work and what do i need to do so it works

Im making a simon game and i have no idea what to do. I got sound and all that good stuff working but as for everything else I have no idea what im doing. I need some help making the buttons work and flash in the right order. (comments are failed attempts) Any help is very much appreciated.
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.*;
import javax.swing.border.*;
import java.util.Random;
import java.applet.*;
import java.util.ArrayList;
public class Game extends JFrame
{
JButton button1, button2, button3, button4, button5;
JLabel label1, label2, label3;
JPanel panel1, panel2;
File wavFile1 = new File("NewRing1.wav");
File wavFile2 = new File("NewRing2.wav");
File wavFile3 = new File("NewRing3.wav");
File wavFile4 = new File("NewRing4.wav");
AudioClip sound1;
AudioClip sound2;
AudioClip sound3;
AudioClip sound4;
int sequence1;
int[] anArray;
public Game()
{
anArray = new int[1000];
GridLayout grid = new GridLayout(3, 2);
this.getContentPane().setLayout(grid);
Container theContainer = this.getContentPane();
EtchedBorder edge = new EtchedBorder(EtchedBorder.RAISED);
button1 = new JButton();
button1.setForeground(Color.BLACK);
button1.setBackground(Color.RED);
button2 = new JButton();
button2.setForeground(Color.BLACK);
button2.setBackground(Color.BLUE);
button3 = new JButton();
button3.setForeground(Color.BLACK);
button3.setBackground(Color.GREEN);
button4 = new JButton();
button4.setForeground(Color.BLACK);
button4.setBackground(Color.YELLOW);
button5 = new JButton("Begin");
label1 = new JLabel("Score");
label2 = new JLabel("High Score");
label3 = new JLabel("Follow The Pattern");
panel1 = new JPanel();
panel1.add(label1);
panel1.add(label2);
panel2 = new JPanel();
panel2.add(label3);
panel2.add(button5);
button1.setBorder(edge);
button2.setBorder(edge);
button3.setBorder(edge);
button4.setBorder(edge);
label1.setBorder(edge);
label2.setBorder(edge);
panel1.setBorder(edge);
panel2.setBorder(edge);
label3.setBorder(edge);
theContainer.add(panel1);
theContainer.add(panel2);
theContainer.add(button1);
theContainer.add(button2);
theContainer.add(button3);
theContainer.add(button4);
Button1Handler handleButton1 = new Button1Handler();
button1.addActionListener(handleButton1);
Button2Handler handleButton2 = new Button2Handler();
button2.addActionListener(handleButton2);
Button3Handler handleButton3 = new Button3Handler();
button3.addActionListener(handleButton3);
Button4Handler handleButton4 = new Button4Handler();
button4.addActionListener(handleButton4);
Button5Handler handleButton5 = new Button5Handler();
button5.addActionListener(handleButton5);
try{sound1 = Applet.newAudioClip(wavFile1.toURL());}
catch(Exception e){e.printStackTrace();}
try{sound2 = Applet.newAudioClip(wavFile2.toURL());}
catch(Exception e){e.printStackTrace();}
try{sound3 = Applet.newAudioClip(wavFile3.toURL());}
catch(Exception e){e.printStackTrace();}
try{sound4 = Applet.newAudioClip(wavFile4.toURL());}
catch(Exception e){e.printStackTrace();}
setVisible(true);
}
public class Button1Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
sound1.play();
}
}
public class Button2Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
sound2.play();
}
}
public class Button3Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
sound3.play();
}
}
public class Button4Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
sound4.play();
}
}
/*
public static int[] buttonClicks(int[] anArray)
{
return anArray;
}
*/
public class Button5Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
for (int i = 1; i <= 159; i++)
{
Random rand = new Random();
int randomNum = rand.nextInt(40) % 4 + 1;
anArray[i] = randomNum;
System.out.println("Element at index: "+ i + " Is: " + anArray[i]);
}
buttonClicks(anArra[3]);
/*
for (int i = 1; i <= 100; i++)
{
Random rand = new Random();
int randomNum = rand.nextInt((4 - 1) + 1) + 1;
if(randomNum == 1)
{
button1.doClick();
sequence1 = 1;
System.out.println(sequence1);
}
else if(randomNum == 2)
{
button2.doClick();
sequence1 = 2;
System.out.println(sequence1);
}
else if(randomNum == 3)
{
button3.doClick();
sequence1 = 3;
System.out.println(sequence1);
}
else
{
button4.doClick();
sequence1 = 4;
System.out.println(sequence1);
}
}
*/
}
}
}
Below is some code to get you started. The playback of the sequences is executed in a separate thread, as you need to use delays in between. This code is by no means ideal. You should use better names for the variables and refactor to try to create a better and more encapsulated game model. Maybe you could use this opportunity to learn about the MVC design pattern?
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.*;
import javax.swing.border.*;
import java.util.Random;
import java.applet.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Game extends JFrame {
JButton button1, button2, button3, button4, button5;
JLabel label1, label2, label3;
JPanel panel1, panel2;
File wavFile1 = new File("NewRing1.wav");
File wavFile2 = new File("NewRing2.wav");
File wavFile3 = new File("NewRing3.wav");
File wavFile4 = new File("NewRing4.wav");
AudioClip sound1;
AudioClip sound2;
AudioClip sound3;
AudioClip sound4;
int level;
int score;
int[] anArray;
int currentArrayPosition;
public Game() {
GridLayout grid = new GridLayout(3, 2);
this.getContentPane().setLayout(grid);
Container theContainer = this.getContentPane();
EtchedBorder edge = new EtchedBorder(EtchedBorder.RAISED);
level = 0;
score = 0;
button1 = new JButton();
button1.setForeground(Color.BLACK);
button1.setBackground(Color.RED);
button2 = new JButton();
button2.setForeground(Color.BLACK);
button2.setBackground(Color.BLUE);
button3 = new JButton();
button3.setForeground(Color.BLACK);
button3.setBackground(Color.GREEN);
button4 = new JButton();
button4.setForeground(Color.BLACK);
button4.setBackground(Color.YELLOW);
button5 = new JButton("Begin");
label1 = new JLabel("Score: " + String.valueOf(score));
label2 = new JLabel("High Score");
label3 = new JLabel("Follow The Pattern");
panel1 = new JPanel();
panel1.add(label1);
panel1.add(label2);
panel2 = new JPanel();
panel2.add(label3);
panel2.add(button5);
button1.setBorder(edge);
button2.setBorder(edge);
button3.setBorder(edge);
button4.setBorder(edge);
label1.setBorder(edge);
label2.setBorder(edge);
panel1.setBorder(edge);
panel2.setBorder(edge);
label3.setBorder(edge);
theContainer.add(panel1);
theContainer.add(panel2);
theContainer.add(button1);
theContainer.add(button2);
theContainer.add(button3);
theContainer.add(button4);
Button1Handler handleButton1 = new Button1Handler();
button1.addActionListener(handleButton1);
Button2Handler handleButton2 = new Button2Handler();
button2.addActionListener(handleButton2);
Button3Handler handleButton3 = new Button3Handler();
button3.addActionListener(handleButton3);
Button4Handler handleButton4 = new Button4Handler();
button4.addActionListener(handleButton4);
Button5Handler handleButton5 = new Button5Handler();
button5.addActionListener(handleButton5);
try {
sound1 = Applet.newAudioClip(wavFile1.toURL());
} catch (Exception e) {
e.printStackTrace();
}
try {
sound2 = Applet.newAudioClip(wavFile2.toURL());
} catch (Exception e) {
e.printStackTrace();
}
try {
sound3 = Applet.newAudioClip(wavFile3.toURL());
} catch (Exception e) {
e.printStackTrace();
}
try {
sound4 = Applet.newAudioClip(wavFile4.toURL());
} catch (Exception e) {
e.printStackTrace();
}
setVisible(true);
}
public class Button1Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
sound1.play();
buttonClicked(button1);
}
}
public class Button2Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
sound2.play();
buttonClicked(button2);
}
}
public class Button3Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
sound3.play();
buttonClicked(button3);
}
}
public class Button4Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
sound4.play();
buttonClicked(button4);
}
}
private void buttonClicked(JButton clickedButton) {
if (isCorrectButtonClicked(clickedButton)) {
currentArrayPosition++;
addToScore(1);
if (currentArrayPosition == anArray.length) {
playNextSequence();
} else {
}
} else {
JOptionPane.showMessageDialog(this, String.format("Your scored %s points", score));
score = 0;
level = 0;
label1.setText("Score: " + String.valueOf(score));
}
}
private boolean isCorrectButtonClicked(JButton clickedButton) {
int correctValue = anArray[currentArrayPosition];
if (clickedButton.equals(button1)) {
return correctValue == 1;
} else if (clickedButton.equals(button2)) {
return correctValue == 2;
} else if (clickedButton.equals(button3)) {
return correctValue == 3;
} else if (clickedButton.equals(button4)) {
return correctValue == 4;
} else {
return false;
}
}
public class Button5Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
playNextSequence();
}
}
private void playNextSequence() {
level++;
currentArrayPosition = 0;
anArray = createSequence(level);
(new Thread(new SequenceButtonClicker())).start();
}
private int[] createSequence(int sequenceLength) {
int[] sequence = new int[sequenceLength];
for (int i = 0; i < sequenceLength; i++) {
Random rand = new Random();
int randomNum = rand.nextInt(40) % 4 + 1;
sequence[i] = randomNum;
}
return sequence;
}
private JButton getButtonFromInt(int sequenceNumber) {
switch (sequenceNumber) {
case 1:
return button1;
case 2:
return button2;
case 3:
return button3;
case 4:
return button4;
default:
return button1;
}
}
private void flashButton(JButton button) throws InterruptedException {
Color originalColor = button.getBackground();
button.setBackground(new Color(255, 255, 255, 200));
Thread.sleep(250);
button.setBackground(originalColor);
}
private void soundButton(JButton button) {
if (button.equals(button1)) {
sound1.play();
} else if (button.equals(button2)) {
sound2.play();
} else if (button.equals(button3)) {
sound3.play();
} else if (button.equals(button4)) {
sound4.play();
}
}
private void addToScore(int newPoints) {
score += newPoints;
label1.setText("Score: " + String.valueOf(score));
}
private class SequenceButtonClicker implements Runnable {
public void run() {
for (int i = 0; i < anArray.length; i++) {
try {
JButton nextButton = getButtonFromInt(anArray[i]);
soundButton(nextButton);
flashButton(nextButton);
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Game.class.getName()).log(Level.SEVERE, "Interrupted", ex);
}
}
}
}
}

Can resume Thread But unable to stop completly

I have finally been able to get my thread to resume after some excellent advice from you guys, but am unable to stop it.. It seems to be locked still but i cannot get it to stop gracefully. here is the whole class so you can run it. I'm so close.. I think. I have commented out what i was attempting in the run and stopmethods
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package treadmakestop;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/**
*
* #author brett
*/
public class WorkFile {
public static void main(String[] args) {
WorkFile workFile = new WorkFile();
}
public WorkFile() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
}
JFrame frame = new JFrame("TvCOnvert");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TvGui());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setSize(350, 100);
frame.setResizable(false);
frame.setVisible(true);
}
});
}
public class TvGui extends JPanel {
private JProgressBar tvpb;
private JButton startButton;
private JButton cancelButton;
private JButton exitButton;
private Worker worker;
private Thread t;
public TvGui() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.NORTHWEST;
startButton = new JButton();
startButton.setText("Start");
gbc.insets = new Insets(10, 5, 0, 0);
gbc.gridx = 1;
gbc.gridy = 2;
gbc.weightx = 0.5;
add(startButton, gbc);
cancelButton = new JButton();
gbc.insets = new Insets(10, 0, 0, 0);
gbc.gridx = 2;
gbc.gridy = 2;
gbc.weightx = 0.5;
cancelButton.setText("Cancel");
add(cancelButton, gbc);
exitButton = new JButton();
gbc.insets = new Insets(10, 0, 0, 5);
gbc.gridx = 3;
gbc.gridy = 2;
gbc.weightx = 0.5;
exitButton.setText("Exit");
add(exitButton, gbc);
tvpb = new JProgressBar();
tvpb.setBorderPainted(true);
tvpb.setStringPainted(true);
gbc.insets = new Insets(5, 5, 0, 5);
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.gridx = 1;
gbc.gridy = 3;
gbc.gridwidth = 3;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.BASELINE;
add(tvpb, gbc);
tvpb.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
System.out.println(tvpb.getValue());
if (tvpb.getValue() >= 100) {
worker = null;
}
}
});
tvpb.addPropertyChangeListener("value", new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
}
});
startButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (worker == null) {
worker = new Worker(tvpb);
t = new Thread(worker);
t.start();
}
}
});
cancelButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
worker.pause();
tvpb.setIndeterminate(true);
int n = JOptionPane.showConfirmDialog(
null,
"Sure you want to delete this process?",
"Kill Operation",
JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.YES_OPTION) {
worker.stop();
//t.interrupt();
//worker = null;
tvpb.setIndeterminate(false);
tvpb.setValue(0);
} else if (n == JOptionPane.NO_OPTION) {
tvpb.setIndeterminate(false);
worker.resume();
}
}
});
exitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
}
public class Worker implements Runnable {
TvGui gu = new TvGui();
private ReentrantLock pauseLock;
private Condition pauseCondition;
private AtomicBoolean paused;
private JProgressBar tvpg;
public Worker(JProgressBar tvpg) {
paused = new AtomicBoolean();
pauseLock = new ReentrantLock();
pauseCondition = pauseLock.newCondition();
this.tvpg = tvpg;
}
public void pause() {
paused.set(true);
}
public void resume() {
paused.set(false);
pauseLock.lock();
try {
pauseCondition.signal();
} finally {
pauseLock.unlock();
}
}
public synchronized void stop(){
try {
// gu.t = null;
// gu.t.interrupt();
//Thread thr = Thread.currentThread();
System.out.println("Thread name is:"+" "+gu.t.getName());
Thread.currentThread().interrupt();
} catch (Exception e) {
}
}
private volatile boolean threadSuspended;
#Override
public void run() {
Thread thisThread = Thread.currentThread();
while ( gu.t == thisThread) {
try {
Thread.sleep(1);
synchronized(this) {
while (threadSuspended && gu.t ==thisThread)
wait();
}
} catch (InterruptedException e){
}
}
int times = 100_000;
for (int i = 0; i <= times; i++) {
checkPauseState();
updateProgress(Math.round((i / (float) times) * 100f));
try {
Thread.sleep(1);
} catch (InterruptedException ex) {
}
}
}
protected void checkPauseState() {
while (paused.get()) {
pauseLock.lock();
try {
pauseCondition.await();
} catch (Exception e) {
} finally {
pauseLock.unlock();
}
}
}
protected void updateProgress(int progress) {
if (EventQueue.isDispatchThread()) {
tvpg.setValue(progress);
} else {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
updateProgress(progress);
}
});
}
}
public boolean isPaused() {
return paused.get();
}
}
}
Unless you're actually checking the intrrupted state of the current thread, then interrupting it will have no effect...
Instead, you could use another AtomicBoolean value which indicates if the thread should continue performing it's work, for example
public class Worker implements Runnable {
//...
private AtomicBoolean keepRunning;
public Worker(JProgressBar tvpg) {
//...
keepRunning = new AtomicBoolean(true);
//...
}
//...
public synchronized void stop() {
keepRunning.set(false);
// Make sure the thread isn't currently
// paused, otherwise it will never exit...
resume();
}
//...
#Override
public void run() {
System.out.println("Runnable has started");
int times = 100_000;
int i = 0;
while (i < times && keepRunning.get()) {
checkPauseState();
updateProgress(Math.round((i / (float) times) * 100f));
try {
Thread.sleep(1);
} catch (InterruptedException ex) {
}
i++;
}
System.out.println("Runnable has exited");
}
We change the loop within the run method to accommodate the new exit condition...
for (int i = 0; i < times && keepRunning.get(); i++) {
checkPauseState();
updateProgress(Math.round((i / (float) times) * 100f));
try {
Thread.sleep(1);
} catch (InterruptedException ex) {
}
}
And the full thing...
public class Worker implements Runnable {
private ReentrantLock pauseLock;
private Condition pauseCondition;
private AtomicBoolean paused;
private AtomicBoolean keepRunning;
private JProgressBar tvpg;
public Worker(JProgressBar tvpg) {
paused = new AtomicBoolean();
keepRunning = new AtomicBoolean(true);
pauseLock = new ReentrantLock();
pauseCondition = pauseLock.newCondition();
this.tvpg = tvpg;
}
public void pause() {
paused.set(true);
}
public void resume() {
paused.set(false);
pauseLock.lock();
try {
pauseCondition.signal();
} finally {
pauseLock.unlock();
}
}
public synchronized void stop() {
keepRunning.set(false);
resume();
}
#Override
public void run() {
System.out.println("Runnable has started");
int times = 100_000;
int i = 0;
while (i < times && keepRunning.get()) {
checkPauseState();
updateProgress(Math.round((i / (float) times) * 100f));
try {
Thread.sleep(1);
} catch (InterruptedException ex) {
}
i++;
}
System.out.println("Runnable has exited");
}
protected void checkPauseState() {
while (paused.get()) {
pauseLock.lock();
try {
pauseCondition.await();
} catch (Exception e) {
} finally {
pauseLock.unlock();
}
}
}
protected void updateProgress(int progress) {
if (EventQueue.isDispatchThread()) {
tvpg.setValue(progress);
} else {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
updateProgress(progress);
}
});
}
}
public boolean isPaused() {
return paused.get();
}
}
Another solution would be to have a state value, which determined the current of the Worker class
public static class Worker implements Runnable {
public enum State {
RUNNING,
PAUSED,
NOT_STARTED,
STOPPPED,
COMPLETED;
}
private volatile State state = State.NOT_STARTED;
This provides you with more information about the current state of the Worker and also information about how it completed (did it complete naturally or was it stopped), for example...
public static class Worker implements Runnable {
public enum State {
RUNNING,
PAUSED,
NOT_STARTED,
STOPPPED,
COMPLETED;
}
private volatile State state = State.NOT_STARTED;
private ReentrantLock pauseLock;
private Condition pauseCondition;
private JProgressBar tvpg;
public Worker(JProgressBar tvpg) {
pauseLock = new ReentrantLock();
pauseCondition = pauseLock.newCondition();
this.tvpg = tvpg;
}
public void pause() {
if (state == State.RUNNING) {
state = State.PAUSED;
}
}
public void resume() {
if (state == State.PAUSED || state == State.STOPPPED) {
if (state == State.PAUSED) {
state = State.RUNNING;
}
pauseLock.lock();
try {
pauseCondition.signal();
} finally {
pauseLock.unlock();
}
}
}
public synchronized void stop() {
state = State.STOPPPED;
resume();
}
#Override
public void run() {
state = State.RUNNING;
System.out.println("Runnable has started");
int times = 100_000;
for (int i = 0; i < times && state != State.STOPPPED; i++) {
checkPauseState();
updateProgress(Math.round((i / (float) times) * 100f));
try {
Thread.sleep(1);
} catch (InterruptedException ex) {
}
}
if (state != State.STOPPPED) {
state = State.COMPLETED;
}
System.out.println("Runnable has exited");
}
protected void checkPauseState() {
while (state == State.PAUSED) {
pauseLock.lock();
try {
pauseCondition.await();
} catch (Exception e) {
} finally {
pauseLock.unlock();
}
}
}
protected void updateProgress(int progress) {
if (EventQueue.isDispatchThread()) {
tvpg.setValue(progress);
} else {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
updateProgress(progress);
}
});
}
}
public boolean isPaused() {
return state == State.PAUSED;
}
public boolean isRunning() {
return state == State.RUNNING;
}
public boolean wasStopped() {
return state == State.STOPPPED;
}
public boolean didComplete() {
return state == State.COMPLETED;
}
}
This does away with the AtomicBoolean variables in favour of the state variable...as another idea

Need to identify SwingWorker completion to stop the current process?

My aim is to select all the files named with MANI.txt which is present in their respective folders and then load path of the MANI.txt files different location in table. After I load the path in the table,I used to select needed path and modifiying those.
To load the MANI.txt files taking more time,because it may present more than 30 times in my workspace or etc. until load the files I want to give alarm to the user with help of ProgessBar.Once the list size has been populated I need to disable ProgressBar.
i came up with this ProgressBar, but progress bar operation gets complete or not, if the background process(finding files and putting their path in the table) got completed means, the result getting displayed and hiding the progress bar? i want the presence of progress bar opertion gets complete 100% in either case? please give me some ideas?how to implement it?
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class JTableHeaderCheckBox extends JFrame implements ActionListener {
protected int counter = 0;
Object colNames[] = { "", "Path" };
Object[][] data = {};
DefaultTableModel dtm;
JTable table;
JButton but;
java.util.List list;
File folder;
JProgressBar current;
JFrame fr1, frame;
int num = 0;
JProgressBar pbar;
JTableHeaderCheckBox it;
public void buildGUI() throws InterruptedException {
dtm = new DefaultTableModel(data, colNames);
table = new JTable(dtm);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
int vColIndex = 0;
TableColumn col = table.getColumnModel().getColumn(vColIndex);
int width = 10;
col.setPreferredWidth(width);
int vColIndex1 = 1;
TableColumn col1 = table.getColumnModel().getColumn(vColIndex1);
int width1 = 500;
col1.setPreferredWidth(width1);
JFileChooser chooser = new JFileChooser();
// chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("Choose workSpace Path");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
{
}
String path = chooser.getSelectedFile().getAbsolutePath();
folder = new File(path);
but = new JButton("REMOVE");
SwingWorker worker = new SwingWorker() {
#Override
public Object doInBackground() {
GatheringFiles ob = new GatheringFiles();
list = ob.returnlist(folder);
return list;
}
#Override
protected void done() {
// java.util.List list = (java.util.List)get();
for (int x = 0; x < list.size(); x++) {
dtm.addRow(new Object[] { new Boolean(false),
list.get(x).toString() });
}
try {
JPanel pan = new JPanel();
JScrollPane sp = new JScrollPane(table);
TableColumn tc = table.getColumnModel().getColumn(0);
tc.setCellEditor(table.getDefaultEditor(Boolean.class));
tc.setCellRenderer(table.getDefaultRenderer(Boolean.class));
tc.setHeaderRenderer(new CheckBoxHeader(
new MyItemListener()));
JFrame f = new JFrame();
pan.add(sp);
pan.add(but);
f.add(pan);
f.setSize(700, 100);
f.pack();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
if (list.size() >= 0) {
// hide the progress bar
frame.hide();
}
} catch (Exception ex) {
}
}
};
worker.execute();
but.addActionListener(this);
//calling progressbar
if(!path.isEmpty())
{
SwingProgressBar();
}
}
public void SwingProgressBar() {
UIManager.put("ProgressBar.selectionBackground", Color.black);
UIManager.put("ProgressBar.selectionForeground", Color.white);
UIManager.put("ProgressBar.foreground", new Color(8, 32, 128));
pbar = new JProgressBar();
pbar.setMinimum(0);
pbar.setMaximum(100);
pbar.setForeground(Color.RED);
pbar.setStringPainted(true);
it = new JTableHeaderCheckBox();
frame = new JFrame("Loading");
final JLabel lb = new JLabel("0");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// frame.setContentPane(it);
frame.add(pbar);
frame.pack();
frame.setVisible(true);
counter = 0;
Thread runner = new Thread() {
public void run() {
counter = 0;
while (counter <= 99) {
Runnable runme = new Runnable() {
public void run() {
pbar.setValue(counter);
}
};
SwingUtilities.invokeLater(runme);
counter++;
try {
Thread.sleep(1000);
} catch (Exception ex) {
}
}
}
};
runner.start();
}
public void updateBar(int newValue) {
pbar.setValue(newValue);
}
class MyItemListener implements ItemListener {
public void itemStateChanged(ItemEvent e) {
Object source = e.getSource();
if (source instanceof AbstractButton == false)
return;
boolean checked = e.getStateChange() == ItemEvent.SELECTED;
for (int x = 0, y = table.getRowCount(); x < y; x++) {
table.setValueAt(new Boolean(checked), x, 0);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
new JTableHeaderCheckBox().buildGUI();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
} catch (Exception ex) {
}
}
});
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (e.getSource() == but) {
System.err.println("table.getRowCount()" + table.getRowCount());
for (int x = 0, y = table.getRowCount(); x < y; x++) {
if ("true".equals(table.getValueAt(x, 0).toString())) {
System.err.println(table.getValueAt(x, 0));
System.err.println(list.get(x).toString());
delete(list.get(x).toString());
}
}
}
}
public void delete(String a) {
String delete = "C:";
System.err.println(a);
try {
File inFile = new File(a);
if (!inFile.isFile()) {
return;
}
// Construct the new file that will later be renamed to the // filename.
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(inFile));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
// Read from the original file and write to the new
// unless content matches data to be removed.
while ((line = br.readLine()) != null) {
System.err.println(line);
line = line.replace(delete, " ");
pw.println(line);
pw.flush();
}
pw.close();
br.close();
// Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
// Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
class CheckBoxHeader extends JCheckBox implements TableCellRenderer,
MouseListener {
protected CheckBoxHeader rendererComponent;
protected int column;
protected boolean mousePressed = false;
public CheckBoxHeader(ItemListener itemListener) {
rendererComponent = this;
rendererComponent.addItemListener(itemListener);
}
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (table != null) {
JTableHeader header = table.getTableHeader();
if (header != null) {
rendererComponent.setForeground(header.getForeground());
rendererComponent.setBackground(header.getBackground());
rendererComponent.setFont(header.getFont());
header.addMouseListener(rendererComponent);
}
}
setColumn(column);
rendererComponent.setText("Check All");
setBorder(UIManager.getBorder("TableHeader.cellBorder"));
return rendererComponent;
}
protected void setColumn(int column) {
this.column = column;
}
public int getColumn() {
return column;
}
protected void handleClickEvent(MouseEvent e) {
if (mousePressed) {
mousePressed = false;
JTableHeader header = (JTableHeader) (e.getSource());
JTable tableView = header.getTable();
TableColumnModel columnModel = tableView.getColumnModel();
int viewColumn = columnModel.getColumnIndexAtX(e.getX());
int column = tableView.convertColumnIndexToModel(viewColumn);
if (viewColumn == this.column && e.getClickCount() == 1
&& column != -1) {
doClick();
}
}
}
public void mouseClicked(MouseEvent e) {
handleClickEvent(e);
((JTableHeader) e.getSource()).repaint();
}
public void mousePressed(MouseEvent e) {
mousePressed = true;
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
}
//
import java.io.File;
import java.util.*;
public class GatheringFiles {
public static List returnlist(File folder)
{
List<File> list = new ArrayList<File>();
List<File> list1 = new ArrayList<File>();
getFiles(folder, list);
return list;
}
private static void getFiles(File folder, List<File> list) {
folder.setReadOnly();
File[] files = folder.listFiles();
for(int j = 0; j < files.length; j++) {
if( "MANI.txt".equals(files[j].getName()))
{
list.add(files[j]);
}
if(files[j].isDirectory())
getFiles(files[j], list);
}
}
}

Categories