Java Swing MVC based Snake game. Issue switching difficulty level - java

I am writing a game for a snake in Java Swing using the MVC pattern.
The code of Controller and View are shown below. I am trying to implement a button that will help player choose a difficulty level.
The difficulty level is controlled by a timer in the Controller class. I am beginner in Java and help is appreciated.
Code of Controller class:
public class Controller implements KeyListener, ActionListener{
private Renderer renderer;
private Timer mainTimer;
private Snake snake;
public Controller() {
snake = new Snake();
renderer = new Renderer(this);
this.renderer.addKeyListener(this);
this.mainTimer = new Timer(150, this);
mainTimer.start();
}
public void stopGame(){
mainTimer.stop();
}
public void startGame(){
mainTimer.start();
}
public void keyPressed(KeyEvent e) {
snake.onMove(e.getKeyCode());
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
public void actionPerformed(ActionEvent arg0) {
renderer.moveForward();
}
public Snake getSnake(){
return snake;
}
View class:
class Renderer extends JFrame {
private final int WIDTH = 500;
private final int HEIGHT = 300;
private Snake snake;
public int LevelConst;
private Controller controller;
public JPanel pamel1, panel2;
public JButton[] ButtonBody = new JButton[200];
public JButton bonusfood;
public JTextArea textArea;
public Fruit fruit;
public int score;
public Random random = new Random();
public JMenuBar mybar;
public JMenu game, help, levels;
public void initializeValues() {
score = 0;
}
Renderer(Controller controller) {
super("Snake: Demo");
this.controller = controller;
snake = controller.getSnake();
fruit = new Fruit();
setBounds(200, 200, 506, 380);
creatbar();
initializeValues();
// GUI
pamel1 = new JPanel();
panel2 = new JPanel();
// Scoreboard
setResizable(false);
textArea = new JTextArea("Счет : " + score);
textArea.setEnabled(false);
textArea.setBounds(400, 400, 100, 100);
textArea.setBackground(Color.GRAY);
// Eating and growing up
bonusfood = new JButton();
bonusfood.setEnabled(false);
//
createFirstSnake();
pamel1.setLayout(null);
panel2.setLayout(new GridLayout(0, 1));
pamel1.setBounds(0, 0, WIDTH, HEIGHT);
pamel1.setBackground(Color.GRAY);
panel2.setBounds(0, HEIGHT, WIDTH, 30);
panel2.setBackground(Color.black);
panel2.add(textArea); // will contain score board
// end of UI design
getContentPane().setLayout(null);
getContentPane().add(pamel1);
getContentPane().add(panel2);
show();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void createFirstSnake() {
for (int i = 0; i < 3; i++) {
ButtonBody[i] = new JButton(" " + i);
ButtonBody[i].setEnabled(false);
pamel1.add(ButtonBody[i]);
ButtonBody[i].setBounds(snake.x[i], snake.y[i], 10, 10);
snake.x[i + 1] = snake.x[i] - 10;
snake.y[i + 1] = snake.y[i];
}
}
// Creating of menu bar
public void creatbar() {
mybar = new JMenuBar();
game = new JMenu("Game");
JMenuItem newgame = new JMenuItem("New Game");
JMenuItem exit = new JMenuItem("Exit");
newgame.addActionListener(e -> reset());
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
game.add(newgame);
game.addSeparator();
game.add(exit);
mybar.add(game);
levels = new JMenu("Level");
JMenuItem easy = new JMenuItem("Easy");
easy.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
LevelConst = 0;
}
});
JMenuItem middle = new JMenuItem("Medium");
middle.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
LevelConst = 1;
}
});
JMenuItem hard = new JMenuItem("Hard");
hard.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
LevelConst = 2;
}
});
levels.add(easy);
levels.addSeparator();
levels.add(middle);
levels.addSeparator();
levels.add(hard);
mybar.add(levels);
help = new JMenu("Help");
JMenuItem creator = new JMenuItem("There must be a button");
creator.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(pamel1, "Random text");
}
});
help.add(creator);
mybar.add(help);
setJMenuBar(mybar);
}
void reset() {
initializeValues();
pamel1.removeAll();
controller.stopGame();
createFirstSnake();
textArea.setText("Score: " + score);
controller.startGame();
}
void growup() {
ButtonBody[snake.getLength()] = new JButton(" " + snake.getLength());
ButtonBody[snake.getLength()].setEnabled(false);
pamel1.add(ButtonBody[snake.getLength()]);
ButtonBody[snake.getLength()].setBounds(snake.getPointBody()[snake.getLength() - 1].x, snake.getPointBody()[snake.getLength() - 1].y, 10, 10);
snake.setLength(snake.getLength() + 1);
}
void moveForward() {
for (int i = 0; i < snake.getLength(); i++) {
snake.getPointBody()[i] = ButtonBody[i].getLocation();
}
snake.x[0] += snake.getDirectionX();
snake.y[0] += snake.getDirectionY();
ButtonBody[0].setBounds(snake.x[0], snake.y[0], 10, 10);
for (int i = 1; i < snake.getLength(); i++) {
ButtonBody[i].setLocation(snake.getPointBody()[i - 1]);
}
if (snake.x[0] == WIDTH) {
controller.stopGame();
} else if (snake.x[0] == 0) {
controller.stopGame();
} else if (snake.y[0] == HEIGHT) {
controller.stopGame();
} else if (snake.y[0] == 0) {
controller.stopGame();
}
createFruit();
collisionFruit();
pamel1.repaint();
}
private void collisionFruit() {
if (fruit.isFood()) {
if (fruit.getPoint().x == snake.x[0] && fruit.getPoint().y == snake.y[0]) {
pamel1.remove(bonusfood);
score += 1;
growup();
textArea.setText("Score: " + score);
fruit.setFood(false);
}
}
}
private void createFruit() {
if (!fruit.isFood()) {
pamel1.add(bonusfood);
bonusfood.setBounds((10 * random.nextInt(50)), (10 * random.nextInt(25)), 10,
10);
fruit.setPoint(bonusfood.getLocation());
fruit.setFood(true);
}
}
Class Model: Fruit:
public class Fruit {
private Point point;
private boolean food;
public Fruit() {
point = new Point();
}
public Point getPoint() {
return point;
}
public void setPoint(Point point) {
this.point = point;
}
public boolean isFood() {
return food;
}
public void setFood(boolean food) {
this.food = food;
}
Class Model: Snake:
public class Snake {
private Point[] pointBody = new Point[300];
private int length;
private boolean isLeft;
private boolean isRight;
private boolean isUp;
private boolean isDown;
private int directionX;
private int directionY;
public int[] x = new int[300];
public int[] y = new int[300];
public Snake() {
isLeft = false;
isRight = true;
isUp = true;
isDown = true;
setDirectionX(10);
setDirectionY(0);
length = 3;
y[0] = 100;
x[0] = 150;
}
public void onMove(int side) {
switch (side) {
case KeyEvent.VK_LEFT:
if (isLeft) {
setDirectionX(-10);
setDirectionY(0);
isRight = false;
isUp = true;
isDown = true;
}
break;
case KeyEvent.VK_UP:
if (isUp) {
setDirectionX(0);
setDirectionY(-10);
isDown = false;
isRight = true;
isLeft = true;
}
break;
case KeyEvent.VK_DOWN:
if (isDown) {
setDirectionX(0);
setDirectionY(+10);
isUp = false;
isRight = true;
isLeft = true;
}
break;
case KeyEvent.VK_RIGHT:
if (isRight) {
setDirectionX(+10);
setDirectionY(0);
isLeft = false;
isUp = true;
isDown = true;
}
break;
default:
break;
}
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public Point[] getPointBody() {
return pointBody;
}
public void setPointBody(Point[] pointBody) {
this.pointBody = pointBody;
}
public int getDirectionX() {
return directionX;
}
public void setDirectionX(int directionX) {
this.directionX = directionX;
}
public int getDirectionY() {
return directionY;
}
public void setDirectionY(int directionY) {
this.directionY = directionY;
}
Main:
public class Main {
public static void main(String[] args) {
new Controller();
}
}

Make a property change listener in Controller:
public PropertyChangeListener getViewListener() {
return new ViewListener();
}
private class ViewListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent evt) {
System.out.println("Level is "+ evt.getNewValue());
//use level
}
}
Invoke createbar by: creatbar(controller.getViewListener());
And use listener :
public void creatbar(PropertyChangeListener listener) {
mybar = new JMenuBar();
mybar.addPropertyChangeListener(listener);//add listener to menu bar
game = new JMenu("Game");
JMenuItem newgame = new JMenuItem("New Game");
JMenuItem exit = new JMenuItem("Exit");
newgame.addActionListener(e -> reset());
exit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
game.add(newgame);
game.addSeparator();
game.add(exit);
mybar.add(game);
levels = new JMenu("Level");
JMenuItem easy = new JMenuItem("Easy");
easy.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
mybar.firePropertyChange("Level", LevelConst, 0); //use listener
LevelConst = 0;
}
});
JMenuItem middle = new JMenuItem("Medium");
middle.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
mybar.firePropertyChange("Level", LevelConst, 1);
LevelConst = 1;
}
});
JMenuItem hard = new JMenuItem("Hard");
hard.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
mybar.firePropertyChange("Level", LevelConst, 2);
LevelConst = 2;
}
});
levels.add(easy);
levels.addSeparator();
levels.add(middle);
levels.addSeparator();
levels.add(hard);
mybar.add(levels);
help = new JMenu("Help");
JMenuItem creator = new JMenuItem("There must be a button");
creator.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(pamel1, "Random text");
}
});
help.add(creator);
mybar.add(help);
setJMenuBar(mybar);
}

