So I am writing a program which has several layers of menus using a JFrame with JButtons but once the user clicks a button that button ends up stuck as selected and I cannot update it. Any help please?
Code:
// Libraries
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class test extends JComponent implements ActionListener {
// Globals
static String buttonPressed = "";
// Dimensions
static final int WIDTH = 765;
static final int HEIGHT = 765;
static final int BUTTON_WIDTH = 220;
static final int BUTTON_HEIGHT = 105;
// General file path
static final String filePath = "<General path for my images>";
// GUI construction
static JFrame mainFrame;
static JButton tl;
public static void main(String[] args) throws IOException {
GUI menuCall = new GUI();
menuCall.menu();
}
public void menu() throws IOException {
// Main JFrame construction
mainFrame = new JFrame("Racing Game");
mainFrame.setSize(WIDTH, HEIGHT);
mainFrame.setLayout(null);
mainFrame.setLocationRelativeTo(null);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setResizable(false);
// Sets background of main JFrame to menu background - calls ImagePanel class
BufferedImage backBuff = ImageIO.read(new File((filePath + "\\Sprites\\Menu.png")));
mainFrame.setContentPane(new ImagePanel(backBuff));
// Menu JButton setup
tl = new JButton("Free Drive");
tl.setBounds(112, 112, BUTTON_WIDTH, BUTTON_HEIGHT);
tl.setForeground(Color.white);
tl.setBackground(Color.decode("0x04092E"));
tl.setFocusPainted(false);
tl.addActionListener(this);
mainFrame.add(tl);
//...
// Makes the main JFrame visible
mainFrame.setVisible(true);
}
public static void freeDrive() {
try {
Thread.sleep(1000000); // Just doing this to show that it stays selected, there is other code here
} catch (Exception e) {}
}
// Overrides
@Override
public void actionPerformed(ActionEvent e) {
freeDrive();
}
}
I've tried removing the JButton, setting it as not selected and updating a variable to allow the override subroutine to end (this I thought would definitely work but for some reason the variable isn't saved when the code returns to the main subroutine - any advice on how to fix this would also be great).
Thread.sleep()
on the Event Dispatch Thread (EDT). That's a no-no. Try using Swing timer instead.Swing Worker
may be a solution.