This question already has answers here:
Java swing GUI freezes
(5 answers)
Closed 7 years ago.
I have some Java classes that should simulate an old calculating machine. One of them is a JFrame, called GUI, with a JTabbedPane. The calculating process should take some time, so I have included Thread.sleep(int). The problem is that while the calculating function is working, the tabs of the JTabbedPane in my GUI can't be selected.
Here is some code:
import java.util.*;
import java.awt.*;
public class Engine
{
private GUI gui;
private Store store;
private Mill mill;
public static void main(String[] args) {
Engine e = new Engine();
}
public Engine() {
gui = new GUI(this);
mill = new Mill(this);
store = new Store(this);
store.draw(); // affects GUI elements
}
public void read(String operations) {
clearStatus(); // affects GUI elements
try {
String[] op = operations.split("\n");
for (int i = 0; i < op.length; i++) {
setStatus(op[i]); // affects GUI elements
if (op[i].length() == 0) { // empty line
continue;
}
int number = Integer.parseInt(op[i]);
store.addNumber(number);
Thread.sleep(200);
}
store.draw(); // affects GUI elements
} catch(Exception e) {
System.out.println(e);
}
}
public void clearStatus() {
gui.statusLabel.setText("");
}
public void setStatus(String msg) {
gui.statusLabel.setText(msg);
}
}
Here's my GUI (this is a short version):
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI extends JFrame
{
private Engine engine;
// Swing
JTabbedPane tabs;
JPanel mill;
JTextArea input, store;
JLabel statusLabel;
JButton sendInput;
public GUI(Engine e)
{
engine = e;
input = new JTextArea();
sendInput = new JButton("Run");
sendInput.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
pressInputButton(evt);
}
});
JPanel inputPanel = new JPanel();
inputPanel.add(input, BorderLayout.CENTER);
inputPanel.add(sendInput, BorderLayout.SOUTH);
mill = new JPanel();
statusLabel = new JLabel();
mill.add(statusLabel);
store = new JTextArea();
JTextPane helpPane = new JTextPane();
helpPane.setText("[...]");
tabs = new JTabbedPane();
tabs.addTab("Input", inputPanel);
tabs.addTab("Mill", mill);
tabs.addTab("Store", new JScrollPane(store));
tabs.addTab("Help", helpPanel);
add(tabs, BorderLayout.CENTER);
setVisible(true);
pack();
}
public void pressInputButton(ActionEvent evt) {
engine.read(input.getText());
}
}
What #sorifiend means is, calling sleep() from an event handler will "lock up" your application's event dispatch thread. The application will not respond to any other user input until the event handler function returns.
If you want the application to be responsive while the calculator is "working", then what you need to do is:
Record that the state of the calculator is "working"
Disable whatever buttons you don't want the user to press while the calculator is "working", --OR-- change the handlers for those buttons to do something different (simulate jamming the machine?) if they are pressed while in the "working" state.
Submit a timer event for some time in the near future (however long the calculation is supposed to take.)
In the handler for the timer event, display the result of the calculation, re-enable the disabled buttons, and change the state from "working" back to "idle" (or whatever).
Related
I want to be able to pass user input from my GUI to one of my classes. However, the input is not passed over and immediately checks the if statement.
How do I get program to wait for the input and only checks after the button is clicked?
Main class
public class MainTest {
public static void main(String[] args) {
String weaponCategory;
//Create Java GUI
GUITest window = new GUITest();
if(window.getCategory() != "")
{
System.out.println("test");
}
}
}
GUITest class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUITest implements ActionListener{
private JFrame frmInventorysystem;
private JPanel frameBottom;
private JComboBox equipList;
private String category = "";
private JButton confirmBtn, cancelBtn;
/**
* Create the application.
*/
public GUITest()
{
frmInventorysystem = new JFrame();
frmInventorysystem.setTitle("InventorySystem");
frmInventorysystem.setBounds(100, 100, 450, 300);
frmInventorysystem.getContentPane().setLayout(new BorderLayout(0, 0));
frmInventorysystem.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/*JFrame inside another JFrame is not recommended. JPanels are used instead.
* Creating a flow layout for the bottom frame
*/
frameBottom = new JPanel();
frameBottom.setLayout(new FlowLayout());
//creates comboBox to find out which of the three items player is looking to insert
String[] weaponCategories = {"Weapon", "Armor", "Mod"};
equipList = new JComboBox(weaponCategories);
frmInventorysystem.getContentPane().add(equipList, BorderLayout.NORTH);
//Converting BorderLayout.south into a flow layout
frmInventorysystem.getContentPane().add(frameBottom, BorderLayout.SOUTH);
confirmBtn = new JButton("Confirm");
confirmBtn.addActionListener(this);
frameBottom.add(confirmBtn);
cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(this);
frameBottom.add(cancelBtn);
frmInventorysystem.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
//creates new windows to sort equipment when confirmBtn is clicked
if(e.getSource() == confirmBtn)
{
if(equipList.getSelectedItem().equals("Weapon"))
{
//GUIWeaponCategory weapon = new GUIWeaponCategory();
category = equipList.getSelectedItem().toString();
}
}
//Exits when cancelBtn is clicked
if(e.getSource() == cancelBtn)
{
System.exit(0);
}
}
public String getCategory()
{
return category;
}
public void setCategory(String a)
{
category = a;
}
}
GUITest launches as expected.
However, the first println is missing.
How would I go about doing this?
What concepts or pieces of code am I missing?
EDIT1: Added a couple more details to make the program reproducible and complete.
EDIT2: Making the code more readable for easy understanding.
There are some changes to make on your program
Remove extends JFrame as stated in my comments above, see Extends JFrame vs. creating it inside the program
Place your program on the EDT, see point #3 on this answer and the main method for an example on how to do that.
You're confused about how the ActionListeners work, they wait until you perform certain action in your program (i.e. you press Confirm button) and then do something. "Something" in your program means: Print the selected item and check if it's a weapon then, do something else.
So, in this case, you don't need to return back to main to continue with your program, main only serves to initialize your application and nothing else. You need to think in the events and not in a sequential way. That's the tricky and most important part.
You need to change your programming paradigm from console applications and do-while that everything happens in a sequential manner rather than events that are triggered when the user does something with your application.
For example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUITest implements ActionListener {
private JFrame frmInventorysystem;
private JPanel frameBottom;
private JComboBox equipList;
private JButton confirmBtn, cancelBtn;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new GUITest()); //Java 8+ if using an earlier version check the point #2 in this answer and modify the code accordingly.
}
/**
* Create the application.
*/
public GUITest() {
frmInventorysystem = new JFrame();
frmInventorysystem.setTitle("InventorySystem");
frmInventorysystem.setBounds(100, 100, 450, 300);
frmInventorysystem.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmInventorysystem.getContentPane().setLayout(new BorderLayout(0, 0));
/*
* JFrame inside another JFrame is not recommended. JPanels are used instead
* Creating a flow layout for the bottom frame
*/
frameBottom = new JPanel();
frameBottom.setLayout(new FlowLayout());
// creates comboBox to find out which of the three items player is looking to
// insert
String[] weaponCategories = { "Weapon", "Armor", "Mod" };
equipList = new JComboBox(weaponCategories);
frmInventorysystem.getContentPane().add(equipList, BorderLayout.NORTH);
// Converting BorderLayout.south into a flow layout
frmInventorysystem.getContentPane().add(frameBottom, BorderLayout.SOUTH);
confirmBtn = new JButton("Confirm");
confirmBtn.addActionListener(this);
frameBottom.add(confirmBtn);
cancelBtn = new JButton("Cancel");
cancelBtn.addActionListener(this);
frameBottom.add(cancelBtn);
frmInventorysystem.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
// creates new windows to sort equipment when confirmBtn is clicked
if (e.getSource() == confirmBtn) {
String category = equipList.getSelectedItem().toString(); //Get the selected category
doSomething(category); //Pass it as a parameter
}
// Exits when cancelBtn is clicked
if (e.getSource() == cancelBtn) {
frmInventorysystem.dispose();
}
}
// Do something with the category
private void doSomething(String selectedEquipment) {
System.out.println(selectedEquipment);
if (selectedEquipment.equals("Weapon")) {
System.out.println("It's a weapon!"); //You can open dialogs or do whatever you need here, not necessarily a print.
} else {
System.out.println("Not a weapon");
}
}
}
Notice that I removed inheritance, I'm not returning back to main and still printing the selected item and checking if it's a weapon or not.
I also exit the application in a safer way.
This is a sample output:
Weapon
It's a weapon!
Armor
Not a weapon
I'm using IntelliJ IDEA, and I have created two GUI forms I want to use as screens for my application.
However I am stuck on how to get my separate main-class to incorporate the two JFrames, and how to control the switch from one JFrame to another. In the code below in the main-class, I'm first initializing an object of both GUI forms, afterwards I'm running the setup-frames 'run' method, which sets the frame visible. This step works.
Now I want an actionListener on my button 'udførButton' which gets the values typed in it's TextFields, so that I can use them as parameters to initialize an instance of the 'Billetautomat' class.
Furthermore, I want the button to close the 'setup' JFrame and to start up the 'gui' JFrame with the gui.run() method.
My intended flow in the program is:
Run 'setup' gui, where I can type in three names and three ints
Run 'gui' (not done designing yet), where I can press multiple buttons to trigger different actions
Run other JFrames for non-specified actions and return to 'gui' (step 2)
Problem is, that the actionListener won't work as I want it to... If I change the code inside the actionListener to billet1Label.setText("HELLO"); it indeed changes the Label's text to display HELLO, but I can't make it work as I intend... I think the problem is that the program doesn't stop and wait for my button click, but just races through the main code...
Do I need some sort of check to see if the button has been pressed, or have you got any expert-advise?
This is my first time working with Swing in Java, so please be patient with me...
The final and the [] on the variables was suggested by IntelliJ....
BenytBilletautomat_GUI.java (main-class)
package automat;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class BenytBilletautomat_GUI {
public static void main(String[] args) {
final int[] pris1 = new int[1];
final int[] pris2 = new int[1];
final int[] pris3 = new int[1];
final String[] navn1 = new String[1];
final String[] navn2 = new String[1];
final String[] navn3 = new String[1];
Setup_GUI setup = new Setup_GUI();
Billetautomat_GUI gui = new Billetautomat_GUI();
setup.udførButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
navn1[0] = setup.getBillet1Text();
pris1[0] = setup.getBilletPris1();
navn2[0] = setup.getBillet1Text();
pris2[0] = setup.getBilletPris1();
navn3[0] = setup.getBillet1Text();
pris3[0] = setup.getBilletPris1();
Billetautomat automat = new Billetautomat(navn1[0],pris1[0],navn2[0],pris2[0],navn3[0],pris3[0]);
setup.frame.setVisible(false);
setup.frame.dispose();
gui.run();
}
});
setup.run();
}
}
Setup_GUI.java (setup gui class)
package automat;
import javax.swing.*;
public class Setup_GUI {
private JPanel mainPanel;
private JLabel gui_title;
private JTextField billet1Text;
private JTextField billet2Text;
private JTextField billet3Text;
private JLabel billet1Label;
private JLabel billet2Label;
private JLabel billet3Label;
private JLabel setupLabel;
private JTextField billetPris1;
private JTextField billetPris2;
private JTextField billetPris3;
public JButton udførButton;
JFrame frame = new JFrame("Setup");
public void run() {
frame.setContentPane(new Setup_GUI().mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public String getBillet1Text() {
return billet1Text.toString();
}
public String getBillet2Text() {
return billet2Text.toString();
}
public String getBillet3Text() {
return billet3Text.toString();
}
public int getBilletPris1() {
return Integer.parseInt(billetPris1.toString());
}
public int getBilletPris2() {
return Integer.parseInt(billetPris2.toString());
}
public int getBilletPris3() {
return Integer.parseInt(billetPris3.toString());
}
}
Billetautomat_GUI.java (gui class, not done yet)
package automat;
import javax.swing.*;
import java.awt.event.ComponentAdapter;
public class Billetautomat_GUI {
JFrame frame = new JFrame("Billetautomat_GUI");
private JPanel mainPanel;
public void run() {
frame.setContentPane(new Billetautomat_GUI().mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
I have a JFrame. in the JFrame is a JDesktopPane, JComboBox, several JLabels, and a JProgressBar. I am facing two challenges:
I want to update/change the text in one of the JLabels in the JFrame by clicking a JButton that is on a JInternalFrame (the button does some calculations).
Upon clicking a JButton that is on another JInternalFrame (the button performs a small task), I want to use the JProgressBar (progressbar is in JFrame) to show the progress of work done.
I use SwingUtilities.invokelater() to perform the tasks done by the buttons.
am using NetBeans as my IDE.
Hard to know what is happening without code, but probably the Event Dispatch Thread (EDT) is being blocked (or terminated?), e.g. by code being called by invokeLater. The EDT is used to update the GUI and should not be used for (slow) non-GUI related calculations. See tutorial The Event Dispatch Thread and subsequent for more details.
Example (without blocking):
import java.awt.*;
import java.awt.event.ActionEvent;
import java.time.LocalTime;
import javax.swing.*;
public class LabelProgress {
public static void main(String[] args) {
LabelProgress main = new LabelProgress();
SwingUtilities.invokeLater(() -> main.showInternal1());
SwingUtilities.invokeLater(() -> main.showInternal2());
}
private JFrame frame;
private JLabel label;
private JDesktopPane desktop;
private JProgressBar bar;
private int progress = 0;
private LabelProgress() {
label = new JLabel("Label: ");
desktop = new JDesktopPane();
bar = new JProgressBar(0, 100);
bar.setStringPainted(true);
frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.add(label, BorderLayout.BEFORE_FIRST_LINE);
frame.add(desktop, BorderLayout.CENTER);
frame.add(bar, BorderLayout.AFTER_LAST_LINE);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(600, 400);
frame.validate();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void showInternal1() {
JButton change = new JButton("Change");
change.addActionListener(this::doChange);
JInternalFrame internal = new JInternalFrame("Change Label");
internal.setLayout(new FlowLayout());
internal.add(change);
internal.setBounds(20, 20, 200, 150);
internal.setVisible(true);
desktop.add(internal);
}
private void showInternal2() {
JButton task = new JButton("Task");
task.addActionListener(this::doTask);
JInternalFrame internal = new JInternalFrame("Small Task");
internal.setLayout(new FlowLayout());
internal.add(task);
internal.setBounds(150, 100, 200, 150);
internal.setVisible(true);
desktop.add(internal);
}
private void doChange(ActionEvent ev) {
// using a SwingWorker:
// for demonstration I used an anonymous class, maybe a own class is better
SwingWorker<LocalTime , Void> worker = new SwingWorker<LocalTime , Void>() {
#Override
protected LocalTime doInBackground() throws Exception {
// not executed on the EDT - just get the current time
LocalTime someCalculation = LocalTime.now();
return someCalculation;
}
#Override
protected void done() {
// executed on EDT
try {
LocalTime resultOfSomeCalculation = get();
label.setText("Label: " + resultOfSomeCalculation.toString());
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
worker.execute();
}
private void doTask(ActionEvent ev) {
// no need to use SwingWorker
Thread thread = new Thread(this::slowTask);
thread.start();
}
private void slowTask() {
// not really that slow, just for demonstration
progress += 10;
if (progress > 100) progress = 100;
// and now switching to the EDT
SwingUtilities.invokeLater(() -> bar.setValue(progress));
}
}
Very new to Java, but I am slowly picking my way through things. So please be kind. I understand most things I've tried so far, and built a version of the following that uses console output, but now I'm trying to make a GUI. I tried the netbeans GUI maker, but it created so much new code that when I tried to pick through it, I got lost. I'm much better at learning by piecing new things together myself, not having an IDE generate a ton of code and then attempt to find where I want to work.
I am trying to build an window that has a list with three choices on the left side, a button in the middle that confirms your choice, and an answer output on the right. Once the button is pressed, the input from the list is read and is converted into a corresponding answer. As of right now, all I get is "We recommend... null" after selecting an option in the list. The button appears to do nothing at the moment.
I have used tutorials, hacked up others' code from online, and referenced a few books, but I'm stuck.
Here is what I have:
package diffguidegui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class DiffGuideGUI extends JPanel implements ListSelectionListener {
private JList resultsTabList;
private DefaultListModel listModel;
private static final String recommendString = "Recommend a Option";
private JButton recommendButton;
private String recommendOutput;
final JLabel output = new JLabel("We recommend..." + recommendOutput);
//build list
public DiffGuideGUI () {
super(new BorderLayout());
listModel = new DefaultListModel();
listModel.addElement("A");
listModel.addElement("B");
//create the list and put it in the scroll pane
resultsTabList = new JList(listModel);
resultsTabList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
resultsTabList.setSelectedIndex(0);
//listener for user input
resultsTabList.addListSelectionListener(this);
resultsTabList.setVisibleRowCount(2);
JScrollPane listScrollPane = new JScrollPane(resultsTabList);
//build the button at the bottom to fire overall behavior
recommendButton = new JButton(recommendString);
recommendButton.setActionCommand(recommendString);
recommendButton.addActionListener(new RecommendListener());
//create a panel that uses Boxlayout for the button
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
buttonPane.add(recommendButton);
//create a panel that uses Boxlayout for the label
JPanel outputPane = new JPanel();
outputPane.setLayout(new BoxLayout(outputPane, BoxLayout.LINE_AXIS));
outputPane.add(output);
add(listScrollPane, BorderLayout.WEST);
add(buttonPane, BorderLayout.CENTER);
add(outputPane, BorderLayout.EAST);
}
//build listener class
class RecommendListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
//build in logic for choice made here
String resultsTabChoice;
resultsTabChoice = (String)resultsTabList.getSelectedValue();
if( resultsTabChoice.equals("A")) {
recommendOutput = "One";}
else {recommendOutput = "Two";}
}
}
public void valueChanged(ListSelectionEvent e) {
if(e.getValueIsAdjusting() == false) {
if(resultsTabList.getSelectedIndex() == -1) {
recommendButton.setEnabled(false);
} else {
recommendButton.setEnabled(true);
}
}
}
//Create GUI and show it
private static void createAndShowGUI() {
JFrame frame = new JFrame("Recommend Window");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//create and set up content pane
JComponent newContentPane = new DiffGuideGUI();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
//display the window
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
The button appears to do nothing at the moment.
It does something. It calculates the value for your recommendOutput varable. But you never output this value.
try the following:
//build listener class
class RecommendListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
//build in logic for choice made here
String resultsTabChoice;
resultsTabChoice = (String)resultsTabList.getSelectedValue();
if( resultsTabChoice.equals("A")) {
recommendOutput = "One";}
else {recommendOutput = "Two";}
System.out.println(recommendOutput); // <-###################
}
}
This should print the value to stdout
To put the value into your label try this instead:
output.setText(recommendOutput);
where do you set the text for the JLabel? It says "We recommend NULL" because recommenedOutput is null when the object is created. I dont see
output.setText("We recommend "+value) anywhere. You probably need output.invalidate() also. Try putting setText(String text)/invalidate() in the RecommendListener.actionPerformed() method.
output.setText("We recommend A");
output.invalidate();
For class I'm working on my first GUI application. It's just a simple image viewer with four buttons: Previous, Next, Stop, Play. Previous and Next work fine, but honestly I don't even know how to begin working on the slideshow part (Play & Stop). I know there's a timer class that would probably be handy for controlling the speed as the images change...but I'm not sure what kind of logic is typically used to cycle through the images. Can anyone point me in the right direction, my brain is a little fried at this point :0
I've included my code below. I'm new to this, so hopefully people won't be too critical of my technique. If it matters, I'm working in eclipse.
here's my code so far:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.TimerTask;
public class ImageGallery extends JFrame
{
private ImageIcon myImage1 = new ImageIcon ("Chrysanthemum.jpg");
private ImageIcon myImage2 = new ImageIcon ("Desert.jpg");
private ImageIcon myImage3 = new ImageIcon ("Jellyfish.jpg");
private ImageIcon myImage4 = new ImageIcon ("Penguins.jpg");
JPanel ImageGallery = new JPanel();
private ImageIcon[] myImages = new ImageIcon[4];
private int curImageIndex=0;
public ImageGallery ()
{
ImageGallery.add(new JLabel (myImage1));
myImages[0]=myImage1;
myImages[1]=myImage2;
myImages[2]=myImage3;
myImages[3]=myImage4;
add(ImageGallery, BorderLayout.NORTH);
JButton PREVIOUS = new JButton ("Previous");
JButton PLAY = new JButton ("Play");
JButton STOP = new JButton ("Stop");
JButton NEXT = new JButton ("Next");
JPanel Menu = new JPanel();
Menu.setLayout(new GridLayout(1,4));
Menu.add(PREVIOUS);
Menu.add(PLAY);
Menu.add(STOP);
Menu.add(NEXT);
add(Menu, BorderLayout.SOUTH);
//register listener
PreviousButtonListener PreviousButton = new PreviousButtonListener ();
PlayButtonListener PlayButton = new PlayButtonListener ();
StopButtonListener StopButton = new StopButtonListener ();
NextButtonListener NextButton = new NextButtonListener ();
//add listeners to corresponding componenets
PREVIOUS.addActionListener(PreviousButton);
PLAY.addActionListener(PlayButton);
STOP.addActionListener(StopButton);
NEXT.addActionListener(NextButton);
}
public static void main (String [] args)
{
ImageGallery frame = new ImageGallery();
frame.setSize(490,430);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
}
class PreviousButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(curImageIndex>0 && curImageIndex <= 3)
{ ImageGallery.remove(0);
curImageIndex=curImageIndex-1;
ImageIcon TheImage= myImages[curImageIndex];
ImageGallery.add(new JLabel (TheImage));
ImageGallery.validate();
ImageGallery.repaint();
}
else
{
ImageGallery.remove(0);
ImageGallery.add(new JLabel (myImage1));
curImageIndex=0;
ImageGallery.validate();
ImageGallery.repaint();
}
}
}
class PlayButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
// *need help here*//
}
}
class StopButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
// *need help here*//
}
}
class NextButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(curImageIndex>=0 && curImageIndex < 3)
{ ImageGallery.remove(0);
curImageIndex = curImageIndex + 1;
ImageIcon TheImage= myImages[curImageIndex];
ImageGallery.add(new JLabel (TheImage));
ImageGallery.validate();
ImageGallery.repaint();
}
else
{
ImageGallery.remove(0);
ImageGallery.add(new JLabel (myImage4));
curImageIndex=3;
ImageGallery.validate();
ImageGallery.repaint();
}
}
}
}
Why complicating simple things,
I think that this is job for CardLayout and for slideshow is there Swing Timer
put images as Icon to the JLabel
This example shows a start/stop button that controls a javax.swing.Timer. Instead of replacing the label each time, just update the label's Icon, as suggested by #mKorbel and shown here.
You need use a thread for the slideshow. You can use a flag in the run method for continue with the show or stop if this flag change, for example, a boolean var. One example you can see in http://java.sun.com/developer/technicalArticles/Threads/applet/.
These are some guidelines that might get you started:
First you will need a separate thread to control the changing images. I suggest you write a class that implements TimerTask. Override the run() method in this class. In this run method you should put the functionality to change the current image being displayed (similar to what you did in the next and previous function).
In the actionPerformed() method for the play button you will need to create an instance of a Timer class and start your timer using the scheduleAtFixedRate(TimerTask task, long delay, long period) method (other methods in this class may be used as well, scheduleAtFixedRate() seem more appropriate though).
For the stop you will then need to add enough functionality to stop the running timer using the cancel() method in the Timer class