Java.awt.event classes management - java

I started writing a game (also taking code parts online) in Java all in one class and now I'm trying to break it into multiple classes but awt.event is giving me problems.
I want the class MainGUI to implement awt.event classes but methods keyPressed and actionPerformed must only contain a call to a method that is in another class that contains the code to be executed in correspondence with the occurrence of the event .
I am doing this because I want the class mainGUI to only realize the game window , leaving the management of controls to another class .
I tried to transfer the code and implement the methods to call and everything works except the method requestFocus .
When I call it indirectly from the class used for the control, asking him to move the focus to the game window, it does not work .
So, the class I want to break is MainGUI and the class I want to manage the controls is Logic:
public class MainGUI extends JFrame implements ComponentListener, ActionListener, FocusListener, KeyListener {
//STATIC ATTRIBUTES
private final static int UP = 0, LEFT = 1, DOWN = 2, RIGHT = 3, STOP = 4;
private final static int NUMBER_OF_ROWS = 70;
private final static int NUMBER_OF_COLUMNS = 70;
private static int direction;
private static int currentX, currentY;
//INSTANCE ATTRIBUTES
private BoardPanel drawPanel;
private JPanel bottomPanel;
private JLabel message;
private Timer timer;
//CONSTRUCTOR
public MainGUI() {
super("Grid");
createGUI();
}
//PUBLIC INSTANCE METHODS
public void createbottomPanel(){
this.bottomPanel=new JPanel();
this.message = new JLabel("To START, Press \"ENTER\"", JLabel.CENTER);
this.message.setBackground(Color.LIGHT_GRAY);
this.message.setBorder(BorderFactory.createEmptyBorder(5,0,5,0));
this.bottomPanel.add(this.message);
}
public void createGUI(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setPreferredSize(new Dimension(800, 600));
this.drawPanel = new BoardPanel();
createbottomPanel();
addComponentListener(this);
addKeyListener(this);
addFocusListener(this);
this.message.addKeyListener(this);
Container contPane = getContentPane();
contPane.setLayout(new BorderLayout());
contPane.add(this.drawPanel,BorderLayout.CENTER);
contPane.add(this.bottomPanel, BorderLayout.SOUTH);
this.currentX = 50;
this.currentY = 30;
this.direction = STOP;
this.message.requestFocus();
pack();
}
public void componentResized(ComponentEvent e) {
this.drawPanel.setGridUnit();
}
public void componentHidden(ComponentEvent e) {
//do-nothing
}
public void componentMoved(ComponentEvent e) {
//do-nothing
}
public void componentShown(ComponentEvent e) {
//do-nothing
}
public void actionPerformed(ActionEvent e) {
switch (direction) {
case UP:
if (currentY > 0)
currentY--;
BoardPanel.fillCell(currentX,currentY);
this.drawPanel.repaint();
break;
case DOWN:
if (currentY < NUMBER_OF_ROWS-1)
currentY++;
BoardPanel.fillCell(currentX,currentY);
this.drawPanel.repaint();
break;
case RIGHT:
if (currentX < NUMBER_OF_COLUMNS-1)
currentX++;
BoardPanel.fillCell(currentX,currentY);
this.drawPanel.repaint();
break;
case LEFT:
if (currentX > 0)
currentX--;
BoardPanel.fillCell(currentX,currentY);
this.drawPanel.repaint();
break;
}
}
public void focusGained(FocusEvent e) {
direction=STOP;
message.setText("To PAUSE, Press \"P\"");
timer = new Timer(50,this);
timer.start();
}
public void focusLost(FocusEvent e) {
if (timer != null)
timer.stop();
timer = null;
message.setText("To START, Press \"ENTER\"");
}
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_LEFT)
direction = LEFT;
else if (code == KeyEvent.VK_RIGHT)
direction = RIGHT;
else if (code == KeyEvent.VK_UP)
direction = UP;
else if (code == KeyEvent.VK_DOWN)
direction = DOWN;
else if (code == KeyEvent.VK_P)
message.requestFocus();
else if (code == KeyEvent.VK_ENTER)
this.requestFocus();
}
public void keyReleased(KeyEvent e) {
//do-nothing
}
public void keyTyped(KeyEvent e) {
//do-nothing
}
//STATIC METHODS
public static void openWindow() {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run () {
new MainGUI().setVisible(true);
}
});
}
} // end class
The class Logic:
public class Logic {
//STATIC ATTRIBUTES
private static MainGUI test = new MainGUI();
//STATIC METHODS
public static void initGame(){
test.openWindow();
}
//This method must be called from actionPerformed in MainGUI and
//contain the code to be executed
public static void logicPerforms(){
//empty-for-now
}
//This method must be called from keyPressed in MainGUI and
//contain the code to be executed
public static void logicPress(){
//empty-for-now
}
} //end-class
The classes are in different packages but I omitted the various imports.
The class Boardpanel draws a grid and colors the cell coordinates (x, y) through its method fillCells.
The main class is:
public class Main {
public static void main(String[] args) {
Logic.initGame();
}
} //end-class
I transferred the necessary variables in the class Logic, copied the code from the methods actionPerformed and keyPressed of MainGUI and created static methods ( for example, to run the repaint ) to be called from logicPerforms and logicPress to solve call problems but these lines are not working:
else if (code == KeyEvent.VK_P)
test.askMessageFocus();
else if (code == KeyEvent.VK_ENTER)
test.askGUIFocus();
where askMessageFocus e askGUIFocus are two of those static methods mentioned earlier (they are in the class MainGUI) whose code is:
this.message.requestFocus();
for askMessageFocus and
this.requestFocus();
for the other one.
I apologize for my English and other mistakes I may have made ​​in the code, I hope someone can help me!
Almost any advice will be welcome , even aimed at optimizing other parts of code!
Thank you!!