Related

How to make it so when I open one JFrame the timer in the other doesn't start?

I have two Pane classes with respective JFrames. I also have another JFrame that acts as a level menu and when I open one of the JFrame both timers start I'm sure I'm missing something simple, but could someone please help me.
First level
Pane class
private static final long serialVersionUID = 1L;
private int x=0;
private int h=getHeight();
private int x1=20;
private int y1=100;
private int w;
private Timer timer;
private Timer timer2;
private Timer timer3;
private int t=60;
private String ti=Integer.toString(t);
private int ccounter=0;
private int angle=60;
private int time=1;
private int initialx=5;
private int initialy=1;
private double dx=Ballphysics.xveloctiy(angle, initialx);
private double dy=Ballphysics.yveloctiy(angle, initialy, time);
private int c1x=45;
private int c2x=60;
private int c3x=75;
private int gamex=-500;
private int points=0;
private Game_Model model;
private boolean a=false;
public Game_Pane(Game_Model model) {
this.setModel(model);
model.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
repaint();
}
});
setFocusable(true);
addKeyListener(this);
setBackground(Color.black);
timer= new Timer(50,new TimerCallback());
timer2=new Timer(5,new TimerCallback2());
timer3=new Timer(1000,new TimerCallback3());
timer.start();
timer2.start();
timer3.start();
}
public boolean isA() {
return a;
}
public void setA(boolean a) {
this.a = a;
}
public class TimerCallback implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
new Ballphysics();
if(x1 < 0 || x1 > w-10)
{
dx=-dx;
}
if (x1 < 0)
{
x1 = 0;
}
if (x1 > w-10)
{
x1 = w-10;
}
else
{
x1 = (int) (x1 + dx);
}
if (y1<50)
{
dy=-dy;
}
if (y1>h-50&&x1>=x&&x1<=x+150&&y1<h-40) {
dy=-dy;
points++;
}
if (y1<50) {
y1=50;
}
else
{
y1=(int)(y1+dy);
}
if (y1>1000) {
ccounter+=1;
y1=50;
x1=0;
if (ccounter==1) {
c3x=-500;
}
if (ccounter==2) {
c2x=-500;
}
if (ccounter==3) {
c1x=-500;
timer2.stop();
timer3.stop();
gamex=w/2-75;
timer.stop();
}
}
if (t==0) {
new Start_Menu(model).setC(true);
if (ccounter==0) {
points+=50;
}
else if (ccounter==1) {
points+=25;
}
else if (ccounter==2) {
points+=5;
}
points+=50;
}
repaint();
}}
public class TimerCallback2 implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
repaint();
}}
public class TimerCallback3 implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
t-=1;
time++;
ti=Integer.toString(t);
if (t==-1) {
timer.stop();
timer3.stop();
timer2.stop();
}
}
}
public void paintComponent(Graphics g) {
h=getHeight();
w=getWidth();
super.paintComponent(g);
g.setColor(Color.white);
g.drawString("Lives:", 10, 20);
g.drawString("Time Remaing:", w-140, 20);
g.drawString(ti, w-50, 20);
g.fillOval(c1x, 10, 10, 10);
g.fillOval(c2x, 10, 10, 10);
g.fillOval(c3x, 10, 10, 10);
g.drawLine(0,50,w,50);
g.drawLine(x, h-40, x+150, h-40);
g.setColor(Color.red);
g.fillOval(x1, y1, 10, 10);
g.setFont(new Font("Times New Roman",Font.BOLD,30));
g.drawString("Game Over", gamex, h/2);
String str=Integer.toString(points);
g.drawString(str, w/2-15, 30);
}
#Override
public void keyPressed(KeyEvent e) {
h=getHeight();
w=getWidth();
if (x>=0) {
if (e.getKeyCode()==37) {
x-=5;
}
else if (e.getKeyCode()==39) {
x+=5;
}}
if (x<0) {
x=0;
}
else if (x>w-150) {
x=w-150;}
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void keyTyped(KeyEvent e) {
}
public Game_Model getModel() {
return model;
}
public void setModel(Game_Model model) {
this.model = model;
}
Frame for the first Pane (level)
Frame for pane
private static final long serialVersionUID = 1L;
private Game_Model model= new Game_Model();
private Game_Pane p= new Game_Pane(model);
public Game_Frame() {
add(p);
setSize(600,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Level 1");
}
The pane for level 2 is identical and so is the frame as I haven't changed it to be unique yet so I won't add it too.
The level menu
private static final long serialVersionUID = 1L;
private JButton button= new JButton("1 player level 1");
private JButton button2= new JButton ("1 player level 2");
private JButton button3= new JButton ("2 player level 1");
private JButton button4= new JButton ("2 player level 2");
private Dimension d= new Dimension(300,50);
private Game_Frame Game_Frame= new Game_Frame();
private Game_Frame2 Frame2= new Game_Frame2();
public Level_Menu() {
setLayout (new GridBagLayout());
GridBagConstraints gbc= new GridBagConstraints();
gbc.gridwidth=GridBagConstraints.REMAINDER;
gbc.fill=GridBagConstraints.HORIZONTAL;
add(button,gbc);
add(button2,gbc);
add(button3,gbc);
add(button4,gbc);
button.setPreferredSize(d);
button2.setPreferredSize(d);
button3.setPreferredSize(d);
button4.setPreferredSize(d);
button.setBackground(Color.GREEN);
button2.setBackground(Color.green);
button3.setBackground(Color.GREEN);
button4.setBackground(Color.green);
setBackground(Color.BLACK);
button.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
button4.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
Object a=e.getSource();
if (a==button) {
Game_Frame.setVisible(true);
}
else if (a==button2) {
Frame2.setVisible(true);
}
else if (a==button3) {
}
else if (a==button4) {
}
}
Menu Frame
private static final long serialVersionUID = 1L;
private Level_Menu level= new Level_Menu();
public Level_Frame() {
add(level);
setSize(600,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Level Menu");}

2 Observers (JInternalFrames) 1 Observable does not work

I have 3 classes. One class is my mainframe, another class is my JInternalFrame and also my Observer and the third class does a simulation with a field ob buttons and that one is also my observable class.
Basically I made a button in my observer that copies itself. That includes the add to the desktoppane and the addObserver function of my observable class.
The clone of my observer should also observer the very same observable. So if I interact with the one JInternalFrame, it also changes stuff for the other InternalFrame. It should act like a mirror. (Actually the copy should have like diffrent color buttons and a diffrent orientation but I think that should not be a problem to implement, as soon as I successfully could mirror my Observer)
So since I am using the Observable pattern, I also have to implement the "update" function in my Observer class. I did that and I works like a charm. But when I copy my JInternalFrame, the new InternalFrame observes the Observable(Simulation), but my original JInternalFrame loses the observable connection. It does not show buttons anymore etc.
What I tried: I created a second Observer/JInternalFrame class that extends my first Observer class. That did not work as well. I don't know if thats even a possibility to achieve what I want to.
Sorry for my non perfect english. Sorry for some german words that you might find in the code and sorry that I post so much code. But I am really uncertain right now where my mistake is since I tried to find the error for ours so far.
So here are 2 pictures for you:
First picture shows how my JInternalFrame looks like when I create it. Here everything works perfectly.
Second picture shows what it looks like when I click on the New View button. As already described. The original JInternalFrame does not show the simulation anymore. Although they are both observing the same Observable.
And here are my 3 imporant classes:
MainFrame:
public class LangtonsAmeise extends JFrame implements ActionListener {
JDesktopPane desk;
JPanel panelButtons;
JMenuBar jmb;
JMenu file, modus;
JMenuItem load, save, exit, mSetzen, mMalen, mLaufen;
JSlider slider;
static int xInt, yInt, xKindFrame = 450, yKindFrame = 450, xLocation,
yLocation, xMainFrame = 1000, yMainFrame = 900;
static boolean bSetzen = false, bMalen = false, running = true;
static JFileChooser fc;
Random randomGenerator = new Random();
JLabel xLabel, yLabel, speed, statusText, status;
JButton start, stop, addAnt;
JTextField xField, yField;
public LangtonsAmeise() {
// Desktop
desk = new JDesktopPane();
getContentPane().add(desk, BorderLayout.CENTER);
// File Chooser
fc = new JFileChooser(System.getProperty("user.dir"));
speed = new JLabel("Geschwindigkeit");
xLabel = new JLabel("x:");
yLabel = new JLabel("y:");
xLabel.setHorizontalAlignment(JLabel.RIGHT);
yLabel.setHorizontalAlignment(JLabel.RIGHT);
xLabel.setOpaque(true);
yLabel.setOpaque(true);
xField = new JTextField();
yField = new JTextField();
start = new JButton("Fenster erstellen");
stop = new JButton("Pause/Fortsetzen");
start.setMargin(new Insets(0, 0, 0, 0));
stop.setMargin(new Insets(0, 0, 0, 0));
// Buttons
panelButtons = new JPanel();
panelButtons.setLayout(new GridLayout());
panelButtons.add(start);
panelButtons.add(xLabel);
panelButtons.add(xField);
panelButtons.add(yLabel);
panelButtons.add(yField);
panelButtons.add(speed);
panelButtons.add(new Panel());
panelButtons.add(stop);
start.addActionListener(this);
stop.addActionListener(this);
add(panelButtons, BorderLayout.NORTH);
statusText = new JLabel("Status:");
status = new JLabel("Stopp");
// JMenuBar
jmb = new JMenuBar();
setJMenuBar(jmb);
file = new JMenu("File");
modus = new JMenu("Mode");
mLaufen = new JMenuItem("Laufen");
mMalen = new JMenuItem("Malen");
mSetzen = new JMenuItem("Setzen");
load = new JMenuItem("Simulation laden");
//save = new JMenuItem("Simulation speichern");
mSetzen.addActionListener(this);
mMalen.addActionListener(this);
mLaufen.addActionListener(this);
exit = new JMenuItem("Exit");
file.add(load);
file.addSeparator();
file.add(exit);
load.addActionListener(this);
modus.add(mLaufen);
modus.add(mSetzen);
modus.add(mMalen);
jmb.add(file);
jmb.add(modus);
for (int i = 0; i < 20; i++) {
jmb.add(new JLabel(" "));
}
jmb.add(statusText);
jmb.add(status);
setSize(new Dimension(xMainFrame, yMainFrame));
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(dim.width / 2 - this.getSize().width / 2, dim.height
/ 2 - this.getSize().height / 2);
xField.setText("5");
yField.setText("5");
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Fenster erstellen")) {
if (xField.getText().equals("") || yField.getText().equals("")) {
} else {
xInt = Integer.parseInt(xField.getText());
yInt = Integer.parseInt(yField.getText());
state s = new state();
kindFenster k = new kindFenster(s, this);
s.addObserver(k);
addChild(k);
s.startSimulation();
}
}
if (e.getActionCommand().equals("Pause/Fortsetzen")) {
running = !running;
System.out.println(running);
status.setText("Stopp");
}
if (e.getActionCommand().equals("Setzen")) {
status.setText("Setzen");
running = false;
bSetzen = true;
bMalen = false;
}
if (e.getActionCommand().equals("Laufen")) {
status.setText("Laufen");
running = true;
bSetzen = false;
bMalen = false;
}
if (e.getActionCommand().equals("Malen")) {
status.setText("Malen");
running = false;
bSetzen = false;
bMalen = true;
}
if (e.getActionCommand().equals("Simulation laden")) {
LangtonsAmeise.running = false;
InputStream fis = null;
try {
fc.showOpenDialog(null);
fis = new FileInputStream(fc.getSelectedFile().getPath());
ObjectInputStream ois = new ObjectInputStream(fis);
state s = (state) ois.readObject();
kindFenster k = new kindFenster(s, this);
s.addObserver(k);
addChild(k);
s.startSimulation();
} catch (IOException | ClassNotFoundException
| NullPointerException e1) {
LangtonsAmeise.running = true;
} finally {
try {
fis.close();
} catch (NullPointerException | IOException e1) {
LangtonsAmeise.running = true;
}
}
LangtonsAmeise.running = true;
}
}
public void addChild(JInternalFrame kind) {
xLocation = randomGenerator.nextInt(xMainFrame - xKindFrame);
yLocation = randomGenerator.nextInt(yMainFrame - yKindFrame - 100);
kind.setSize(370, 370);
kind.setLocation(xLocation, yLocation);
desk.add(kind);
kind.setVisible(true);
}
public static void main(String[] args) {
LangtonsAmeise hauptFenster = new LangtonsAmeise();
}
}
JInternalFrame:
public class kindFenster extends JInternalFrame implements ActionListener,
Serializable,Observer,Cloneable {
/**
*
*/
private static final long serialVersionUID = 8939449766068226519L;
static int nr = 0;
static int x,y,xScale,yScale,xFrame,yFrame;
state s;
ArrayList<ImageIcon> ameisen = new ArrayList<ImageIcon>();
JFileChooser fc;
LangtonsAmeise la;
Color alteFarbe, neueFarbe;
JButton save, addAnt, newView;
JPanel panelButtonsKind;
JSlider sliderKind;
public JPanel panelSpielfeld,panelSpielfeldKopie;
JButton[] jbArrayy;
static SetzenActionListener sal = new SetzenActionListener();
static MouseMotionActionListener mmal = new MouseMotionActionListener();
public kindFenster(state s,LangtonsAmeise la) {
super("Kind " + (++nr), true, true, true, true);
setLayout(new BorderLayout());
this.s=s;
jbArrayy=new JButton[s.jbArrayy.length];
for (int b = 1; b<s.jbArrayy.length;b++) {
this.jbArrayy[b] = s.jbArrayy[b];
}
this.la=la;
setSize(new Dimension(xFrame, yFrame));
this.addInternalFrameListener(listener);
this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
panelSpielfeld = new JPanel();
panelSpielfeld.setLayout(new GridLayout(s.y, s.x));
panelButtonsKind = new JPanel();
panelButtonsKind.setLayout(new GridLayout(1, 3));
save = new JButton("<html>Save<br>simulation</html>");
addAnt = new JButton("<html>Add<br>ant</html>");
newView = new JButton("<html>New<br>View</html>");
save.setActionCommand("save");
addAnt.setActionCommand("addAnt");
newView.setActionCommand("newView");
save.setMargin(new Insets(0, 0, 0, 0));
addAnt.setMargin(new Insets(0, 0, 0, 0));
addAnt.addActionListener(this);
save.addActionListener(this);
newView.addActionListener(this);
sliderKind = new JSlider(JSlider.HORIZONTAL, 1, 9, 5);
sliderKind.setSnapToTicks(true);
sliderKind.setPaintTicks(true);
sliderKind.setPaintTrack(true);
sliderKind.setMajorTickSpacing(1);
sliderKind.setPaintLabels(true);
sliderKind.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider) e.getSource();
if (!source.getValueIsAdjusting()) {
int speed = source.getValue();
state.sleeptime = 1000 / speed;
}
}
});
panelButtonsKind.add(save);
panelButtonsKind.add(newView);
panelButtonsKind.add(sliderKind);
panelButtonsKind.add(addAnt);
add(panelButtonsKind, BorderLayout.NORTH);
add(panelSpielfeld, BorderLayout.CENTER);
this.addComponentListener(new MyComponentAdapter());
for (int i = 1 ; i<jbArrayy.length;i++) {
panelSpielfeld.add(jbArrayy[i]);
}
}
// I have been trying around to change the orientation of the buttons in the copy of the frame
public void secondViewFrameSettings() {
int temp;
for (int i = 1; i<=x;i++) {
for (int k = 0; k<y;k++) {
temp = i+(k*x);
panelSpielfeldKopie.add(s.jbArrayy[temp]);
}
}
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("addAnt")) {
s.addAnt();
}
if (e.getActionCommand().equals("newView")){
kindFenster kk = new kindFenster(s,la);
s.addObserver(kk);
la.addChild(kk);
}
if (e.getActionCommand().equals("save")) {
OutputStream fos = null;
try {
LangtonsAmeise.running=false;
try {
fc = new JFileChooser(System.getProperty("user.dir"));
fc.showSaveDialog(null);
LangtonsAmeise.fc.setCurrentDirectory(fc.getSelectedFile());
fos = new FileOutputStream(fc.getSelectedFile());
ObjectOutputStream o = new ObjectOutputStream(fos);
o.writeObject(s);
} catch (NullPointerException e2) {
System.out.println("Fehler beim Auswählen der Datei. Wenden Sie sich an den Entwickler.");
}
} catch (IOException e1) {
LangtonsAmeise.running=true;
System.err.println(e1);
} finally {
try {
fos.close();
} catch (NullPointerException | IOException e1) {
LangtonsAmeise.running=true;
}
LangtonsAmeise.running=true;
}
LangtonsAmeise.running=true;
}
}
InternalFrameListener listener = new InternalFrameAdapter() {
public void internalFrameClosing(InternalFrameEvent e) {
e.getInternalFrame().dispose();
s.simulation.suspend();
}
};
class MyComponentAdapter extends ComponentAdapter {
public void componentResized(ComponentEvent e) {
//Ameisenbilder an die Buttongrößen anpassen
xScale=s.jbArrayy[1].getSize().width;
yScale=s.jbArrayy[1].getSize().height;
s.ameisen.clear();
s.ameisen.add(new ImageIcon(new ImageIcon("ameise.gif")
.getImage().getScaledInstance(xScale, yScale,
Image.SCALE_SMOOTH)));
s.ameisen.add(new ImageIcon(new ImageIcon("ameise90.gif")
.getImage().getScaledInstance(xScale, yScale,
Image.SCALE_SMOOTH)));
s.ameisen.add(new ImageIcon(new ImageIcon("ameise180.gif")
.getImage().getScaledInstance(xScale, yScale,
Image.SCALE_SMOOTH)));
s.ameisen.add(new ImageIcon(new ImageIcon("ameise270.gif")
.getImage().getScaledInstance(xScale, yScale,
Image.SCALE_SMOOTH)));
}
}
public void update(Observable o, Object arg) {
if (o == s) {
for (int i = 1;i<s.jbArrayy.length;i++) {
jbArrayy[i].setBackground(s.jbArrayy[i].getBackground());
}
}
}
}
class SetzenActionListener implements ActionListener,Serializable {
JButton source;
#Override
public void actionPerformed(ActionEvent e) {
source = (JButton) e.getSource();
if (LangtonsAmeise.bSetzen == true) {
if (source.getBackground().equals(Color.GREEN)) {
source.setBackground(Color.WHITE);
} else {
source.setBackground(Color.GREEN);
}
}
}
}
class MouseMotionActionListener extends MouseInputAdapter implements Serializable {
boolean dragged = false;
JButton tempJButton = new JButton();
public void mouseEntered(MouseEvent e) {
if (LangtonsAmeise.bMalen == true && dragged == true) {
((JButton) e.getSource()).setBackground(Color.GREEN);
}
}
public void mouseDragged(MouseEvent e) {
dragged = true;
}
public void mouseReleased(MouseEvent e) {
dragged = false;
}
}
Observable class:
public class state extends Observable implements Serializable {
/**
*
*/
private static final long serialVersionUID = 450773214079105589L;
int[] obRand, reRand, unRand, liRand;
int x, y, temp;
static int sleeptime = 200;
Color background;
int posAmeise, aktuellesIcon = 1, altePosAmeise, xScale, yScale;
Color alteFarbe, neueFarbe, color1, color2;
ArrayList<JButton> jbSer = new ArrayList<JButton>();
private List<Ant> ants = new ArrayList<Ant>();
ArrayList<ImageIcon> ameisen = new ArrayList<>();
JButton[] jbArrayy;
transient Thread simulation;
public state() {
this.x = LangtonsAmeise.xInt;
this.y = LangtonsAmeise.yInt;
color1 = Color.WHITE;
color2 = Color.GREEN;
jbArrayy = new JButton[x * y + 1];
initializeBorders();
initializeAntsImages();
initializeSimulationButtons();
xScale = jbArrayy[1].getSize().width;
yScale = jbArrayy[1].getSize().height;
// Startpunkt für die Ameise festlegen
posAmeise = (((x / 2) * y) - y / 2);
background = jbArrayy[posAmeise].getBackground();
ants.add(new Ant(this));
}
public void initializeAntsImages() {
ameisen.add(new ImageIcon(new ImageIcon("ameise.gif").getImage()
.getScaledInstance(LangtonsAmeise.xKindFrame / x,
LangtonsAmeise.yKindFrame / y, Image.SCALE_SMOOTH)));
ameisen.add(new ImageIcon(new ImageIcon("ameise90.gif").getImage()
.getScaledInstance(LangtonsAmeise.xKindFrame / x,
LangtonsAmeise.yKindFrame / y, Image.SCALE_SMOOTH)));
ameisen.add(new ImageIcon(new ImageIcon("ameise180.gif").getImage()
.getScaledInstance(LangtonsAmeise.xKindFrame / x,
LangtonsAmeise.yKindFrame / y, Image.SCALE_SMOOTH)));
ameisen.add(new ImageIcon(new ImageIcon("ameise270.gif").getImage()
.getScaledInstance(LangtonsAmeise.xKindFrame / x,
LangtonsAmeise.yKindFrame / y, Image.SCALE_SMOOTH)));
}
// Alle Buttons für das Simulationsfeld werden erstellt
public void initializeSimulationButtons() {
jbArrayy[0] = new JButton();
for (int i = 1; i < jbArrayy.length; i++) {
jbArrayy[i] = new JButton();
jbArrayy[i].setBackground(color1);
jbArrayy[i].addActionListener(kindFenster.sal);
jbArrayy[i].addMouseListener(kindFenster.mmal);
jbArrayy[i].addMouseMotionListener(kindFenster.mmal);
}
}
// Ränderindex in Array schreiben
public void initializeBorders() {
reRand = new int[y];
liRand = new int[y];
obRand = new int[x];
unRand = new int[x];
for (int i = 0; i < x; i++) {
obRand[i] = i + 1;
unRand[i] = (x * y - x) + i + 1;
}
for (int i = 1; i <= y; i++) {
reRand[i - 1] = i * x;
liRand[i - 1] = i * x - (x - 1);
}
}
public void initializeSimulation() {
if (simulation != null && simulation.isAlive()) {
simulation.stop();
}
simulation = new Thread() {
#Override
public void run() {
super.run();
while (true) {
try {
sleep(300);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
while (LangtonsAmeise.running && countObservers() > 0) {
try {
Thread.sleep(sleeptime);
for (Ant a : ants) {
move(a);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
};
}
public void startSimulation() {
initializeSimulation();
simulation.start();
}
public void changeColor(int altePos, Color c) {
jbArrayy[altePos].setBackground(c);
}
public void addAnt() {
ants.add(new Ant(this));
}
public void changeIcon(boolean k, Ant a) {
int g = (k == true) ? 1 : -1;
if (a.aktuellesIcon + g < 0) {
a.aktuellesIcon = 3;
} else if (a.aktuellesIcon + g > 3) {
a.aktuellesIcon = 0;
} else {
a.aktuellesIcon += g;
}
jbArrayy[a.posAmeise].setIcon(ameisen.get(a.aktuellesIcon));
setChanged();
notifyObservers();
}
public void rightCheck(Ant a) {
if (checkInArray(a.posAmeise, reRand)) {
a.posAmeise -= x - 1;
} else {
a.posAmeise += 1;
}
}
public void leftCheck(Ant a) {
if (checkInArray(a.posAmeise, liRand)) {
a.posAmeise += x - 1;
} else {
a.posAmeise -= 1;
}
}
public void upCheck(Ant a) {
if (checkInArray(a.posAmeise, obRand)) {
a.posAmeise += (y - 1) * x;
} else {
a.posAmeise -= x;
}
}
public void downCheck(Ant a) {
if (checkInArray(a.posAmeise, unRand)) {
a.posAmeise -= (y - 1) * x;
} else {
a.posAmeise += x;
}
}
public void checkAmeisenSize(Ant a) {
while (!(ameisen.size() == 4)) {
}
;
}
public static boolean checkInArray(int currentState, int[] myArray) {
int i = 0;
for (; i < myArray.length; i++) {
if (myArray[i] == currentState)
break;
}
return i != myArray.length;
}
public ImageIcon getAntImage() {
return ameisen.get(aktuellesIcon);
}
public void move(Ant a) throws InterruptedException {
try {
a.altePosAmeise = a.posAmeise;
a.alteFarbe = jbArrayy[a.posAmeise].getBackground();
if (a.alteFarbe.equals(Color.GREEN) && ameisen.size() == 4) {
if (a.aktuellesIcon == 0) {
checkAmeisenSize(a);
rightCheck(a);
} else if (a.aktuellesIcon == 1) {
checkAmeisenSize(a);
downCheck(a);
} else if (a.aktuellesIcon == 2) {
checkAmeisenSize(a);
leftCheck(a);
} else if (a.aktuellesIcon == 3) {
checkAmeisenSize(a);
upCheck(a);
}
changeIcon(true, a);
changeColor(a.altePosAmeise, Color.WHITE);
} else if (a.alteFarbe.equals(Color.WHITE) && ameisen.size() == 4) {
if (a.aktuellesIcon == 0) {
checkAmeisenSize(a);
leftCheck(a);
} else if (a.aktuellesIcon == 1) {
checkAmeisenSize(a);
upCheck(a);
} else if (a.aktuellesIcon == 2) {
checkAmeisenSize(a);
rightCheck(a);
} else if (a.aktuellesIcon == 3) {
checkAmeisenSize(a);
downCheck(a);
}
changeIcon(false, a);
changeColor(a.altePosAmeise, Color.GREEN);
setChanged();
notifyObservers();
}
jbArrayy[a.altePosAmeise].setIcon(new ImageIcon());
} catch (IndexOutOfBoundsException e) {
move(a);
}
}
}
Edit: Ant Class
import java.awt.Color;
import java.awt.Image;
import java.io.Serializable;
import java.util.ArrayList;
import javax.swing.ImageIcon;
public class Ant implements Serializable {
int posAmeise, aktuellesIcon = 1, altePosAmeise;
Color alteFarbe, neueFarbe;
ArrayList<ImageIcon> ameisen = new ArrayList<>();
public Ant(state s) {
this.posAmeise = s.posAmeise;
s.jbArrayy[posAmeise].setIcon(s.ameisen.get(aktuellesIcon));
}
}

How do i set delay after function java

I'm developing an memory card game in java. I need a delay after SelectedTile.hideFace();
Control.java
package control;
public class Control extends JFrame {
private static final long serialVersionUID = 1L;
public static Control CurrentWindow = null;
private ImageIcon background1,background2,background3,background4,background5,background6,background7,background8;
private final String title ="Remembory";
private Tile SelectedTile = null;
private int points = 0;
private int fails = 0;
private int failsleft = 5;
private JLabel score = new JLabel("Score:0");
private JLabel pogingen = new JLabel("Pogingen:5");
public Control() {
setSize(334,464);
setTitle(title);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBackground(Color.BLACK);
setUpGame();
add(score,BorderLayout.SOUTH);
score.setForeground(new Color(1,21,118));
score.setFont(score.getFont().deriveFont(18.0f));
add(pogingen,BorderLayout.SOUTH);
pogingen.setForeground(new Color(1,21,118));
pogingen.setFont(pogingen.getFont().deriveFont(18.0f));
setVisible(true);
}
public void setUpGame()
{
background1 = new ImageIcon("src//card.png");
background2 = new ImageIcon("src//card1.png");
background3 = new ImageIcon("src//card2.png");
background4 = new ImageIcon("src//card3.png");
background5 = new ImageIcon("src//card4.png");
background6 = new ImageIcon("src//card5.png");
background7 = new ImageIcon("src//card6.png");
background8 = new ImageIcon("src//card7.png");
getContentPane().setLayout(new FlowLayout());
getContentPane().add(new Tile(background1));
getContentPane().add(new Tile(background1));
getContentPane().add(new Tile(background2));
getContentPane().add(new Tile(background2));
getContentPane().add(new Tile(background3));
getContentPane().add(new Tile(background3));
getContentPane().add(new Tile(background4));
getContentPane().add(new Tile(background4));
getContentPane().add(new Tile(background5));
getContentPane().add(new Tile(background5));
getContentPane().add(new Tile(background6));
getContentPane().add(new Tile(background6));
getContentPane().add(new Tile(background7));
getContentPane().add(new Tile(background7));
getContentPane().add(new Tile(background8));
getContentPane().add(new Tile(background8));
}
private void Addfails() {
fails++;
failsleft--;
pogingen.setText("Pogingen:" + failsleft);
repaint();
System.out.println( "Poging " + fails + " u heeft nog " + failsleft + " poging over" );
}
private void AddPoint() {
points++;
score.setText("Score:" + points);
repaint();
System.out.println(" + " + points + "Punten");
}
public void TileClicked (Tile tile){
if (SelectedTile == null) {
tile.showFace();
SelectedTile = tile;
return;
}
if (SelectedTile == tile) {
tile.hideFace();
SelectedTile = null;
return;
}
if (points < 8){
tile.showFace();
}
if (fails > 3){
JOptionPane.showMessageDialog(null, "Helaas u hebt geen pogingen meer");
System.exit(0);
}
if (points == 7){
JOptionPane.showMessageDialog(null, "Gefeliciteerd! Jou score is : " + points);
System.exit(0);
}
if (SelectedTile.getFaceColor().equals(tile.getFaceColor())) {
AddPoint();
SelectedTile = null;
return;
}
SelectedTile.hideFace();
//delay here
tile.hideFace();
Addfails();
System.out.println("Probeer het nogmaals");
SelectedTile = null;
}
public static void main(String[] args){
CurrentWindow = new Control();
}
}
Tile.java
package Tiles;
public class Tile extends JLabel implements MouseListener{
private static final long serialVersionUID = 1L;
private ImageIcon faceColor = new ImageIcon("src//background.png"); // standaard image (back)
private final static Dimension size = new Dimension(71,96);
public Tile(ImageIcon kleur)
{
setFaceColor(kleur);
setMinimumSize(size);
setMaximumSize(size);
setPreferredSize(size);
setOpaque(true);
setIcon(new ImageIcon("src//background.png"));
addMouseListener(this);
}
public void showFace()
{
//setBackground(faceColor);
setIcon(faceColor);
}
public void hideFace()
{
setIcon(new ImageIcon("src//background.png"));
//setBackground(new Color(213,86,31));
}
protected void setFaceColor(ImageIcon c)
{
this.faceColor = c;
}
public ImageIcon getFaceColor()
{
return this.faceColor;
}
public void mouseClicked(MouseEvent arg0) {
control.Control.CurrentWindow.TileClicked(this);
}
public void mouseEntered(MouseEvent arg0) {
}
public void mouseExited(MouseEvent arg0) {
}
public void mousePressed(MouseEvent arg0) {
}
public void mouseReleased(MouseEvent arg0) {
}
}
What do mean with "delay"? Normally, a Thread.sleep(milliseconds) would do the job, but the program will completely stop at this moment!
If you want to have an action with a delay (like hiding your cards after 500 milliseconds) you can schedule it like this:
import java.util.Timer;
import java.util.TimerTask;
// ...
SelectedTile.hideFace();
new Timer().schedule(new TimerTask() {
public void run() {
tile.hideFace();
}
}, 500); // hide face after 500 ms
// ...

Getting the error " Cannot find symbol " on getdocumentBase()

Despite I import the applet library, NetBeans cannot recognize and use getDocumentBase() in my code, I have my html file within my project and all other required files as well, here is a part of my code :
import java.awt.*;
import java.applet.*;
public class AirportCanvas extends Canvas
{
SingleLaneAirport controller;
Image redPlane;
Image bluePlane;
Image airport;
//AudioClip crashSound;
int[] redX,redY,blueX,blueY;
int maxCar = 2;
final static int initredX = 5;
final static int initredY = 55;
final static int initblueX = 410;
final static int initblueY = 130;
final static int bridgeY = 90;
boolean frozen = false;
int cycleTime = 20;
AirportCanvas(SingleLaneAirport controller)
{
super();
this.controller = controller;
// crashSound=controller.getAudioClip(controller.getDocumentBase(),"crash.au");
MediaTracker mt;
mt = new MediaTracker(this);
redPlane = controller.getImage(controller.getDocumentBase(), "redplane.png");
mt.addImage(redPlane, 0);
bluePlane = controller.getImage(controller.getDocumentBase(), "blueplane.png");
mt.addImage(bluePlane, 1);
airport = controller.getImage(controller.getDocumentBase(), "airport.png");
mt.addImage(airport, 2);
try
{
mt.waitForID(0);
mt.waitForID(1);
mt.waitForID(2);
}
catch (java.lang.InterruptedException e)
{
System.out.println("Couldn't load one of the images");
}
setSize(airport.getWidth(null),airport.getHeight(null));
init(1);
}
public final void init(int ncars)
{ //set number of cars
maxCar = ncars;
frozen = false;
redX = new int[maxCar];
redY = new int[maxCar];
blueX = new int[maxCar];
blueY = new int[maxCar];
for (int i = 0; i<maxCar ; i++)
{
redX[i] = initredX - i*85;
redY[i] = initredY;
blueX[i] =initblueX + i*85;
blueY[i] =initblueY;
}
repaint();
}
Image offscreen;
Dimension offscreensize;
Graphics offgraphics;
public void backdrop()
{
Dimension d = getSize();
if ((offscreen == null) || (d.width != offscreensize.width)
|| (d.height != offscreensize.height))
{
offscreen = createImage(d.width, d.height);
offscreensize = d;
offgraphics = offscreen.getGraphics();
offgraphics.setFont(new Font("Helvetica",Font.BOLD,36));
}
offgraphics.setColor(Color.lightGray);
offgraphics.drawImage(airport,0,0,this);
}
#Override
public void paint(Graphics g)
{
update(g);
}
#Override
public void update(Graphics g)
{
backdrop();
for (int i=0; i<maxCar; i++)
{
offgraphics.drawImage(redPlane,redX[i],redY[i],this);
offgraphics.drawImage(bluePlane,blueX[i],blueY[i],this);
}
if (blueY[0]==redY[0] && Math.abs(redX[0]+80 - blueX[0])<5)
{
offgraphics.setColor(Color.red);
offgraphics.drawString("Crunch!",200,100);
frozen=true;
// crashSound.play();
}
g.drawImage(offscreen, 0, 0, null);
}
//returns true for the period from just before until just after car on bridge
public boolean moveRed(int i) throws InterruptedException
{
int X = redX[i];
int Y = redY[i];
synchronized (this)
{
while (frozen )
wait();
if (i==0 || Math.abs(redX[i-1] - X) > 120)
{
X += 2;
if (X >=500)
{
X = -80; Y = initredY;
}
if (X >=60 && X < 290 && Y<bridgeY)
++Y;
if (X >=290 && Y>initredY)
--Y;
}
redX[i]=X;
redY[i]=Y;
repaint();
}
Thread.sleep(cycleTime);
return (X>25 && X<400);
}
//returns true for the period from just before until just after car on bridge
public boolean moveBlue(int i) throws InterruptedException
{
int X = blueX[i];
int Y = blueY[i];
synchronized (this)
{
while (frozen )
wait();
if (i==0 || Math.abs(blueX[i-1] - X) > 120)
{
X -= 2;
if (X <=-80)
{
X = 500; Y = initblueY;
}
if (X <=370 && X > 130 && Y>bridgeY)
--Y;
if (X <=130 && Y<initblueY)
++Y;
blueX[i]=X;
}
blueY[i]=Y;
repaint();
}
Thread.sleep(cycleTime);
repaint();
return (X>25 && X<400);
}
public synchronized void freeze()
{
frozen = true;
}
public synchronized void thaw()
{
frozen = false;
notifyAll();
}
}
Single Lane Airport Class :
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class SingleLaneAirport {
AirportCanvas display;
Button restart;
Button freeze;
Button onecar;
Button twocar;
Button threecar;
Checkbox fair;
Checkbox safe;
boolean fixed = false;
int maxCar = 1;
Thread red[];
Thread blue[];
#Override
public void init()
{
setLayout(new BorderLayout());
display = new AirportCanvas(this);
add("Center",display);
restart = new Button("Restart");
restart.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
display.thaw();
}
});
freeze = new Button("Freeze");
freeze.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
display.freeze();
}
});
onecar = new Button("One Car");
onecar.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
stop();
maxCar = 1;
start();
}
});
twocar = new Button("Two Cars");
twocar.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
stop();
maxCar = 2;
start();
}
});
threecar = new Button("Three Cars");
threecar.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
stop();
maxCar = 3;
start();
}
});
safe = new Checkbox("Safe",null,true);
safe.setBackground(Color.lightGray);
safe.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
stop();
start();
}
});
fair = new Checkbox("Fair",null,false);
fair.setBackground(Color.lightGray);
fair.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
stop();
start();
}
});
Panel p1 = new Panel();
p1.setLayout(new FlowLayout());
p1.add(freeze);
p1.add(restart);
p1.add(onecar);
p1.add(twocar);
p1.add(threecar);
p1.add(safe);
p1.add(fair);
add("South",p1);
setBackground(Color.lightGray);
}
#Override
public void start()
{
red = new Thread[maxCar];
blue = new Thread[maxCar];
display.init(maxCar);
Airport b;
if (fair.getState() && safe.getState())
b = new FairAirport();
else if ( safe.getState())
b = new SafeAirport();
else
b = new Airport();
for (int i = 0; i<maxCar; i++)
{
red[i] = new Thread(new RedPlane(b,display,i));
blue[i] = new Thread(new BluePlane(b,display,i));
}
for (int i = 0; i<maxCar; i++)
{
red[i].start();
blue[i].start();
}
}
#Override
public void stop()
{
for (int i = 0; i<maxCar; i++)
{
red[i].interrupt();
blue[i].interrupt();
}
}
}
Your class SingleLaneAirport should extend Applet class in order to use getDocumentBase() function.
Because getDocumentBase() is the function of Applet class and not the Object class

