Adding images to JButtons - java

I want to add images to my JButtons. I have tried to add the rollover icon command to one of my buttons, but I keep getting an exception even though eclipse doesn't say that there are any errors. I have saved the images in workspace/projectname/src where the class files are, and they are called a and b, and they are JPEG images.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class button extends JFrame {
private static final long serialVersionUID = 1L;
private JButton hi;
private JButton custom;
public button() {
super("The title");
setLayout(new FlowLayout());
hi = new JButton("Hi button");
Icon a = new ImageIcon(getClass().getResource("a.JPEG"));
Icon b = new ImageIcon(getClass().getResource("b.JPEG"));
custom = new JButton("custom", a);
custom.setRolloverIcon(b);
add(custom);
add(hi);
HandlerClass handler = new HandlerClass();
hi.addActionListener(handler);
custom.addActionListener(handler);
}
private class HandlerClass implements ActionListener {
public void actionPerformed(ActionEvent event) {
JOptionPane.showMessageDialog(null, String.format("%s", event.getActionCommand()));
}
}
}
import javax.swing.JFrame;
public class buttonm {
public static void main(String[] args) {
button hello = new button();
hello.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
hello.setSize(350,100);
hello.setVisible(true);
}
}

the Button class
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Button extends JFrame {
private JButton button;
private JPanel p;
public Button() {
super("The title");
p = new JPanel(new BorderLayout());
button = new JButton();
ImageIcon icon = new ImageIcon(getClass().getResource("button2.jpg"));
button.setIcon(icon);
button.setDisabledIcon(icon);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(400, 400);
p.add(button);
add(p);
}
}
your main class
public static void main(String[] args) {
Button btn = new Button();
btn.setVisible(true);
}

Related

Can I communicate between two JFrames WITHOUT using static variables or methods?

Basically, I'm trying to get the JButton in Frame1 to edit the JLabel in Frame2. I know it can work if I set the JLabel and getLabel() method in Frame2 to static, and have the ActionListener reference Frame1 directly, but I want to know if there's a way to do it without using static variables or methods.
Here's the code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Test {
public static void main(String[] args) {
Frame2 f2 = new Frame2();
f2.pack();
f2.setLocation(700, 400);
f2.setVisible(true);
Frame1 f1 = new Frame1(f2);
f1.pack();
f1.setLocation(400, 400);
f1.setVisible(true);
}
}
class Frame1 extends JFrame {
JButton button;
public Frame1(JFrame f) {
super("Frame 1");
setDefaultCloseOperation(EXIT_ON_CLOSE);
button = new JButton("Button");
add(button);
button.addActionListener(new Listener(f.getLabel()));
}
}
class Frame2 extends JFrame {
JLabel label;
public Frame2() {
super("Frame 2");
setDefaultCloseOperation(EXIT_ON_CLOSE);
label = new JLabel("hello");
add(label);
}
public JLabel getLabel() {
return label;
}
}
class Listener implements ActionListener {
private JLabel lab;
public Listener(JLabel lab) {
this.lab = lab;
}
public void actionPerformed(ActionEvent e) {
lab.setText("nice");
}
}
Any suggestions? Thanks!
EDIT: Here's a compilable version of the code -- label and getLabel() are static, and the ActionListener references JFrame1 directly when it's called. My goal is to have no static variables or methods (outside of main).
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Test {
public static void main(String[] args) {
Frame2 f2 = new Frame2();
f2.pack();
f2.setLocation(700, 400);
f2.setVisible(true);
Frame1 f1 = new Frame1(f2);
f1.pack();
f1.setLocation(400, 400);
f1.setVisible(true);
}
}
class Frame1 extends JFrame {
JButton button;
public Frame1(JFrame f) {
super("Frame 1");
setDefaultCloseOperation(EXIT_ON_CLOSE);
button = new JButton("Button");
add(button);
button.addActionListener(new Listener(Frame2.getLabel()));
}
}
class Frame2 extends JFrame {
static JLabel label;
public Frame2() {
super("Frame 2");
setDefaultCloseOperation(EXIT_ON_CLOSE);
label = new JLabel("hello");
add(label);
}
public static JLabel getLabel() {
return label;
}
}
class Listener implements ActionListener {
private JLabel lab;
public Listener(JLabel lab) {
this.lab = lab;
}
public void actionPerformed(ActionEvent e) {
lab.setText("nice");
}
}
Oracle has a really nifty Swing tutorial. I think your studying the tutorial would be a really good idea.
I had to make a bunch of changes to your code to get it to execute.
The main change I made was to keep the reference to the JLabel in the Frame2 class. I passed an instance of Frame2 to the Listener class. Just like I did yesterday with your previous question.
Here's the code. Take the time to study what I did before you ask another question tomorrow.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class DoubleJFrameTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Frame2 f2 = new Frame2();
f2.pack();
f2.setLocation(700, 400);
f2.setVisible(true);
Frame1 f1 = new Frame1(f2);
f1.pack();
f1.setLocation(400, 400);
f1.setVisible(true);
}
});
}
}
class Frame1 extends JFrame {
private static final long serialVersionUID = 1L;
private JButton button;
public Frame1(Frame2 f) {
super("Frame 1");
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel panel = new JPanel(new BorderLayout());
button = new JButton("Button");
button.addActionListener(new Listener(f));
panel.add(button, BorderLayout.CENTER);
add(panel);
}
}
class Frame2 extends JFrame {
private static final long serialVersionUID = 1L;
private JLabel label;
public Frame2() {
super("Frame 2");
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel panel = new JPanel(new BorderLayout());
label = new JLabel("hello");
panel.add(label, BorderLayout.CENTER);
add(panel);
}
public void setLabelText(String text) {
label.setText(text);;
}
}
class Listener implements ActionListener {
private Frame2 frame;
public Listener(Frame2 frame) {
this.frame = frame;
}
#Override
public void actionPerformed(ActionEvent e) {
frame.setLabelText("nice");
}
}