Related

problem with calling the method after pressing the key

I would like to implement KeyListiner so that when pressing Space key program would generate new object of Function class and draw new image representing this function. For now program is working but pressing space key does not allow to generate a new image. Every advice will be greatly appreciated :)
Main class:
public class Main {
public static void main(String[] args) {
JFrame window = new JFrame(SOFTWARE_TITLE);
MainView mainView = new MainView();
Key key = new Key();
Controller controller = new Controller(mainView);
key.setController(controller);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(790, 580);
window.setLocationRelativeTo(null);
window.setResizable(false);
window.add(mainView);
window.setVisible(true);
}
}
MainView class:
public class MainView extends JPanel {
private Function function;
public MainView(){
super();
setBackground(Color.GRAY);
setLayout(null);
setSize(200, 200);
function = new Function();
DrawBoard drawBoard = new DrawBoard(function);
drawBoard.setSize(500, 500);
drawBoard.setBackground(Color.lightGray);
drawBoard.setLocation(250, 20);
add(drawBoard);
setVisible(true);
}
}
DrawBoard class:
public class DrawBoard extends Canvas {
short CUSTOM_WIDTH = 5 * 100;
private Function function;
public DrawBoard(Function function) {
this.function = function;
}
public void paint(Graphics g) {
double difference = function.getzMax() - function.getzMin();
for (int indexX = 0; indexX < 100; indexX++) {
for (int indexY = 0; indexY < 100; indexY++) {
double value = function.getPoints()[indexX][indexY].getZ() - function.getzMin();
double corrected = setFloatInRGBRange(difference, value);
g.setColor(intToColor((int) corrected));
g.fillRect(indexX * 5, CUSTOM_WIDTH - ((indexY+1) * 5), 5, 5);
}
}
}
public Color intToColor(int colNum){
return new Color(colNum, colNum, colNum);
}
private int setFloatInRGBRange(double difference, double value){
return (int) ((255 * value)/difference);
}
}
Key class:
public class Key implements KeyListener {
Controller controller;
public void setController(Controller controller) {
this.controller = controller;
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
if (e.getKeyChar() == KeyEvent.VK_SPACE){
controller.generateFormula();
}
}
}
Controller class:
public class Controller {
MainView mainView;
public Controller(MainView mainView) {
this.mainView = mainView;
}
public void generateFormula() {
this.mainView = new MainView();
}
}
There is some other things that need be reviewed in code you posted. But for your main concern i guess you donc check Key strokes properly.
I would use e.getKeyCode() instead of e.getKeyChar() to check the event.
So your condition would be : e.getKeyCode() == KeyEvent.VK_SPACE
it is out of topic, but :
Your use of Function in multiples classes is unnecessary. It could be used only in DrawBoard
Don't mix Swing and AWT components as other already advised

KeyListener not responding to key inputs [duplicate]

