I am still new to using Swing and creating GUIs in Java. I was working on a simple test code where the color of a button changes to a random color when it is pressed. Although it works, every time I press the button, it minimizes the previous window and opens a new one and they keep piling up. How will I make it so that this does not happen? Does this occur because I am creating an object in the actionPerformed method? The reason why I have made an object there is to link the Swing class with the separate Action class I have made in order to manipulate the button variable.
Therefore, my two questions are:
How can I prevent multiple windows from appearing and instead have them replace each other?
Is there a way to utilize ActionListener within the same class and would it make things easier?
Any help is greatly appreciated!
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.*;
public class Swing extends JFrame{
private JFrame f;
private JLabel l;
private JButton b;
private JPanel p;
public Swing(){
test();
}
//*
public JFrame getJFrame(){
return f;
}
public JLabel getJLabel(){
return l;
}
public JButton getJButton(){
return b;
}
public JPanel getJPanel(){
return p;
}
//*
public void test(){
// Frame Setup
f = new JFrame("Frame");
f.setVisible(true);
f.setSize(500, 500);
f.setResizable(true);
f.setDefaultCloseOperation(EXIT_ON_CLOSE);
//
// Panel Setup
p = new JPanel();
p.setVisible(true);
//
// Other
b = new JButton("Button");
l = new JLabel("Label");
b.addActionListener(new Action());
//
// Additions
p.add(b);
p.add(l);
f.add(p); // ***
//
}
public static void main(String[] args){
Swing swing = new Swing();
swing.test();
}
}
final class Action implements ActionListener{
public void actionPerformed(ActionEvent e){
Swing swingObject = new Swing(); //
JButton button = swingObject.getJButton(); //
button.setBackground(randomColor());
}
public Color randomColor(){
Random rn = new Random();
ArrayList<Color> color = new ArrayList<Color>();
color.add(Color.BLUE);
color.add(Color.GREEN);
color.add(Color.RED);
color.add(Color.YELLOW);
color.add(Color.PINK);
color.add(Color.CYAN);
color.add(Color.ORANGE);
color.add(Color.MAGENTA);
int s = color.size();
int random = rn.nextInt(s);
return color.get(random);
}
}
From your listener, you're executing
Swing swingObject = new Swing();
This does what it should do: create a new Swing JFrame. You don't want a new JFrame, so don't call its constructor. From the listener, simply get the button that fired the event, and change its color:
JButton button = (JButton) e.getSource();
button.setBackground(randomColor());
You could also pass the button to modify when creating the listener:
class Action implements ActionListener{
private JButton buttonToUpdate;
public Action(JButton buttonToUpdate) {
this.buttonToUpdate = buttonToUpdate;
}
public void actionPerformed(ActionEvent e){
buttonToUpdate.setBackground(randomColor());
}
}
And, to create it:
b = new JButton("Button");
b.addActionListener(new Action(b));
Related
Hi guyz i have a prob in writing java code for my project as am unable to tackle that, i want my "Categories" button to perform action like it should show bread class in it but am unable to inherit it and put a pic on it so can anyone here just tell me whats the problem in it..
here is the code:
JButton b1 = new JButton("Categories");
b1.setSize(120,25);
b1.setLocation(130,650);
b1.setBackground(Color.LIGHT_GRAY) ;
b1.addActionListener(new AL());
f.add(b1);
public class AL implements ActionListener{
public void actionPerformed(ActionEvent ae){
JFrame f3 = new JFrame("Delicious Bakery");
f3.setVisible(true);
f3.setSize(400,200);
f3.add(Bread);
Now here is the Bread class:
public class Bread extends AL implements ActionListener
{
Bread()
{
ImageIcon BreadImage = new ImageIcon("C:\\Users\\Baba\\Downloads\\Documents\\Bread1.jpg");
JButton Bread = new JButton("Bread",BreadImage);
Bread.setSize(128,96);
}}
You appear to be making several basic mistakes including what looks to be trying to add a class that implements ActionListener to your GUI as if it were a button, but it's not. This suggests that you'd greatly benefit from first reading through the JButton Tutorial and the ActionListener Tutorial.
Note that if this were my project, I'd use AbstractActions a concept that is sort of like an "ActionListener on steroids". You would set your JButton with this Action and in doing so, gain the button its name text, its icon and its ActionListener behavior.
Some notes on your code:
JButton b1 = new JButton("Categories"); // (1)
b1.setSize(120,25); // (2)
b1.setLocation(130,650); // (3)
b1.setBackground(Color.LIGHT_GRAY) ;
b1.addActionListener(new AL()); // (4)
f.add(b1); // (5)
You here create a JButton with a String name text
Here you try to set absolute size, something that we don't recommend as doing this, and using null layouts leads to rigid hard to improve and debug programs
Same for setting locations
You appear to be adding an ActionListener OK
And then add your button to a container (the JFrame perhaps)?
public class AL implements ActionListener{ // (6)
public void actionPerformed(ActionEvent ae){
JFrame f3 = new JFrame("Delicious Bakery"); // (7)
f3.setVisible(true); // (8)
f3.setSize(400,200); // (9)
f3.add(Bread); // (10)
OK, so the AL class implements ActionListener and has an actionPerformed method, so far so good
OK, so inside it you create a new JFrame, a bit unusual since most GUI's have only one JFrame
You're calling setVisible(true) on the JFrame before adding components -- not code, since this may sometimes not allow the JFrame to fully render components added after this setVisible was called
Same notes as previous about setting sizes
Now you add Bread to the JFrame. But Bread looks to not be a component but rather only an ActionListener. This line should not compile.
public class Bread extends AL implements ActionListener { // (11)
Bread() {
// (12)
ImageIcon BreadImage = new ImageIcon("C:\\Users\\Baba\\Downloads\\Documents\\Bread1.jpg");
JButton Bread = new JButton("Bread",BreadImage); // (13)
Bread.setSize(128,96); // (14)
}
}
Your Bread class extends AL but also implements ActionListener which is redundant since AL already implements ActionListener.
You are creating an image icon using a file and an absolute path, a slight no-no. Better to use resources and absolute paths
OK you create a new JButton, but you give it the same name as the non-JButton class -- very confusing. Simply don't do this. Ever. Name your fields with unique names, and obey Java naming issues.
Same issue regarding setting sizes.
For example:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
public class TestBread extends JPanel {
// String to url for bread image
private static final String BREAD_IMG_PATH = "http://findicons.com/files/icons/339/"
+ "coffee_break/128/sliced_bread.png";
// preferred size of jpanel
private static final int PREF_W = 400;
private static final int PREF_H = 300;
private BreadAction breadAction; // our abstract action
private JButton breadButton; // our jbutton
public TestBread() {
Icon breadIcon = null;
try {
// get image and put into Icon
URL breadUrl = new URL(BREAD_IMG_PATH);
BufferedImage breadImg = ImageIO.read(breadUrl);
breadIcon = new ImageIcon(breadImg);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
breadAction = new BreadAction("Bread", KeyEvent.VK_B, breadIcon); // create Action
breadButton = new JButton(breadAction); // create button with Action
breadButton.setVerticalTextPosition(AbstractButton.BOTTOM); // position text
breadButton.setHorizontalTextPosition(SwingConstants.CENTER);
add(breadButton);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
TestBread mainPanel = new TestBread();
JFrame frame = new JFrame("TestBread");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
Our AbstractAction or "super" ActionListener
#SuppressWarnings("serial")
class BreadAction extends AbstractAction {
public BreadAction(String name, int mnemonic, Icon icon) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
putValue(LARGE_ICON_KEY, icon);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("bread pressed");
}
}
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);
}
}
So I have 1 class, with a radio button and 1 class, that will create an applet depending on the outcome of the Radio Button. I don't know how to make the graphics run depending on an if/else statement. All help will be greatly appreciated.
Radio Button Class:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RadioButton extends JPanel {
static JFrame frame;
JLabel pic;
RadioListener myListener = null;
protected JRadioButton displacement;
protected JRadioButton accel;
protected JRadioButton time;
public RadioButton() {
// Create the radio buttons
displacement = new JRadioButton("Displacement");
displacement.setMnemonic(KeyEvent.VK_N);
displacement.setSelected(true);
//Displacement Button, set to automatically be clicked
accel = new JRadioButton("Acceleration");
accel.setMnemonic(KeyEvent.VK_A);
accel.setActionCommand("acceleration");
//Acceleration Button
time = new JRadioButton("Change in time");
time.setMnemonic(KeyEvent.VK_S);
time.setActionCommand("deltaT");
//The change in time button
// Creates the group of buttons
ButtonGroup group = new ButtonGroup();
group.add(displacement);
group.add(accel);
group.add(time);
myListener = new RadioListener();
displacement.addActionListener(myListener);
accel.addActionListener(myListener);
time.addActionListener(myListener);
// Set up the picture label
pic = new JLabel(new ImageIcon(""+"numbers" + ".jpg")); //Set the Default Image
pic.setPreferredSize(new Dimension(177, 122));
// Puts the radio buttons down
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 1));
panel.add(displacement);
panel.add(accel);
panel.add(time);
setLayout(new BorderLayout());
add(panel, BorderLayout.WEST);
add(pic, BorderLayout.CENTER);
setBorder(BorderFactory.createEmptyBorder(40,40,40,40));
}
//Listening to the buttons
class RadioListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
pic.setIcon(new ImageIcon(""+e.getActionCommand()
+ ".jpg"));
}
}
public static void main(String s[]) {
frame = new JFrame("∆x = Vavg * time");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
});
frame.getContentPane().add(new RadioButton(), BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
If/Else Statements class:
import java.lang.Object;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.*;
public class RadioButtonMain extends RadioButton {
public static void main(String [ ] args) {
new RadioButtonMain().doMain();
}
public void doMain() {
if ( displacement.isSelected()) {
//option 1 for applet
}
if ( accel.isSelected()) {
//Option 2 for applet
}
else {
//Option 3 for applet
}
}
}
How would I get the graphics to run based on whether or not the variables accel and displacement are pressed? Thanks.
Remember, a GUI is an event driven environment, things don't run within a linear manner. Instead of trying run a method yourself, you need to use a callback or listener of some kind which will tell you when the state of the program/buttons change...
When the JRadioButton actionPerformed event is raised, you need to call another method which provides information about what has occurred. You can then override these methods in your RadioButtonMain class and take action when they are called
This is very similar to an Observer Pattern
Currently working on a school project in which I am making a wheel of fortune replica in Java. I have a panel of JButtons within a class called buttonPanel, and a separate class, wheelGUI, which acts as the class that the program runs through. What I want to happen is when the JButton spin is pressed on the GUI, it assigns a random value from String[] wheelStuff to a String, spinValue,using the method spinWheel which acts as the parameter for the JTextField results, and then displays that random value on the Cyan box in the GUI. In non-technical terms, when the button spin is pressed, display a random value in the Cyan box which acts as the current players' spin value. Here is the code for the class buttonPanel
package wheelOfFortune;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class buttonPanels extends JPanel
implements ActionListener
{
private JButton spin, solve, buyVowel, guess, reset, end, cont;
Color yungMoney = new Color(0, 180, 100);
private static String[] wheelStuff = new String[]{"Bankrupt", "Lose a Turn", "$5000", "$600", "$500", "$300", "$800", "$550", "$400", "$900", "$350", "$450", "$700"};
public buttonPanels()
{
setBackground(yungMoney);
spin = new JButton("Spin!");
spin.addActionListener(this);
solve = new JButton("Solve the Puzzle");
solve.addActionListener(this);
buyVowel = new JButton("Buy a Vowel");
buyVowel.addActionListener(this);
guess = new JButton("Guess a Letter");
guess.addActionListener(this);
reset = new JButton("Reset");
reset.addActionListener(this);
cont = new JButton("Continue");
cont.addActionListener(this);
JPanel buttonPanel = new JPanel(new GridLayout(3, 1, 5, 5));
buttonPanel.setPreferredSize(new Dimension(300,380));
buttonPanel.setBackground(yungMoney);
buttonPanel.add(spin);
buttonPanel.add(guess);
buttonPanel.add(buyVowel);
buttonPanel.add(solve);
buttonPanel.add(cont);
buttonPanel.add(reset);
add(buttonPanel);
}
public void actionPerformed(ActionEvent e)
{
JButton b = (JButton)e.getSource();
b.addActionListener(this);
if(b==spin)
{
wheelGUI.spinWheel(wheelStuff);
}
repaint();
}
}
And here is the code for the main class, wheelGUI
package wheelOfFortune;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.util.Random;
import javax.swing.*;
public class wheelGUI extends JFrame implements ActionListener {
private playerPlate player1, player2, player3;
Color yungMoney = new Color(0, 180, 100);
private String fileName = "M:/wheelOfFortune/src/wheelOfFortune/img/wheel1.png";
private String cat;
private static String spinValue = "";
private static String[] wheelStuff = new String[]{"Bankrupt", "Lose a Turn", "$5000", "$600", "$500", "$300", "$800", "$550", "$400", "$900", "$350", "$450", "$700"};
private static JTextField results;
public wheelGUI() {
super("Butt Stuff!");
ImageIcon i = new ImageIcon(fileName);
JLabel picture = new JLabel(i);
player1 = new playerPlate("Garrett", Color.RED);
player2 = new playerPlate("Jonny", Color.YELLOW);
player3 = new playerPlate("Robert", Color.BLUE);
buttonPanels buttons = new buttonPanels();
letterBoard letters = new letterBoard();
catBox category = new catBox(cat);
inputField input = new inputField();
Box wall = Box.createHorizontalBox();
wall.add(player1);
wall.add(Box.createHorizontalStrut(5));
wall.add(player2);
wall.add(Box.createHorizontalStrut(5));
wall.add(player3);
JPanel result = new JPanel();
result.setBackground(yungMoney);
JTextField results = new JTextField(spinValue);
results.setBackground(Color.CYAN);
results.setHorizontalAlignment(JTextField.CENTER);
results.setBorder(BorderFactory.createLineBorder(Color.BLACK,2));
results.setPreferredSize(new Dimension(150,100));
results.setFont(new Font("Impact", Font.PLAIN, 28));
results.setEditable(false);
result.add(results);
Box catInput = Box.createVerticalBox();
catInput.add(category);
catInput.add(Box.createVerticalStrut(50));
catInput.add(result);
catInput.add(Box.createVerticalStrut(100));
catInput.add(input);
Container c = getContentPane();
c.setBackground(yungMoney);
c.add(buttons, BorderLayout.EAST);
c.add(wall, BorderLayout.SOUTH);
c.add(letters, BorderLayout.NORTH);
c.add(picture, BorderLayout.WEST);
c.add(catInput, BorderLayout.CENTER);
}
public static String spinWheel(String[] wheelStuff)
{
Random rnd = new Random();
wheelStuff[rnd.nextInt(wheelStuff.length)] = spinValue;
return spinValue;
}
public static void main(String[] args) {
wheelGUI window = new wheelGUI();
window.setBounds(50, 50, 1024, 768);
window.setDefaultCloseOperation(EXIT_ON_CLOSE);
window.setResizable(false);
window.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
// logic for any additional panels. other logics should be in individual
// classes.
}
}
Thanks for your help! Note: all of the code in wheelGUI that isn't related to something previously stated can be ignored, it's from various other classes.
The use of static fields in this manner is not recommended.
Instead, the buttonsPanel should be taking a reference of the wheelGUI. This will allow the buttonsPanel to call the required methods on the wheelGUI when it needs to.
A better solution would be to use a model which can sit between the two UIs and model the logic, firing events as parts of the model change
Your primary problem is your shadowing the results textfield. That is, you've declared and class level, static field and then redeclared it within your constructor
Change the following line in your wheelGUI constructor
JTextField results = new JTextField(spinValue);
To
results = new JTextField(spinValue);
This will mean when you set the text on the results field, you will be setting the value of the correct instance of the field.
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