Using the original instance of a JFrame

I have two Java classes; mcveF1 and mcveF2. The code below disables when run opens a JFrame with a singular JButton on it. This button opens a second JFrame and disables the first. Similarly this frame has a singular JButton on it. This button should close the second frame and re-enable the first frame. However an exception is thrown, java.lang.NullPointerException. I believe this is because I am creating a new instance of mcveF1 instead of using the current one. I am unaware of how to fix this and would appreciate any help in fixing it.
mcveF1
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import net.miginfocom.swing.MigLayout;
public class mcveF1
{
public JFrame myMainWindow = new JFrame("Frame 1");
JPanel panel2 = new JPanel();
//Variables and Components
JButton openFrame = new JButton("Open new frame");
public void runGUI()
{
myMainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myMainWindow.setLayout(new GridLayout(1,1));
createSortTestPanel();
myMainWindow.getContentPane().add(panel2);
myMainWindow.setVisible(true);
myMainWindow.pack();
myMainWindow.setMinimumSize(new Dimension(myMainWindow.getBounds().getSize()));
myMainWindow.setLocationRelativeTo(null);
}
public void createSortTestPanel()
{
MigLayout layout = new MigLayout("", "[grow]");
panel2.setLayout(layout);
openFrame.addActionListener(new buttonAction());
panel2.add(openFrame);
}
public static void main(String[] args)
{
mcveF1 f1 = new mcveF1();
f1.runGUI();
}
class buttonAction implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
myMainWindow.setEnabled(false);
mcveF2 f2 = new mcveF2();
f2.runGUI();
}
}
}
mcveF2
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import net.miginfocom.swing.MigLayout;
public class mcveF2
{
JFrame myMainWindow = new JFrame("Frame 2");
JPanel panel2 = new JPanel();
//Variables and Components
JButton closeFrame = new JButton("Close");
mcveF1 f1;
public void runGUI()
{
myMainWindow.setLayout(new GridLayout(1,1));
createSortTestPanel();
myMainWindow.getContentPane().add(panel2);
myMainWindow.setVisible(true);
myMainWindow.pack();
myMainWindow.setMinimumSize(new Dimension(myMainWindow.getBounds().getSize()));
myMainWindow.setLocationRelativeTo(null);
}
public void createSortTestPanel()
{
MigLayout layout = new MigLayout("", "[grow]");
panel2.setLayout(layout);
closeFrame.addActionListener(new buttonAction());
panel2.add(closeFrame);
}
public static void main(String[] args)
{
mcveF2 f2 = new mcveF2();
f2.runGUI();
}
class buttonAction implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
myMainWindow.dispose();
f1.myMainWindow.setEnabled(true);
}
}
}
The null pointer exception is shown in this picture as per PM77-1's request.
Create a constructor in your class mcveF2
public class mcveF2() {
public mcveF2(mcveF1 f1) {
this.f1 = f1;
}
Then pass instance of mcveF1 to this constructor in button action listener.
class buttonAction implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
myMainWindow.setEnabled(false);
mcveF2 f2 = new mcveF2(mcveF1.this);
f2.runGUI();
}
}