Animations when using Gridbag Layout.

I have recently started Java and wondered if it was possible to make Animations whilst using GridBag Layout.
Are these possible and how? Any tutorials, help and such would be greatly appreciated :)
In order to perform any kind of animation of this nature, you're going to need some kind of proxy layout manager.
It needs to determine the current position of all the components, the position that the layout manager would like them to have and then move them into position.
The following example demonstrates the basic idea. The animation engine use is VERY basic and does not include features like slow-in and slow-out fundamentals, but uses a linear approach.
public class TestAnimatedLayout {
public static void main(String[] args) {
new TestAnimatedLayout();
}
public TestAnimatedLayout() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestAnimatedLayoutPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestAnimatedLayoutPane extends JPanel {
public TestAnimatedLayoutPane() {
setLayout(new AnimatedLayout(new GridBagLayout()));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
add(new JLabel("Value:"), gbc);
gbc.gridx++;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
add(new JComboBox(), gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.gridwidth = 2;
add(new JScrollPane(new JTextArea()), gbc);
gbc.gridwidth = 0;
gbc.gridy++;
gbc.gridx++;
gbc.weightx = 0;
gbc.weighty = 0;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.EAST;
add(new JButton("Click"), gbc);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
public class AnimatedLayout implements LayoutManager2 {
private LayoutManager2 proxy;
private Map<Component, Rectangle> mapStart;
private Map<Component, Rectangle> mapTarget;
private Map<Container, Timer> mapTrips;
private Map<Container, Animator> mapAnimators;
public AnimatedLayout(LayoutManager2 proxy) {
this.proxy = proxy;
mapTrips = new WeakHashMap<>(5);
mapAnimators = new WeakHashMap<>(5);
}
#Override
public void addLayoutComponent(String name, Component comp) {
proxy.addLayoutComponent(name, comp);
}
#Override
public void removeLayoutComponent(Component comp) {
proxy.removeLayoutComponent(comp);
}
#Override
public Dimension preferredLayoutSize(Container parent) {
return proxy.preferredLayoutSize(parent);
}
#Override
public Dimension minimumLayoutSize(Container parent) {
return proxy.minimumLayoutSize(parent);
}
#Override
public void layoutContainer(Container parent) {
Timer timer = mapTrips.get(parent);
if (timer == null) {
System.out.println("...create new trip");
timer = new Timer(125, new TripAction(parent));
timer.setRepeats(false);
timer.setCoalesce(false);
mapTrips.put(parent, timer);
}
System.out.println("trip...");
timer.restart();
}
protected void doLayout(Container parent) {
System.out.println("doLayout...");
mapStart = new HashMap<>(parent.getComponentCount());
for (Component comp : parent.getComponents()) {
mapStart.put(comp, (Rectangle) comp.getBounds().clone());
}
proxy.layoutContainer(parent);
LayoutConstraints constraints = new LayoutConstraints();
for (Component comp : parent.getComponents()) {
Rectangle bounds = comp.getBounds();
Rectangle startBounds = mapStart.get(comp);
if (!mapStart.get(comp).equals(bounds)) {
comp.setBounds(startBounds);
constraints.add(comp, startBounds, bounds);
}
}
System.out.println("Items to layout " + constraints.size());
if (constraints.size() > 0) {
Animator animator = mapAnimators.get(parent);
if (animator == null) {
animator = new Animator(parent, constraints);
mapAnimators.put(parent, animator);
} else {
animator.setConstraints(constraints);
}
animator.restart();
} else {
if (mapAnimators.containsKey(parent)) {
Animator animator = mapAnimators.get(parent);
animator.stop();
mapAnimators.remove(parent);
}
}
}
#Override
public void addLayoutComponent(Component comp, Object constraints) {
proxy.addLayoutComponent(comp, constraints);
}
#Override
public Dimension maximumLayoutSize(Container target) {
return proxy.maximumLayoutSize(target);
}
#Override
public float getLayoutAlignmentX(Container target) {
return proxy.getLayoutAlignmentX(target);
}
#Override
public float getLayoutAlignmentY(Container target) {
return proxy.getLayoutAlignmentY(target);
}
#Override
public void invalidateLayout(Container target) {
proxy.invalidateLayout(target);
}
protected class TripAction implements ActionListener {
private Container container;
public TripAction(Container container) {
this.container = container;
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("...trip");
mapTrips.remove(container);
doLayout(container);
}
}
}
public class LayoutConstraints {
private List<AnimationBounds> animationBounds;
public LayoutConstraints() {
animationBounds = new ArrayList<AnimationBounds>(25);
}
public void add(Component comp, Rectangle startBounds, Rectangle targetBounds) {
add(new AnimationBounds(comp, startBounds, targetBounds));
}
public void add(AnimationBounds bounds) {
animationBounds.add(bounds);
}
public int size() {
return animationBounds.size();
}
public AnimationBounds[] getAnimationBounds() {
return animationBounds.toArray(new AnimationBounds[animationBounds.size()]);
}
}
public class AnimationBounds {
private Component component;
private Rectangle startBounds;
private Rectangle targetBounds;
public AnimationBounds(Component component, Rectangle startBounds, Rectangle targetBounds) {
this.component = component;
this.startBounds = startBounds;
this.targetBounds = targetBounds;
}
public Rectangle getStartBounds() {
return startBounds;
}
public Rectangle getTargetBounds() {
return targetBounds;
}
public Component getComponent() {
return component;
}
public Rectangle getBounds(float progress) {
return calculateProgress(getStartBounds(), getTargetBounds(), progress);
}
}
public static Rectangle calculateProgress(Rectangle startBounds, Rectangle targetBounds, float progress) {
Rectangle bounds = new Rectangle();
if (startBounds != null && targetBounds != null) {
bounds.setLocation(calculateProgress(startBounds.getLocation(), targetBounds.getLocation(), progress));
bounds.setSize(calculateProgress(startBounds.getSize(), targetBounds.getSize(), progress));
}
return bounds;
}
public static Point calculateProgress(Point startPoint, Point targetPoint, float progress) {
Point point = new Point();
if (startPoint != null && targetPoint != null) {
point.x = calculateProgress(startPoint.x, targetPoint.x, progress);
point.y = calculateProgress(startPoint.y, targetPoint.y, progress);
}
return point;
}
public static Dimension calculateProgress(Dimension startSize, Dimension targetSize, float progress) {
Dimension size = new Dimension();
if (startSize != null && targetSize != null) {
size.width = calculateProgress(startSize.width, targetSize.width, progress);
size.height = calculateProgress(startSize.height, targetSize.height, progress);
}
return size;
}
public static int calculateProgress(int startValue, int endValue, float fraction) {
int value = 0;
int distance = endValue - startValue;
value = (int) ((float) distance * fraction);
value += startValue;
return value;
}
public class Animator implements ActionListener {
private Timer timer;
private LayoutConstraints constraints;
private int tick;
private Container parent;
public Animator(Container parent, LayoutConstraints constraints) {
setConstraints(constraints);
timer = new Timer(16, this);
timer.setRepeats(true);
timer.setCoalesce(true);
this.parent = parent;
}
private void setConstraints(LayoutConstraints constraints) {
this.constraints = constraints;
}
public void restart() {
tick = 0;
timer.restart();
}
protected void stop() {
timer.stop();
tick = 0;
}
#Override
public void actionPerformed(ActionEvent e) {
tick += 16;
float progress = (float)tick / (float)1000;
if (progress >= 1f) {
progress = 1f;
timer.stop();
}
for (AnimationBounds ab : constraints.getAnimationBounds()) {
Rectangle bounds = ab.getBounds(progress);
Component comp = ab.getComponent();
comp.setBounds(bounds);
comp.invalidate();
comp.repaint();
}
parent.repaint();
}
}
}
Update
You could also take a look at AurelianRibbon/Sliding-Layout
This is the program which i did long time back when i just started my Java classes.I did simple animations on different tabs on JTabbedPane (change the path of images/sound file as required),hope this helps:
UPDATE:
Sorry about not following concurrency in Swing.
Here is updated answer:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class ClassTestHello extends JApplet {
private static JPanel j1;
private JLabel jl;
private JPanel j2;
private Timer timer;
private int i = 0;
private int[] a = new int[10];
#Override
public void init() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
start();
paint();
}
});
}
public void paint() {
jl = new JLabel("hiii");
j1.add(jl);
a[0] = 1000;
a[1] = 800;
a[2] = 900;
a[3] = 2000;
a[4] = 500;
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
if(i % 2 == 0)
jl.setText("hiii");
else
jl.setText("byee");
i++;
if(i > 4)
i=0;
timer.setDelay(a[i]);
}
};
timer = new Timer(a[i], actionListener);
timer.setInitialDelay(0);
timer.start();
}
#Override
public void start() {
j1 = new JPanel();
j2 = new JPanel();
JTabbedPane jt1 = new JTabbedPane();
ImageIcon ic = new ImageIcon("e:/guitar.gif");
JLabel jLabel3 = new JLabel(ic);
j2.add(jLabel3);
jt1.add("one", j1);
jt1.addTab("hii", j2);
getContentPane().add(jt1);
}
}

Categories

Resources