How could I make my Simulator buttons appear? - java

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.

Related

Java program in netbeans won't run properly but works perfectly fine when debugging

Good evening,
I've been programing a snake game the last few days using netbeans. Everything was perfectly fine until today when I decided to put in a JMenuBar so the user can set difficulty etc. This also worked fine but when I put the listeners for the MenuItems the program would only show an empty frame when running the project(F6). But when I click debug project(ctrl + f5) the game starts normaly. The run button also works when I remove the listeners. Any idea why this is that way?
Main class:
package test1;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Test1 extends JPanel implements KeyListener, Runnable{
private JFrame frame;
private Schlange snake;
private Apfel apfel;
private boolean up;
private boolean left;
private boolean right;
private boolean down;
private int bounds;
private boolean beschleunigen;
private int level;
private JMenu menu;
private JMenu sub1;
private JMenu sub2;
private JMenuItem restart;
private JMenuItem schw1, schw2, schw3, schw4, schw5;
private JMenuBar menuBar;
private boolean running;
public Test1(){
super();
init();
}
public static void main(String[] args) {
Test1 t1 = new Test1();
}
private void init() {
bounds = 300;
//Frame
frame = new JFrame();
frame.setSize(bounds,bounds);
frame.setTitle("Snake by Fluffy");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(100,100);
frame.setVisible(true);
frame.setFocusable(true);
frame.setResizable(false);
frame.addKeyListener(this);
//Spiel
snake = new Schlange(5, this);
apfel = new Apfel(frame);
up = false;
left = false;
right = false;
down = false;
apfel.getRnd(snake);
level = 160;
beschleunigen = false;
running = true;
//Menue
sub1 = new JMenu("Schwierigkeit");
sub2 = new JMenu("Spiel");
schw1 = new JMenuItem("Leicht");
schw2 = new JMenuItem("Mittel");
schw3 = new JMenuItem("Schwer");
schw4 = new JMenuItem("Irre");
schw5 = new JMenuItem("Beschleunigung");
restart = new JMenuItem("Neustart");
//Menue Listener
schw1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
level = 200;
}
});
schw2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
level = 160;
}
});
schw3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
level = 120;
}
});
schw4.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
level = 80;
}
});
schw5.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
beschleunigen = true;
}
});
restart.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
restart();
}
});
sub1.add(schw1);
sub1.add(schw2);
sub1.add(schw3);
sub1.add(schw4);
sub1.add(schw5);
sub2.add(restart);
menuBar = new JMenuBar();
menu = new JMenu("Optionen");
menu.add(sub1);
//menu.add(restart);
menuBar.add(sub2);
menuBar.add(menu);
//Ende
frame.setJMenuBar(menuBar);
this.setBackground(Color.green);
frame.add(this);
run();
}
#Override
public void paintComponent(Graphics gr) {
super.paintComponent(gr);
apfel.paintComponent(gr);
if(snake.collision()) {
gr.drawString("GAME OVER", 200, 200);
running = false;
}
snake.paintComponent(gr);
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case 37:
if(right!=true){
left = true;
up = false;
down = false;
right = false;
}
break;
case 38:
if(down!=true){
up = true;
down = false;
right = false;
left = false;
}
break;
case 39:
if(left!=true){
right = true;
left = false;
up = false;
down = false;
}
break;
case 40:
if(up!=true){
down = true;
up = false;
right = false;
left = false;
}
break;
default:
break;
}
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void run() {
while (running) {
if(up) snake.move("up");
if(down) snake.move("down");
if(left) snake.move("left");
if(right) snake.move("right");
repaint();
if(snake.collisionApfel(apfel.getX(), apfel.getY())) {
apfel.getRnd(snake);
if(level > 20 && beschleunigen) level -= 10;
}
try {
Thread.sleep(level);
} catch (InterruptedException ex) {
Logger.getLogger(Test1.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public Apfel getApfel(){
return apfel;
}
public void restart(){
snake = null;
apfel = null;
snake = new Schlange(5, this);
apfel = new Apfel(frame);
repaint();
up = false;
left = false;
right = false;
down = false;
apfel.getRnd(snake);
level = 160;
beschleunigen = false;
running = true;
}
}
If needed I can also post the other classes but they shouldn't be the problem... Some of the code is in german which I hope is no problem either :D
Take frame.setVisible(true); and place it at the end of the init method. You have a race condition between the frame been realized on the screen and the EDT

Java sliding JPanels

I have a menu that has a variety of buttons on display, I'm able to make the buttons call their respective JPanels when clicked. The thing is I would like to make the Jpanel slide in when its called instead of instantaneously popping in. I tried using tween engine and as Java beginner, I find it really overwhelming, so I decided to use timed animation. I was able to make the Jpanel on top to slide to one side but for some reason the next panel doesn't want to display, im really tired, can someone help please! There code is below:
public class Listener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
new Timer(0, new ActionListener() {
public void actionPerformed(ActionEvent e) {
mainpane.setLocation(mainpane.getX() - 10, 0);
if (mainpane.getX() + mainpane.getWidth() == 0)
{
((Timer) e.getSource()).stop();
System.out.println("Timer stopped");
}
}
}).start();
}
}
Sliding panels can be tricky. Here is some starter code. Modify to fit
your needs. Add error checking and exception handling as necessary.
This example uses JButtons and a JTree as content but you can use just about any type of content.
Usage:
static public void main(final String[] args) throws Exception {
SwingUtilities.invokeAndWait(new Runnable() {
#Override
public void run() {
final JFrame jFrame = new JFrame() {
{
final PanelSlider42<JFrame> slider = new PanelSlider42<JFrame>(this);
final JPanel jPanel = slider.getBasePanel();
slider.addComponent(new JButton("1"));
slider.addComponent(new JButton("22"));
slider.addComponent(new JButton("333"));
slider.addComponent(new JButton("4444"));
getContentPane().add(jPanel);
setSize(300, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible(true);
}
};
}
});
}
The impl is lengthy ...
package com.java42.example.code;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseMotionAdapter;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JWindow;
import javax.swing.SwingUtilities;
public class PanelSlider42<ParentType extends Container> {
private static final int RIGHT = 0x01;
private static final int LEFT = 0x02;
private static final int TOP = 0x03;
private static final int BOTTOM = 0x04;
private final JPanel basePanel = new JPanel();
private final ParentType parent;
private final Object lock = new Object();
private final ArrayList<Component> jPanels = new ArrayList<Component>();
private final boolean useSlideButton = true;
private boolean isSlideInProgress = false;
private final JPanel glassPane;
{
glassPane = new JPanel();
glassPane.setOpaque(false);
glassPane.addMouseListener(new MouseAdapter() {
});
glassPane.addMouseMotionListener(new MouseMotionAdapter() {
});
glassPane.addKeyListener(new KeyAdapter() {
});
}
public PanelSlider42(final ParentType parent) {
if (parent == null) {
throw new RuntimeException("ProgramCheck: Parent can not be null.");
}
if ((parent instanceof JFrame) || (parent instanceof JDialog) || (parent instanceof JWindow) || (parent instanceof JPanel)) {
}
else {
throw new RuntimeException("ProgramCheck: Parent type not supported. " + parent.getClass().getSimpleName());
}
this.parent = parent;
attach();
basePanel.setSize(parent.getSize());
basePanel.setLayout(new BorderLayout());
if (useSlideButton) {
final JPanel statusPanel = new JPanel();
basePanel.add(statusPanel, BorderLayout.SOUTH);
statusPanel.add(new JButton("Slide Left") {
private static final long serialVersionUID = 9204819004142223529L;
{
setMargin(new Insets(0, 0, 0, 0));
}
{
addActionListener(new ActionListener() {
#Override
public void actionPerformed(final ActionEvent e) {
slideLeft();
}
});
}
});
statusPanel.add(new JButton("Slide Right") {
{
setMargin(new Insets(0, 0, 0, 0));
}
private static final long serialVersionUID = 9204819004142223529L;
{
addActionListener(new ActionListener() {
#Override
public void actionPerformed(final ActionEvent e) {
slideRight();
}
});
}
});
statusPanel.add(new JButton("Slide Up") {
{
setMargin(new Insets(0, 0, 0, 0));
}
private static final long serialVersionUID = 9204819004142223529L;
{
addActionListener(new ActionListener() {
#Override
public void actionPerformed(final ActionEvent e) {
slideTop();
}
});
}
});
statusPanel.add(new JButton("Slide Down") {
{
setMargin(new Insets(0, 0, 0, 0));
}
private static final long serialVersionUID = 9204819004142223529L;
{
addActionListener(new ActionListener() {
#Override
public void actionPerformed(final ActionEvent e) {
slideBottom();
}
});
}
});
}
}
public JPanel getBasePanel() {
return basePanel;
}
private void attach() {
final ParentType w = this.parent;
if (w instanceof JFrame) {
final JFrame j = (JFrame) w;
if (j.getContentPane().getComponents().length > 0) {
throw new RuntimeException("ProgramCheck: Parent already contains content.");
}
j.getContentPane().add(basePanel);
}
if (w instanceof JDialog) {
final JDialog j = (JDialog) w;
if (j.getContentPane().getComponents().length > 0) {
throw new RuntimeException("ProgramCheck: Parent already contains content.");
}
j.getContentPane().add(basePanel);
}
if (w instanceof JWindow) {
final JWindow j = (JWindow) w;
if (j.getContentPane().getComponents().length > 0) {
throw new RuntimeException("ProgramCheck: Parent already contains content.");
}
j.getContentPane().add(basePanel);
}
if (w instanceof JPanel) {
final JPanel j = (JPanel) w;
if (j.getComponents().length > 0) {
throw new RuntimeException("ProgramCheck: Parent already contains content.");
}
j.add(basePanel);
}
}
public void addComponent(final Component component) {
if (jPanels.contains(component)) {
}
else {
jPanels.add(component);
if (jPanels.size() == 1) {
basePanel.add(component);
}
component.setSize(basePanel.getSize());
component.setLocation(0, 0);
}
}
public void removeComponent(final Component component) {
if (jPanels.contains(component)) {
jPanels.remove(component);
}
}
public void slideLeft() {
slide(LEFT);
}
public void slideRight() {
slide(RIGHT);
}
public void slideTop() {
slide(TOP);
}
public void slideBottom() {
slide(BOTTOM);
}
private void enableUserInput(final ParentType w) {
if (w instanceof JFrame) {
((JFrame) w).getGlassPane().setVisible(false);
}
if (w instanceof JDialog) {
((JDialog) w).getGlassPane().setVisible(false);
}
if (w instanceof JWindow) {
((JWindow) w).getGlassPane().setVisible(false);
}
}
private void disableUserInput(final ParentType w) {
if (w instanceof JFrame) {
((JFrame) w).setGlassPane(glassPane);
}
if (w instanceof JDialog) {
((JDialog) w).setGlassPane(glassPane);
}
if (w instanceof JWindow) {
((JWindow) w).setGlassPane(glassPane);
}
glassPane.setVisible(true);
}
private void enableTransparentOverylay() {
if (parent instanceof JFrame) {
((JFrame) parent).getContentPane().setBackground(jPanels.get(0).getBackground());
parent.remove(basePanel);
parent.validate();
}
if (parent instanceof JDialog) {
((JDialog) parent).getContentPane().setBackground(jPanels.get(0).getBackground());
parent.remove(basePanel);
parent.validate();
}
if (parent instanceof JWindow) {
((JWindow) parent).getContentPane().setBackground(jPanels.get(0).getBackground());
parent.remove(basePanel);
parent.validate();
}
}
private void slide(final int slideType) {
if (!isSlideInProgress) {
isSlideInProgress = true;
final Thread t0 = new Thread(new Runnable() {
#Override
public void run() {
parent.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
disableUserInput(parent);
slide(true, slideType);
enableUserInput(parent);
parent.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
isSlideInProgress = false;
}
});
t0.setDaemon(true);
t0.start();
}
else {
Toolkit.getDefaultToolkit().beep();
}
}
private void slide(final boolean useLoop, final int slideType) {
if (jPanels.size() < 2) {
System.err.println("Not enough panels");
return;
}
synchronized (lock) {
Component componentOld = null;
Component componentNew = null;
if ((slideType == LEFT) || (slideType == TOP)) {
componentNew = jPanels.remove(jPanels.size() - 1);
componentOld = jPanels.get(0);
jPanels.add(0, componentNew);
}
if ((slideType == RIGHT) || (slideType == BOTTOM)) {
componentOld = jPanels.remove(0);
jPanels.add(componentOld);
componentNew = jPanels.get(0);
}
final int w = componentOld.getWidth();
final int h = componentOld.getHeight();
final Point p1 = componentOld.getLocation();
final Point p2 = new Point(0, 0);
if (slideType == LEFT) {
p2.x += w;
}
if (slideType == RIGHT) {
p2.x -= w;
}
if (slideType == TOP) {
p2.y += h;
}
if (slideType == BOTTOM) {
p2.y -= h;
}
componentNew.setLocation(p2);
int step = 0;
if ((slideType == LEFT) || (slideType == RIGHT)) {
step = (int) (((float) parent.getWidth() / (float) Toolkit.getDefaultToolkit().getScreenSize().width) * 40.f);
}
else {
step = (int) (((float) parent.getHeight() / (float) Toolkit.getDefaultToolkit().getScreenSize().height) * 20.f);
}
step = step < 5 ? 5 : step;
basePanel.add(componentNew);
basePanel.revalidate();
if (useLoop) {
final int max = (slideType == LEFT) || (slideType == RIGHT) ? w : h;
final long t0 = System.currentTimeMillis();
for (int i = 0; i != (max / step); i++) {
switch (slideType) {
case LEFT: {
p1.x -= step;
componentOld.setLocation(p1);
p2.x -= step;
componentNew.setLocation(p2);
break;
}
case RIGHT: {
p1.x += step;
componentOld.setLocation(p1);
p2.x += step;
componentNew.setLocation(p2);
break;
}
case TOP: {
p1.y -= step;
componentOld.setLocation(p1);
p2.y -= step;
componentNew.setLocation(p2);
break;
}
case BOTTOM: {
p1.y += step;
componentOld.setLocation(p1);
p2.y += step;
componentNew.setLocation(p2);
break;
}
default:
new RuntimeException("ProgramCheck").printStackTrace();
break;
}
try {
Thread.sleep(500 / (max / step));
} catch (final Exception e) {
e.printStackTrace();
}
}
final long t1 = System.currentTimeMillis();
}
componentOld.setLocation(-10000, -10000);
componentNew.setLocation(0, 0);
}
}
}
I have searched for that problem some time ago.I found this sample code somewhere - saved in my evernote for future reference. This is the shortest way to implement that when I googled that in the past
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class SlidingPanel {
JPanel panel;
public void makeUI() {
panel = new JPanel();
panel.setBackground(Color.RED);
panel.setBounds(0, 0, 400, 400);
JButton button = new JButton("Click");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
((JButton) e.getSource()).setEnabled(false);
new Timer(1, new ActionListener() {
public void actionPerformed(ActionEvent e) {
panel.setLocation(panel.getX() - 1, 0);
if (panel.getX() + panel.getWidth() == 0) {
((Timer) e.getSource()).stop();
System.out.println("Timer stopped");
}
}
}).start();
}
});
panel.add(button);
JFrame frame = new JFrame("Sliding Panel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setLayout(null);
frame.add(panel);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SlidingPanel().makeUI();
}
});
}
}