Resize JOptionPane Dialog and lines in a dialogs

My program is supposed to have the basic code examples in java and to do that I need help to have the dialogues where I can write have the code preloaded but I can't add spaces in the dialogues and resize them. Please help!
Main Class:
public class JavaHelperTester{
public static void main(String[] args){
JavaWindow display = new JavaWindow();
JavaHelper j = new JavaHelper();
display.addPanel(j);
display.showFrame();
}
}
Method Class:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class JavaHelper extends JPanel implements ActionListener{
JButton print = new JButton("Print Statements");
JButton classes = new JButton("Classes");
JButton varibles = new JButton("Assiging variables");
JButton signs = new JButton("Sign meanings");
JButton typesv = new JButton("Different Types of variables");
JButton scanners = new JButton("Scanner");
JButton loops = new JButton("Loops");
JButton ifstatements = new JButton("If statements");
JButton graphics = new JButton("Graphics");
JButton objects = new JButton("Making an oject");
JButton importstatments = new JButton("Import Statements");
JButton integers = new JButton("Different types of integers");
JButton methods = new JButton("Scanner methods");
JButton math = new JButton("Math in java");
JButton creation = new JButton("Method creation");
JButton arrays = new JButton("Arrays");
JButton jframe = new JButton("JFrame");
JButton stringtokenizer = new JButton("String Tokenizer");
JButton extending = new JButton("Class extending");
JButton fileio = new JButton("File I.O.");
JButton quit = new JButton("Quit");
public JavaHelper(){
setPreferredSize(new Dimension(500,350));
setBackground(Color.gray);
this.add(print);
print.addActionListener(this);
this.add(classes);
classes.addActionListener(this);
this.add(varibles);
varibles.addActionListener(this);
this.add(signs);
signs.addActionListener(this);
this.add(typesv);
typesv.addActionListener(this);
this.add(scanners);
scanners.addActionListener(this);
this.add(loops);
loops.addActionListener(this);
this.add(ifstatements);
ifstatements.addActionListener(this);
this.add(graphics);
graphics.addActionListener(this);
this.add(objects);
objects.addActionListener(this);
this.add(importstatments);
importstatments.addActionListener(this);
this.add(integers);
integers.addActionListener(this);
this.add(methods);
methods.addActionListener(this);
this.add(math);
math.addActionListener(this);
this.add(creation);
creation.addActionListener(this);
this.add(arrays);
arrays.addActionListener(this);
this.add(jframe);
jframe.addActionListener(this);
this.add(stringtokenizer);
stringtokenizer.addActionListener(this);
this.add(fileio);
fileio.addActionListener(this);
this.add(quit);
quit.addActionListener(this);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == print){
JOptionPane.showMessageDialog (null, "System.out.println(); and System.out.print();", "Print Statements", JOptionPane.INFORMATION_MESSAGE);
}
if(e.getSource() == classes){
JOptionPane.showMessageDialog (null, "Main class : public class ClassNameTester{ // public static void main(String[] args){, Other Classes : public class ClassName", "Classes", JOptionPane.INFORMATION_MESSAGE);
}
if(e.getSource() == quit){
System.exit(0);
}
}
private void dialogSize(){
}
}
JavaWindow:
import java.awt.*;
import javax.swing.*;
public class JavaWindow extends JFrame{
private Container c;
public JavaWindow(){
super("Java Helper");
c = this.getContentPane();
}
public void addPanel(JPanel p){
c.add(p);
}
public void showFrame(){
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
I made changes to clean up the Java Helper GUI and to allow you to format the information on the JOptionPane dialogs.
Here's the Java Helper GUI.
And here's the Classes JOptionPane.
I modified your JavaHelperTester class to include a call to the SwingUtilities invokeLater method. This method puts the creation and use of your Swing components on the Event Dispatch thread (EDT). A Swing GUI must start with a call to the SwingUtilities invokeLater method.
I also formatted all of your code and resolved the imports.
package com.ggl.java.helper;
import javax.swing.SwingUtilities;
public class JavaHelperTester {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
JavaWindow display = new JavaWindow();
JavaHelper j = new JavaHelper();
display.addPanel(j);
display.showFrame();
}
};
SwingUtilities.invokeLater(runnable);
}
}
Here's your JavaWindow class.
package com.ggl.java.helper;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class JavaWindow extends JFrame {
private static final long serialVersionUID = 6535974227396542181L;
private Container c;
public JavaWindow() {
super("Java Helper");
c = this.getContentPane();
}
public void addPanel(JPanel p) {
c.add(p);
}
public void showFrame() {
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
And here's your JavaHelper class. I made the changes to your action listener to allow you to define the text as an HTML string. You may only use HTML 3.2 commands.
I also changed your button panel to use the GridLayout. The grid layout makes your buttons look neater and makes it easier for the user to select a JButton.
package com.ggl.java.helper;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class JavaHelper extends JPanel implements ActionListener {
private static final long serialVersionUID = -3150356430465932424L;
JButton print = new JButton("Print Statements");
JButton classes = new JButton("Classes");
JButton varibles = new JButton("Assiging variables");
JButton signs = new JButton("Sign meanings");
JButton typesv = new JButton("Different Types of variables");
JButton scanners = new JButton("Scanner");
JButton loops = new JButton("Loops");
JButton ifstatements = new JButton("If statements");
JButton graphics = new JButton("Graphics");
JButton objects = new JButton("Making an oject");
JButton importstatments = new JButton("Import Statements");
JButton integers = new JButton("Different types of integers");
JButton methods = new JButton("Scanner methods");
JButton math = new JButton("Math in java");
JButton creation = new JButton("Method creation");
JButton arrays = new JButton("Arrays");
JButton jframe = new JButton("JFrame");
JButton stringtokenizer = new JButton("String Tokenizer");
JButton extending = new JButton("Class extending");
JButton fileio = new JButton("File I.O.");
JButton quit = new JButton("Quit");
public JavaHelper() {
this.setLayout(new GridLayout(0, 2));
setBackground(Color.gray);
this.add(print);
print.addActionListener(this);
this.add(classes);
classes.addActionListener(this);
this.add(varibles);
varibles.addActionListener(this);
this.add(signs);
signs.addActionListener(this);
this.add(typesv);
typesv.addActionListener(this);
this.add(scanners);
scanners.addActionListener(this);
this.add(loops);
loops.addActionListener(this);
this.add(ifstatements);
ifstatements.addActionListener(this);
this.add(graphics);
graphics.addActionListener(this);
this.add(objects);
objects.addActionListener(this);
this.add(importstatments);
importstatments.addActionListener(this);
this.add(integers);
integers.addActionListener(this);
this.add(methods);
methods.addActionListener(this);
this.add(math);
math.addActionListener(this);
this.add(creation);
creation.addActionListener(this);
this.add(arrays);
arrays.addActionListener(this);
this.add(jframe);
jframe.addActionListener(this);
this.add(stringtokenizer);
stringtokenizer.addActionListener(this);
this.add(fileio);
fileio.addActionListener(this);
this.add(quit);
quit.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == print) {
String title = ((JButton) e.getSource()).getText();
JLabel label = new JLabel(createPrintText());
JOptionPane.showMessageDialog(this, label, title,
JOptionPane.INFORMATION_MESSAGE);
}
if (e.getSource() == classes) {
String title = ((JButton) e.getSource()).getText();
JLabel label = new JLabel(createClassesText());
JOptionPane.showMessageDialog(this, label, title,
JOptionPane.INFORMATION_MESSAGE);
}
if (e.getSource() == quit) {
System.exit(0);
}
}
private String createPrintText() {
StringBuilder builder = new StringBuilder();
builder.append("<html><pre><code>");
builder.append("System.out.print()");
builder.append("<br>");
builder.append("System.out.println()");
builder.append("</code></pre>");
return builder.toString();
}
private String createClassesText() {
StringBuilder builder = new StringBuilder();
builder.append("<html><pre><code>");
builder.append("Main class : public class ClassNameTester { <br>");
builder.append(" public static void main(String[] args) { <br>");
builder.append(" } <br>");
builder.append("} <br><br>");
builder.append("Other Classes : public class ClassName { <br>");
builder.append("}");
builder.append("</code></pre>");
return builder.toString();
}
}

When i change JPanel in JFrame i lose focus

As in subject: When i change JPanel in JFrame i lose focus. I have class Game, Action, Button.
I have also class Stage when drawing the game stage.
At first in Game i have Action panel, which contains buttons, after push button NewGame i change panel in Game to Stage, but i cant control ship, which i am flying.
How to fix it or how to do it different?
Action.java
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.io.FileNotFoundException;
import javax.swing.*;
#SuppressWarnings("serial")
public class Action extends JPanel {
public static final int xxx = 800;
public static final int yyy = 600;
private Button buttonPanel;
public Action(Game game) {
setLayout(new FlowLayout());
setPreferredSize(new Dimension(xxx, yyy));
buttonPanel = new Button(game);
add(buttonPanel);
setVisible(true);
}
}
Button.java
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class Button extends JPanel implements ActionListener{
public static final int xxx = 100;
public static final int yyy = 300;
private JButton NewGame;
private JButton Scores;
private JButton Exit;
private Game game;
public Button(Game game) {
NewGame = new JButton("NewGame");
Scores = new JButton("Scores");
Exit = new JButton("Wyjście");
this.game=game;
NewGame.addActionListener(this);
setLayout(new FlowLayout());
setPreferredSize(new Dimension(xxx, yyy));
add(NewGame);
add(Scores);
add(Exit);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(source == NewGame){
game.setPanel("stage");
}
;
}
}
Game.java
#SuppressWarnings("serial")
public class Game extends JFrame {
private Action menu;
private static Stage stage = new Stage();
public Game() {
super("Lunar Lander");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(Stage.WIDTH,Stage.HEIGHT);
setMinimumSize(new Dimension(400,300));
this.setResizable(true);
//stage = new Stage(0);
menu = new Action(this);
add(menu);
pack();
//setPanel("stage");
setVisible(true);
}
public void setPanel(String panel) {
if (panel=="stage") {
remove(menu);
add(stage);
pack();
} else if (panel=="menu") {
remove(stage);
add(menu);
pack();
}
}
public static void main(String[] args) throws FileNotFoundException {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Game();
}
});
Thread a = new Thread(stage);
a.start();
while (a.isAlive()) {}
Scores scores = new Scores();
scores.changeScores(stage.getPlayer().getName(),stage.getPlayer().getPoints());
}
}
but i cant control ship, which i am flying.
KeyEvents are only passed to the component with focus. When you swap panels the panel no longer has focus.
Don't use a KeyListener. Instead you should be using Key Bindings. Then you can handle the event even if the component doesn't have focus.
See Motion Using the Keyboard for more information and working examples.
Edit:
Don't use "==" for String comparisons. Use the String.equals(...) method.
Variable names should NOT start with an upper case character.