This question already has an answer here:
Pong Paddle bottom doesn't move up when UP key is pressed
(1 answer)
Closed 7 years ago.
So I have seen a couple of these questions asked. They all say that you should not be using a Keylistener but instead a KeyBinding thing. But when I go to use the Keybinding it does not work. I understand I probably should be using the KeyBinding thing but is there a way that I can fix my code so that the KeyListener works. Thank you.
Game Class:
public class Game extends JFrame implements KeyListener{
public static int ppx,ppy;
public static void main(String[] args) {
JFrame frame = new JFrame("Game");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,600);
frame.add(new THIng());
frame.setVisible(true);
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
int keycode = e.getKeyCode();
if(keycode == KeyEvent.VK_D){
System.out.println("Debug");
}
}
#Override
public void keyReleased(KeyEvent e) {
}
}
THIng Class:
public class THIng extends JPanel{
public static int px,py,pwid,phei;
public void main(String[]args){
Timer timer;
timer = new Timer(60,
new ActionListener(){
public void actionPerformed(ActionEvent evt){
p();
}
}
);
}
public THIng(){
px = Game.ppx;py = Game.ppy;pwid = 50;phei = pwid;
}
#Override
public Dimension getPreferredSize(){
return new Dimension(500,600);
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics p = (Graphics)g;
p.drawRect(px,py,pwid,phei);
}
public void p(){
repaint();
}
}
you don't have to make a constructor, just add frame.addKeyListener(this); where you have set other properties of the JFrame.
as MadProgrammer has pointed out the right thing to do is use the Key Bindings API which you can see step by step Key Bindings API
add a constructor that adds a key listener and in your main make it class Game instead of JFrame
public class Game extends JFrame implements KeyListener{
public static int ppx,ppy;
public Game(String string) {
addKeyListener(this);
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
Game frame = new Game("Game");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,600);
frame.add(new THIng());
frame.setVisible(true);
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
int keycode = e.getKeyCode();
if(keycode == KeyEvent.VK_D){
System.out.println("Debug");
}
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}

KeyListener is not being called [duplicate]

I am trying to do something when one of the arrow keys are pressed using the KeyListener in my JPanel class. Here is my code:
public class TestPanel extends JPanel implements KeyListener{
public TestPanel(){
this.addKeyListener(this);
this.setFocusable(true);
this.requestFocusInWindow();
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
System.out.println("Right");
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
System.out.println("Left");
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
}
My main method adds a new instance of this panel to a frame and displays it. Do I need to add the keylistener to the JFrame? In my case, this would be difficult and inefficient, so I would like to make it work with this JPanel if possible. Anyone know what I am doing wrong?
EDIT: Key Bindings code that does not work either:
public class GamePanel extends JPanel implements ActionListener{
//Constructor
public GamePanel(){
setupKeyBinding();
this.setFocusable(true);
this.requestFocusInWindow();
}
private void setupKeyBinding() {
int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
InputMap inMap = getInputMap(condition);
ActionMap actMap = getActionMap();
inMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "Left");
actMap.put("Left", new leftAction());
}
private class leftAction extends AbstractAction {
public void actionPerformed(ActionEvent e) {
System.out.println("test");
}
}
public void actionPerformed(ActionEvent e) {
//some other game info
}
}
Can someone tell me why this doesnt work either? (my second action listener is for other stuff needed for my game)
If you search this problem, you'll see that it is asked and has been solved many times.
KeyListeners need to be on the focused component to work. One solution is to give your component the focus after first making it focusable.
Better by a long shot however is to use Key Bindings. Google the tutorial on this.
Please have a look at my answer to this question for more on this, including many of the gory details.
For reference, I've create an example using your approach; while it works, it also suggests a focus problem elsewhere in your code. Key Bindings avoid this, as shown here.
Addendum: Here's my working key binding.
private static class TestPanel extends JPanel {
private static final String LEFT = "Left";
private Action left = new AbstractAction(LEFT) {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(LEFT);
}
};
private static final String RIGHT = "Right";
private Action right = new AbstractAction(RIGHT) {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(RIGHT);
}
};
public TestPanel() {
this.getInputMap().put(
KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), LEFT);
this.getActionMap().put(LEFT, left);
this.getInputMap().put(
KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), RIGHT);
this.getActionMap().put(RIGHT, right);
}
}
Original SSCCE:
import java.awt.EventQueue;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* #see https://stackoverflow.com/a/16531380/230513
*/
public class Test {
private void display() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new TestPanel());
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private static class TestPanel extends JPanel implements KeyListener {
public TestPanel() {
this.addKeyListener(this);
this.setFocusable(true);
this.requestFocusInWindow();
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
System.out.println("Right");
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
System.out.println("Left");
}
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Test().display();
}
});
}
}
For receives key events on JPanel you must set focus:
setFocusable(true);
requestFocus();
the JPanel now has focus, so it receives key events
I had to do two things: I added comp.setFocusable(true); to the component comp that listens to key events, and I added comp.requestFocus(); to each action which caused comp to lose the focus.