How to transmit sound from Synthesizer to sequencer

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

internal frame not working

Hi I have created three frames inside a container and each frame has three buttons which performs the functions of min,max and close. For surprise only one frame is working and the rest three are not working.can you please sort it out.thanks
package Project;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.*;
import java.beans.PropertyVetoException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.plaf.basic.BasicInternalFrameTitlePane;
import javax.swing.plaf.basic.BasicInternalFrameUI;
public class Test4 {
JInternalFrame inf ;
DesktopPane pane;
public static void main(String[] args) {
new Test4();
}
private int xpos = 0;
private int ypos = 0;
public Test4() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception exp) {
exp.printStackTrace();
}
pane = new DesktopPane();
pane.add(newInternalFrame());
pane.add(newInternalFrame());
pane.add(newInternalFrame());
JFrame frame = new JFrame();
frame.add(pane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public JInternalFrame newInternalFrame() {
inf= new JInternalFrame("Blah", true, true, true, true);
inf.setLocation(xpos, ypos);
inf.setSize(200, 100);
inf.setVisible(true);
xpos += 50;
ypos += 50;
JPanel jp = new JPanel();
JLabel jl=new JLabel("panel"+xpos);
JButton jb = new JButton("_");
JButton jb2 = new JButton("[]");
JButton jb3 = new JButton("X");
inf.setLayout(new GridLayout(2, 2));
jp.add(jl);
jp.add(jb);
jp.add(jb2);
jp.add(jb3);
inf.add(jp);
jb.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
try {
if (inf.getLayer() == JDesktopPane.FRAME_CONTENT_LAYER) {
pane.remove(inf);
pane.add(inf, JDesktopPane.DEFAULT_LAYER);
pane.revalidate();
pane.repaint();
}
inf.pack();
inf.setIcon(true);
} catch (PropertyVetoException ex) {
ex.printStackTrace();
}
}
});
jb2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
try {
if (inf.isMaximum()) {//restore
inf.pack();
} else {//maximize
inf.setMaximum(true);
}
pane.remove(inf);
pane.add(inf, JDesktopPane.FRAME_CONTENT_LAYER);
pane.revalidate();
pane.repaint();
} catch (Exception e) {
e.printStackTrace();
}
}
});
jb3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
try {
inf.dispose();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
BasicInternalFrameTitlePane titlePane = (BasicInternalFrameTitlePane) ((BasicInternalFrameUI) inf.getUI()).getNorthPane();
inf.remove(titlePane);
return inf;
}
public class DesktopPane extends JDesktopPane {
#Override
public void doLayout() {
super.doLayout();
List<Component> icons = new ArrayList<Component>(25);
int maxLayer = 0;
for (Component comp : getComponents()) {
if (comp instanceof JInternalFrame.JDesktopIcon) {
icons.add(comp);
maxLayer = Math.max(getLayer(comp), maxLayer);
}
}
maxLayer++;
int x = 0;
for (Component icon : icons) {
int y = getHeight() - icon.getHeight();
icon.setLocation(x, y);
x += icon.getWidth();
setLayer(icon, maxLayer);
}
}
/* public void doLayout() {
super.doLayout();
List<Component> icons = new ArrayList<Component>(25);
for (Component comp : getComponents()) {
if (comp instanceof JInternalFrame.JDesktopIcon) {
icons.add(comp);
}
}
int x = 0;
for (Component icon : icons) {
int y = getHeight() - icon.getHeight();
icon.setLocation(x, y);
x += icon.getWidth();
}
}*/
}
}
package Project;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.*;
import java.beans.PropertyVetoException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.plaf.basic.BasicInternalFrameTitlePane;
import javax.swing.plaf.basic.BasicInternalFrameUI;
public class Test4 {
private JDesktopPane pane;
public static void main(String[] args) {
new Test4();// there was a little change here
}
private int xpos = 0;
private int ypos = 0;
public Test4() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception exp) {
exp.printStackTrace();
}
pane = new Test4.DesktopPane() {
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
};
pane.add(newInternalFrame());
pane.add(newInternalFrame());
pane.add(newInternalFrame());
JFrame frame = new JFrame();
frame.add(pane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public JInternalFrame newInternalFrame() {
final JInternalFrame inf = new JInternalFrame("Blah", true, true, true, true);
inf.setLocation(xpos, ypos);
inf.setSize(200, 100);
inf.setVisible(true);
xpos += 50;
ypos += 50;
JPanel jp = new JPanel();
JLabel jl = new JLabel("panel" + xpos);
JButton jb = new JButton("_");
JButton jb2 = new JButton("[]");
JButton jb3 = new JButton("X");
inf.setLayout(new GridLayout(2, 2));
jp.add(jl);
jp.add(jb);
jp.add(jb2);
jp.add(jb3);
inf.add(jp);
jb.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
try {
if (inf.getLayer() == JDesktopPane.FRAME_CONTENT_LAYER) {
pane.remove(inf);
pane.add(inf, JDesktopPane.DEFAULT_LAYER);
pane.revalidate();
pane.repaint();
}
inf.pack();
inf.setIcon(true);
} catch (PropertyVetoException ex) {
ex.printStackTrace();
}
}
});
jb2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
try {
if (inf.isMaximum()) {//restore
inf.pack();
} else {//maximize
inf.setMaximum(true);
}
pane.remove(inf);
pane.add(inf, JDesktopPane.FRAME_CONTENT_LAYER);
pane.revalidate();
pane.repaint();
} catch (Exception e) {
e.printStackTrace();
}
}
});
jb3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
try {
inf.dispose();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
BasicInternalFrameTitlePane titlePane = (BasicInternalFrameTitlePane) ((BasicInternalFrameUI) inf.getUI()).getNorthPane();
inf.remove(titlePane);
return inf;
}
public class DesktopPane extends JDesktopPane {
#Override
public void doLayout() {
super.doLayout();
List<Component> icons = new ArrayList<Component>(25);
int maxLayer = 0;
for (Component comp : getComponents()) {
if (comp instanceof JInternalFrame.JDesktopIcon) {
icons.add(comp);
maxLayer = Math.max(getLayer(comp), maxLayer);
}
}
maxLayer++;
int x = 0;
for (Component icon : icons) {
int y = getHeight() - icon.getHeight();
icon.setLocation(x, y);
x += icon.getWidth();
setLayer(icon, maxLayer);
}
}
}
}
just add the following line
final JInternalFrame inf= new JInternalFrame("Blah", true, true, true, true);
in place of inf= new JInternalFrame("Blah", true, true, true, true);
and remove this JInternalFrame inf from main.