how to auto change image in java swing?

Hi i am creating a java desktop application where i want to show image and i want that all image should change in every 5 sec automatically i do not know how to do this
here is my code
public class ImageGallery extends JFrame
{
private ImageIcon myImage1 = new ImageIcon ("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\yellow.png");
private ImageIcon myImage2 = new ImageIcon ("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\d.jpg");
private ImageIcon myImage3 = new ImageIcon ("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\e.jpg");
private ImageIcon myImage4 = new ImageIcon ("E:\\SOFTWARE\\TrainPIS\\res\\drawable\f.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 NEXT = new JButton ("Next");
JPanel Menu = new JPanel();
Menu.setLayout(new GridLayout(1,4));
Menu.add(PREVIOUS);
Menu.add(NEXT);
add(Menu, BorderLayout.SOUTH);
}
How can i achieve this?
Thanks in advance
In this example, a List<JLabel> holds each image selected from a List<Icon>. At each step of a javax.swing.Timer, the list of images is shuffled, and each image is assigned to a label.
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
/**
* #see http://stackoverflow.com/a/22423511/230513
* #see http://stackoverflow.com/a/12228640/230513
*/
public class ImageShuffle extends JPanel {
private List<Icon> list = new ArrayList<Icon>();
private List<JLabel> labels = new ArrayList<JLabel>();
private Timer timer = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
update();
}
});
public ImageShuffle() {
this.setLayout(new GridLayout(1, 0));
list.add(UIManager.getIcon("OptionPane.errorIcon"));
list.add(UIManager.getIcon("OptionPane.informationIcon"));
list.add(UIManager.getIcon("OptionPane.warningIcon"));
list.add(UIManager.getIcon("OptionPane.questionIcon"));
for (Icon icon : list) {
JLabel label = new JLabel(icon);
labels.add(label);
this.add(label);
}
timer.start();
}
private void update() {
Collections.shuffle(list);
int index = 0;
for (JLabel label : labels) {
label.setIcon(list.get(index++));
}
}
private void display() {
JFrame f = new JFrame("ImageShuffle");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new ImageShuffle().display();
}
});
}
}
one way of achieving your goal is setting a swing.Timer to notify its action listeners every 5 seconds, set your class to be the listener for the timer and implement the actionListener interface by having an actionPerformed method which will change all images using their setImage method. the code should look like this:
public class ImageGallery extends JFrame implements ActionListener {
Timer timer;
public ImageGallery() {
timer = new Timer(5000, this);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == timer) {
for (int i=0; i<vectorOfImages.size(); i++) {
vectorOfImages.get(i).setImage(AnotherImage);
}
}
}
}

Categories