Keylistener not working for JPanel

I am trying to do something when one of the arrow keys are pressed using the KeyListener in my JPanel class. Here is my code:
public class TestPanel extends JPanel implements KeyListener{
public TestPanel(){
this.addKeyListener(this);
this.setFocusable(true);
this.requestFocusInWindow();
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
System.out.println("Right");
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
System.out.println("Left");
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
}
My main method adds a new instance of this panel to a frame and displays it. Do I need to add the keylistener to the JFrame? In my case, this would be difficult and inefficient, so I would like to make it work with this JPanel if possible. Anyone know what I am doing wrong?
EDIT: Key Bindings code that does not work either:
public class GamePanel extends JPanel implements ActionListener{
//Constructor
public GamePanel(){
setupKeyBinding();
this.setFocusable(true);
this.requestFocusInWindow();
}
private void setupKeyBinding() {
int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
InputMap inMap = getInputMap(condition);
ActionMap actMap = getActionMap();
inMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "Left");
actMap.put("Left", new leftAction());
}
private class leftAction extends AbstractAction {
public void actionPerformed(ActionEvent e) {
System.out.println("test");
}
}
public void actionPerformed(ActionEvent e) {
//some other game info
}
}
Can someone tell me why this doesnt work either? (my second action listener is for other stuff needed for my game)
If you search this problem, you'll see that it is asked and has been solved many times.
KeyListeners need to be on the focused component to work. One solution is to give your component the focus after first making it focusable.
Better by a long shot however is to use Key Bindings. Google the tutorial on this.
Please have a look at my answer to this question for more on this, including many of the gory details.
For reference, I've create an example using your approach; while it works, it also suggests a focus problem elsewhere in your code. Key Bindings avoid this, as shown here.
Addendum: Here's my working key binding.
private static class TestPanel extends JPanel {
private static final String LEFT = "Left";
private Action left = new AbstractAction(LEFT) {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(LEFT);
}
};
private static final String RIGHT = "Right";
private Action right = new AbstractAction(RIGHT) {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(RIGHT);
}
};
public TestPanel() {
this.getInputMap().put(
KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), LEFT);
this.getActionMap().put(LEFT, left);
this.getInputMap().put(
KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), RIGHT);
this.getActionMap().put(RIGHT, right);
}
}
Original SSCCE:
import java.awt.EventQueue;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* #see https://stackoverflow.com/a/16531380/230513
*/
public class Test {
private void display() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new TestPanel());
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private static class TestPanel extends JPanel implements KeyListener {
public TestPanel() {
this.addKeyListener(this);
this.setFocusable(true);
this.requestFocusInWindow();
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
System.out.println("Right");
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
System.out.println("Left");
}
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Test().display();
}
});
}
}
For receives key events on JPanel you must set focus:
setFocusable(true);
requestFocus();
the JPanel now has focus, so it receives key events
I had to do two things: I added comp.setFocusable(true); to the component comp that listens to key events, and I added comp.requestFocus(); to each action which caused comp to lose the focus.

While loop with delay makes JFrame unresponsive