How to show autocomplete as I type in JTextArea?

I need to show suggestions (autocomplete) as the user types in a JTextArea, kind of like cell phone T9.
I don't know how to do this in myTextAreaKeyTyped() event.
This app is a typing helper. It shows variants of characters non-present on the keyboard.
E.G. You press 'A', it shows Â:1, Á:2 ,À:3… 'A' will be replaced if you press 1,2 or 3.
It's already done, but the variants are shown in a JLabel at the bottom of my JFrame, because I don't know how to do this.
Can you please help me out? Thanks in advance.
Here is a snippet to get yourself inspired. You will probably need to reorganize a bit the code to make it more maintainable, but it should give you the gist.
Basically, we listen for key events (I don't find it relevant to listen to document events, for example if the user pastes some text, I don't want the suggestion panel to appear), and when the caret has at least 2 characters behind, we make some suggestions, using a popupmenu containing a JList of suggestions (here suggestions are really not meaningful, but it would not be too hard to bind this to a dictionnary). As for the shortcuts you are mentionning, it should not be too hard to do so.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JTextArea;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.BadLocationException;
public class Test {
public class SuggestionPanel {
private JList list;
private JPopupMenu popupMenu;
private String subWord;
private final int insertionPosition;
public SuggestionPanel(JTextArea textarea, int position, String subWord, Point location) {
this.insertionPosition = position;
this.subWord = subWord;
popupMenu = new JPopupMenu();
popupMenu.removeAll();
popupMenu.setOpaque(false);
popupMenu.setBorder(null);
popupMenu.add(list = createSuggestionList(position, subWord), BorderLayout.CENTER);
popupMenu.show(textarea, location.x, textarea.getBaseline(0, 0) + location.y);
}
public void hide() {
popupMenu.setVisible(false);
if (suggestion == this) {
suggestion = null;
}
}
private JList createSuggestionList(final int position, final String subWord) {
Object[] data = new Object[10];
for (int i = 0; i < data.length; i++) {
data[i] = subWord + i;
}
JList list = new JList(data);
list.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 1));
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setSelectedIndex(0);
list.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
insertSelection();
}
}
});
return list;
}
public boolean insertSelection() {
if (list.getSelectedValue() != null) {
try {
final String selectedSuggestion = ((String) list.getSelectedValue()).substring(subWord.length());
textarea.getDocument().insertString(insertionPosition, selectedSuggestion, null);
return true;
} catch (BadLocationException e1) {
e1.printStackTrace();
}
hideSuggestion();
}
return false;
}
public void moveUp() {
int index = Math.min(list.getSelectedIndex() - 1, 0);
selectIndex(index);
}
public void moveDown() {
int index = Math.min(list.getSelectedIndex() + 1, list.getModel().getSize() - 1);
selectIndex(index);
}
private void selectIndex(int index) {
final int position = textarea.getCaretPosition();
list.setSelectedIndex(index);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
textarea.setCaretPosition(position);
};
});
}
}
private SuggestionPanel suggestion;
private JTextArea textarea;
protected void showSuggestionLater() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
showSuggestion();
}
});
}
protected void showSuggestion() {
hideSuggestion();
final int position = textarea.getCaretPosition();
Point location;
try {
location = textarea.modelToView(position).getLocation();
} catch (BadLocationException e2) {
e2.printStackTrace();
return;
}
String text = textarea.getText();
int start = Math.max(0, position - 1);
while (start > 0) {
if (!Character.isWhitespace(text.charAt(start))) {
start--;
} else {
start++;
break;
}
}
if (start > position) {
return;
}
final String subWord = text.substring(start, position);
if (subWord.length() < 2) {
return;
}
suggestion = new SuggestionPanel(textarea, position, subWord, location);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
textarea.requestFocusInWindow();
}
});
}
private void hideSuggestion() {
if (suggestion != null) {
suggestion.hide();
}
}
protected void initUI() {
final JFrame frame = new JFrame();
frame.setTitle("Test frame on two screens");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new BorderLayout());
textarea = new JTextArea(24, 80);
textarea.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 1));
textarea.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == KeyEvent.VK_ENTER) {
if (suggestion != null) {
if (suggestion.insertSelection()) {
e.consume();
final int position = textarea.getCaretPosition();
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
textarea.getDocument().remove(position - 1, 1);
} catch (BadLocationException e) {
e.printStackTrace();
}
}
});
}
}
}
}
#Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_DOWN && suggestion != null) {
suggestion.moveDown();
} else if (e.getKeyCode() == KeyEvent.VK_UP && suggestion != null) {
suggestion.moveUp();
} else if (Character.isLetterOrDigit(e.getKeyChar())) {
showSuggestionLater();
} else if (Character.isWhitespace(e.getKeyChar())) {
hideSuggestion();
}
}
#Override
public void keyPressed(KeyEvent e) {
}
});
panel.add(textarea, BorderLayout.CENTER);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Test().initUI();
}
});
}
}

Categories