So, my JFrame becomes unresponsive when I run this code. I managed to trace it back to the while loop under gameLoop(). Regardless of using delay(1000/FRAMERATE) which calls Thread.sleep() within it, it will not allow the Key or Mouse Listeners to do their job.
Full code below, problem exists in gameLoop()
package me.LemmingsGame;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class Game extends JFrame implements KeyListener, MouseListener{
private World wrld;//reference to current world
private WorldFile loader=null;//world data
private int gateCounter;
private int width,height; //width and height of level
private int mx,my;
private int tool = Lemming.CLIMB;
private Image dbImage; private Graphics dbg; //backbuffer
private Image [] sprites;//all images used in game
private Lemming[] lemmings; //array of all Lemmings in level
private int nextLem;//next Lemming to be received from Gate class
private int running;//state of game
private static final int FRAMERATE=180;//assigned framerate
public Game(WorldFile loader){
super("Lemmings");
setLocation(50,40);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
width=3+loader.x*10;height=29+loader.y*10;
loadImages();
lemmings=new Lemming[loader.noLemmings*loader.gates().length];
setSize(width,height);
setVisible(true);
addMouseListener(this);
addKeyListener(this);
this.loader=loader;
running=2;
dbImage= createImage(width,height);
dbg=dbImage.getGraphics();
wrld=new World(loader,createImage(width,height), sprites, this);
gameLoop();
}
public void loadImages(){
sprites=new Image[2];
sprites[0]=new ImageIcon("Resources/toolbar.png").getImage();
sprites[1]=new ImageIcon("Resources/selector.png").getImage();
}
public static void delay(long len){
try{
Thread.sleep(len);
}catch(InterruptedException e){
System.out.println(e);
}
}
public void moveLemmings(){
if(nextLem>0)
for(int i = 0;i<nextLem;i++)
lemmings[i].cycle();
}
public void gameLoop(){
wrld.openGates();
while(running>0){
delay(1000/FRAMERATE);
if(running==2){
gateCounter++;
if(gateCounter>FRAMERATE*2){
wrld.cycleGates();
gateCounter=0;
}
moveLemmings();
if(nextLem>0)
wrld.checkPositions(lemmings,nextLem);
}
repaint();
//paint(getGraphics());
}
}
public void paint(Graphics g){
if(wrld!=null){
dbg.setColor(Color.BLACK);
dbg.fillRect(0, 0, width, height);
wrld.draw(dbg);
if(nextLem>0)
for(int i=0;i<nextLem;i++){
lemmings[i].draw(dbg);
}
dbg.drawImage(sprites[0],0,0,null);
dbg.drawImage(sprites[1],tool-3*39,0,null);
g.drawImage(dbImage,3,29,this);
}
}
public void addLemming(Lemming lemmy) {
lemmings[nextLem]=lemmy;
lemmy.spawn();
nextLem++;
}
public void goal(){
running=0;
dispose();
new Menu();
}
public void fail(){
running=0;
dispose();
new Menu();
}
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void keyTyped(KeyEvent e) {}
public void mousePressed(MouseEvent e) {
System.out.println("boop");
mx=e.getX();
my=e.getY();
if(my<40)
if(mx<40)
tool=Lemming.CLIMB;
else if(mx>39&&mx<=39*2)
tool=Lemming.CHUTE;
}
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void keyPressed(KeyEvent e) {
System.out.println("boop2");
}
public void keyReleased(KeyEvent e) {
}
}
If it matters the program begins here and goes to the Game class
package me.LemmingsGame;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import javax.swing.*;
public class Menu extends JFrame implements ActionListener{
/**
*
*/
private static final long serialVersionUID = -1448646591011984524L;
private JComboBox worldList;
private JButton launch, worldEditor;
private String [] worldPaths;
private String [] worldNames;
private int currentWorld;
public Menu(){
super("Lemmings! By: Jordan and Seth");
this.setLocation(new Point(550,400));
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
File listDir[] = new File("./Worlds").listFiles();
int x=0;
for (int i = 0; i < listDir.length; i++)
if (listDir[i].isDirectory())
x++;
worldPaths=new String[x];
worldNames=new String[x];
x=0;
for (int i = 0; i < listDir.length; i++)
if (listDir[i].isDirectory()){
worldPaths[x]=listDir[i].getPath().substring(2);
worldNames[x]=worldPaths[x].substring(7);
x++;
}
worldList=new JComboBox(worldNames);
worldList.addActionListener(this);
worldEditor=new JButton("Open World Editor");
worldEditor.addActionListener(this);
launch = new JButton("Play");
launch.addActionListener(this);
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
cp.add(worldEditor);
cp.add(worldList);
cp.add(launch);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==worldEditor){
dispose();
new MapEditor();
}else if(e.getSource()==launch){
dispose();
try {
new Game(new WorldFile(worldPaths[currentWorld]));
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}else if(e.getSource()==worldList){
currentWorld=worldList.getSelectedIndex();
}
}
public static void main(String [] args){
new Menu();
}
}
Probably irrelevant, but here's a plug to the github repo https://github.com/cybnetsurfe3011/Lemmings-Computer-Science/
You are performing Thread.sleep() in your main thread which in this case is the EDT (Event Dispatcher Thread). This thread is responsible for painting your graphics and listening to events. By doing Thread.sleep() you are essentially pausing it, thus not allowing it to do it's job.
It seems that you want to refresh your GUI at intervals (at least that is what I am guessing). If this is the case, you will need to move your logic to a new separate thread and then, call what ever update methods you will need from the thread you will have spawned off. To make changes visible, you will need to call the event dispatcher thread again by using the SwingUtilities.invokeLater() method.

Categories