I am trying to add and actionListener to a JPanel it's self but keep getting the error"cannot find symbol". I was just wondering if it is possible to do this as I want to be able to click on the panel and make the colour change. Any help would be appreciated.
Here is what i have so far.
import java.awt.*;
import javax.swing.*;
import javax.swing.JPanel.*;
import java.awt.Color.*;
import java.awt.event.*;
/**
* Write a description of class SimpleFrame here.
*
* #author OFJ2
* #version
*/
public class Game extends JFrame
implements ActionListener
{
private final int ROWS = 5;
private final int COLUMS = 2;
private final int GAP = 2;
private final int SIZE = ROWS * COLUMS;
private int x;
private JPanel leftPanel = new JPanel(new GridLayout(ROWS,COLUMS, GAP,GAP));
private JPanel [] gridPanel = new JPanel[SIZE];
private JPanel middlePanel = new JPanel();
private JPanel rightPanel = new JPanel();
private Color col1 = Color.GREEN;
private Color col2 = Color.YELLOW;
private Color tempColor;
public Game()
{
super("Chasing Bombs OFJ2");
setSize(200,200);
setVisible(true);
makeFrame();
}
public void makeFrame()
{
Container contentPane = getContentPane();
contentPane.setLayout(new GridLayout());
leftPanel.setLayout(new GridLayout(ROWS, COLUMS));
//JLabel label2 = new JLabel("Pocahontas");
JButton playButton = new JButton("Play Game");
JButton exitButton = new JButton("Exit");
JButton easyButton = new JButton("Easy");
JButton mediumButton = new JButton("Medium");
JButton hardButton = new JButton("Hard");
add(leftPanel);
add(middlePanel, new FlowLayout());
add(rightPanel);
setGrid();
middlePanel.add(playButton);
middlePanel.add(exitButton);
rightPanel.add(easyButton);
rightPanel.add(mediumButton);
rightPanel.add(hardButton);
leftPanel.setBackground(Color.PINK);
middlePanel.setBackground(Color.RED);
easyButton.addActionListener(this);
mediumButton.addActionListener(this);
hardButton.addActionListener(this);
playButton.addActionListener(this);
exitButton.addActionListener(this);
}
public void setGrid()
{
for(int x = 0; x < SIZE; x++) {
gridPanel[x] = new JPanel();
gridPanel[x].setBorder(BorderFactory.createLineBorder(Color.BLACK));
leftPanel.add(gridPanel[x]);
gridPanel[x].setBackground(Color.GREEN);
gridPanel[x].addActionListener(this);
}
}
#Override
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (source == gridPanel[0]){
gridPanel[x].setBackground(Color.BLACK);
}
}
}
I have tried to find if there is any other method that is needed to do this but cant find anything. Is it possible that I will have to add a button to fill each of the panels to make this work?
Thanks!
It defaults to no addActionListener, and the code below is a reference suggestion.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
class GPanel extends JPanel {
private List<ActionListener> listenerList = new ArrayList<>();
public GPanel() {
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
var event = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "GPanel");
for (var i : listenerList) {
i.actionPerformed(event);
}
}
});
}
public void addActionListener(ActionListener listener) {
listenerList.add(listener);
}
}
public class ActionListenerTest extends JFrame {
public static void main(String[] args) {
new ActionListenerTest();
}
public ActionListenerTest() {
GPanel test = new GPanel();
test.setBackground(Color.BLUE);
add(test);
test.addActionListener(e-> {
System.out.println("Click: " + e.getActionCommand());
});
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
}
Related
I am a noob in java and am trying to make a kind of text adventure game. I want to be able to have the program have some kind of fade ability as it transitions from one layout of the UI to another.
I really have no idea what the best approach to this problem would be or if its really even feasible, but I have so far been trying to have a Jpanel that covers the entire window and uses a timer to fade in to cover everything else in black, or fades out from black to transparency thereby revealing everything underneath.
I have been testing this idea by trying to fade in/out the program at the start just to get the logic for the fade system working before trying to have it as a transition effect. The fade-out kind of works, but I have the program output the alpha level and the screen is turning black at around alpha 50 out of 255 which is confusing me. The fade-in does not work at all.
Here is the code for the fade method:
static int opacityCounter = 0;
public void fadeOut(JPanel frame){
System.out.println(opacityCounter);
opacityCounter = 0;
fadeTimer = new Timer(50, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.setBackground(new Color(0,0,0,opacityCounter));
opacityCounter++;
gui.window.add(frame);
if(opacityCounter >= 255){
opacityCounter = 255;
fadeTimer.stop();
}
System.out.println(opacityCounter);
}
});
fadeTimer.start();
}
This is the code where the "fadePanel" that covers the window is created and deployed in the method.
fadeScreen = new JPanel();
fadeScreen.setBounds(0,0,800,600);
fadeScreen.setBackground(Color.black);
window.add(fadeScreen);
game.visibilityManager.fadeOut(this.fadeScreen);
To clarify I want something that goes from a UI layout like this:
fades to black, before fading back to a UI that looks like this
This is a minimal reproducible example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Test {
JFrame window;
JPanel fadeScreen, screen1, screen2;
JLabel text1, text2;
Timer fadeTimer;
public Test(){
//Frame Window
window = new JFrame();
window.setSize(800,600);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().setBackground(Color.blue);
//Screen 1
screen1 = new JPanel();
screen1.setBounds(100, 100, 600, 125);
screen1.setBackground(Color.white);
text1 = new JLabel("Text1");
screen1.add(text1);
window.add(screen1);
//Screen 2
screen2 = new JPanel();
screen2.setBounds(100, 400, 600, 125);
screen2.setBackground(Color.white);
text2 = new JLabel("Text2");
screen2.add(text2);
window.add(screen2);
//Cover Panel
fadeScreen = new JPanel();
fadeScreen.setBounds(0,0,800,600);
fadeScreen.setBackground(Color.black);
window.add(fadeScreen);
window.setVisible(true);
//Comment out which method you don't want to use
fadeOut(this.fadeScreen);
//fadeIn(this.fadeScreen);
}
//Fade methods
int opacityCounter = 0;
public void fadeOut(JPanel frame){
System.out.println(opacityCounter);
opacityCounter = 0;
fadeTimer = new Timer(50, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.setBackground(new Color(0,0,0,opacityCounter));
opacityCounter++;
window.add(frame);
if(opacityCounter >= 255){
opacityCounter = 255;
fadeTimer.stop();
}
System.out.println(opacityCounter);
}
});
fadeTimer.start();
}
public void fadeIn(JPanel frame){
System.out.println(opacityCounter);
opacityCounter = 255;
fadeTimer = new Timer(50, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.setBackground(new Color(0,0,0,opacityCounter));
opacityCounter--;
window.add(frame);
if(opacityCounter <= 0){
opacityCounter = 0;
fadeTimer.stop();
}
System.out.println(opacityCounter);
}
});
fadeTimer.start();
}
public static void main(String[] args){
new Test();
}
}
Thanks in advance!
I would try these things:
Use the GlassPane of the top-level window and make a section of it darker where you want to cover things up, using a Swing Timer.
Use a CardLayout to swap the underlying components, and make the swap when the covering JPanel is darkest.
Then undarken the covering panel after the swap.
For example (to write more code explanation later):
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.Point;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class Test2 extends JPanel {
public static final String PANEL_1 = "panel 1";
public static final String PANEL_2 = "panel 2";
private CardLayout cardLayout = new CardLayout();
private JPanel cardPanel = new JPanel(cardLayout);
private JPanel panel1 = new JPanel();
private JPanel panel2 = new JPanel();
private Action fadeAction = new FadeAction(cardPanel);
public Test2() {
JLabel label = new JLabel("Panel 1");
label.setFont(label.getFont().deriveFont(Font.BOLD, 100f));
panel1.setLayout(new GridBagLayout());
int gap = 40;
panel1.setBorder(BorderFactory.createEmptyBorder(gap, gap, gap, gap));
panel1.add(label);
panel1.setBackground(Color.PINK);
label = new JLabel("Panel 2");
label.setFont(label.getFont().deriveFont(Font.BOLD, 100f));
panel2.setLayout(new GridBagLayout());
panel2.setBorder(BorderFactory.createEmptyBorder(gap, gap, gap, gap));
panel2.add(label);
panel2.setBackground(new Color(131, 238, 255));
cardPanel.add(panel1, PANEL_1);
cardPanel.add(panel2, PANEL_2);
JButton startFadeBtn = new JButton(fadeAction);
JPanel buttonPanel = new JPanel();
buttonPanel.add(startFadeBtn);
setLayout(new BorderLayout(5, 5));
add(cardPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.PAGE_END);
}
private static class FadeAction extends AbstractAction {
private static final int FADE_DELAY = 20;
private static final int UNFADE_VALUE = 255;
private JPanel cardPanel;
private JComponent glassPane;
private JPanel coverPanel = new JPanel();
private Timer fadeTimer;
private int counter = 0;
private boolean fade = true;
public FadeAction(JPanel cardPanel) {
super("Start Fade");
putValue(MNEMONIC_KEY, KeyEvent.VK_S);
this.cardPanel = cardPanel;
}
#Override
public void actionPerformed(ActionEvent e) {
counter = 0;
fade = true;
setEnabled(false);
CardLayout cl = (CardLayout) cardPanel.getLayout();
cl.show(cardPanel, PANEL_1);
Window topLevelWindow = SwingUtilities.getWindowAncestor(cardPanel);
glassPane = (JComponent) ((RootPaneContainer) topLevelWindow).getRootPane().getGlassPane();
glassPane.setVisible(true);
glassPane.setLayout(null);
coverPanel.setSize(cardPanel.getSize());
int x = cardPanel.getLocationOnScreen().x - glassPane.getLocationOnScreen().x;
int y = cardPanel.getLocationOnScreen().y - glassPane.getLocationOnScreen().y;
Point coverPanelPoint = new Point(x, y);
coverPanel.setLocation(coverPanelPoint);
glassPane.add(coverPanel);
fadeTimer = new Timer(FADE_DELAY, e2 -> fadeTimerActionPerformed(e2));
fadeTimer.start();
}
private void fadeTimerActionPerformed(ActionEvent e) {
coverPanel.setBackground(new Color(0, 0, 0, counter));
glassPane.repaint();
if (fade) {
counter++;
} else if (counter > 0) {
counter--;
} else {
glassPane.remove(coverPanel);
glassPane.setVisible(false);
setEnabled(true);
((Timer) e.getSource()).stop();
}
if (counter >= UNFADE_VALUE) {
fade = false;
CardLayout cl = (CardLayout) cardPanel.getLayout();
cl.show(cardPanel, PANEL_2);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Test2());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section. Pay close attention to the Concurrency in Swing and the Laying Out Components Within a Container sections.
This is Hovercraft Full Of Eels' answer. All I did was clean up the GUI creation and demonstrate how this would work with more than two JPanels.
I created five JPanels and displayed them in order with the fade-out/fade-in effect.
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.RootPaneContainer;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class FadeEffectsTesting {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Fade Effects Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new FadeEffectsTesting().getMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
});
}
public static final String[] PANEL_SEQUENCE = { "Panel 1", "Panel 2", "Panel 3", "Panel 4",
"Panel 5" };
private int sequence = 0;
private CardLayout cardLayout;
private FadeAction action;
private JPanel cardPanel, mainPanel;
public FadeEffectsTesting() {
this.mainPanel = new JPanel(new BorderLayout(5, 5));
this.cardPanel = createCardPanel();
this.action = new FadeAction(cardPanel);
mainPanel.add(cardPanel, BorderLayout.CENTER);
mainPanel.add(createButtonPanel(), BorderLayout.PAGE_END);
}
private JPanel createCardPanel() {
cardLayout = new CardLayout();
JPanel panel = new JPanel(cardLayout);
panel.add(createTextPanel(Color.PINK, PANEL_SEQUENCE[0]),
PANEL_SEQUENCE[0]);
panel.add(createTextPanel(new Color(131, 238, 255),
PANEL_SEQUENCE[1]), PANEL_SEQUENCE[1]);
panel.add(createTextPanel(Color.PINK, PANEL_SEQUENCE[2]),
PANEL_SEQUENCE[2]);
panel.add(createTextPanel(new Color(131, 238, 255),
PANEL_SEQUENCE[3]), PANEL_SEQUENCE[3]);
panel.add(createTextPanel(Color.PINK, PANEL_SEQUENCE[4]),
PANEL_SEQUENCE[4]);
return panel;
}
private JPanel createTextPanel(Color color, String text) {
JPanel panel = new JPanel(new FlowLayout());
panel.setBackground(color);
int gap = 40;
panel.setBorder(BorderFactory.createEmptyBorder(gap, gap, gap, gap));
JLabel label = new JLabel(text);
label.setFont(label.getFont().deriveFont(Font.BOLD, 72f));
panel.add(label);
return panel;
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new FlowLayout());
setFadeAction();
JButton startFadeBtn = new JButton(action);
panel.add(startFadeBtn);
return panel;
}
public void setFadeAction() {
action.setFromPanel(PANEL_SEQUENCE[sequence]);
action.setToPanel(PANEL_SEQUENCE[sequence + 1]);
}
public JPanel getMainPanel() {
return mainPanel;
}
public class FadeAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private static final int FADE_DELAY = 20;
private static final int UNFADE_VALUE = 255;
private JPanel cardPanel;
private JComponent glassPane;
private JPanel coverPanel;
private Timer fadeTimer;
private int alphaValue;
private boolean fadeOut;
private String fromPanel, toPanel;
public FadeAction(JPanel cardPanel) {
super("Start Fade");
this.putValue(MNEMONIC_KEY, KeyEvent.VK_S);
this.cardPanel = cardPanel;
this.alphaValue = 0;
this.fadeOut = true;
}
public void setFromPanel(String fromPanel) {
this.fromPanel = fromPanel;
}
public void setToPanel(String toPanel) {
this.toPanel = toPanel;
}
#Override
public void actionPerformed(ActionEvent event) {
alphaValue = 0;
fadeOut = true;
setEnabled(false);
CardLayout cl = (CardLayout) cardPanel.getLayout();
cl.show(cardPanel, fromPanel);
Window topLevelWindow = SwingUtilities.getWindowAncestor(cardPanel);
glassPane = (JComponent) ((RootPaneContainer) topLevelWindow).getRootPane()
.getGlassPane();
glassPane.setLayout(null);
coverPanel = new JPanel();
coverPanel.setSize(cardPanel.getSize());
glassPane.add(coverPanel);
glassPane.setVisible(true);
fadeTimer = new Timer(FADE_DELAY, e2 -> fadeTimerActionPerformed(e2));
fadeTimer.start();
}
private void fadeTimerActionPerformed(ActionEvent event) {
coverPanel.setBackground(new Color(0, 0, 0, alphaValue));
glassPane.repaint();
if (fadeOut) {
alphaValue += 3;
} else if (alphaValue > 0) {
alphaValue -= 3;
} else {
glassPane.remove(coverPanel);
glassPane.setVisible(false);
((Timer) event.getSource()).stop();
if (++sequence < (PANEL_SEQUENCE.length - 1)) {
setFadeAction();
setEnabled(true);
}
}
if (alphaValue >= UNFADE_VALUE) {
fadeOut = false;
CardLayout cl = (CardLayout) cardPanel.getLayout();
cl.show(cardPanel, toPanel);
}
}
}
}
Everything looks ok to me but for some reason, nothing is showing up properly, maybe I missed something but I'm not sure why it's not working, can someone help me out?
** task **
Improve your program by adding two
combo boxes in the frame. Through the combo boxes, the user should be able to
select their preferred fonts and font sizes. The displayed text will then be updated
accordingly (see the figure below).
Here is what its suppose to look like
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JTextField;
import java.awt.*;
import java.awt.event.*;
public class ComboGUI extends JFrame implements ActionListener {
public JButton update;
public JTextField textField;
public JLabel textLabel;
public JComboBox<String> fontBox;
public JComboBox sizeBox;
public String font;
public String size;
public ComboGUI()
{
components();
panels();
actionListener();
}
public void components()
{
this.update = new JButton("update");
this.textField=new JTextField(20);
this.textField.setText("hello");
this.textLabel= new JLabel("GUI");
this.font="Arial";
this.size="20";
this.textLabel.setFont(new Font(this.font, Font.PLAIN, Integer.parseInt(this.size)));
this.fontBox=new JComboBox();
this.fontBox.addItem("Times New Roman");
this.fontBox.addItem("Calibri");
this.sizeBox= new JComboBox();
this.sizeBox.addItem("20");
this.sizeBox.addItem("30");
this.sizeBox.addItem("40");
this.setSize(400, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
}
public void panels(){
JPanel northPanel =new JPanel();
JLabel fontLabel =new JLabel("Font: ");
JLabel sizeLabel =new JLabel("size: ");
northPanel.add(fontLabel);
//center
BGPanel centerPanel =new BGPanel();
centerPanel.add(this.textLabel);
this.add(centerPanel,BorderLayout.CENTER);
//south
BGPanel southPanel =new BGPanel();
southPanel.add(this.textLabel);
this.add(southPanel,BorderLayout.CENTER);
}
public void actionListener(){
this.update.addActionListener(this);
this.fontBox.addActionListener(this);
this.sizeBox.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e){
if(e.getSource()==this.update){
this.textLabel.setText(this.textField.getText());
}
if(e.getSource()==this.fontBox || e.getSource()==this.sizeBox){
this.font=this.fontBox.getSelectedItem().toString();
this.size=this.sizeBox.getSelectedItem().toString();
this.textLabel.setFont(new Font(this.font,Font.PLAIN,Integer.parseInt(this.size)));
}
this.repaint();
}
public static void main(String[] args) {
ComboGUI comb =new ComboGUI();
combo.setVisible(true);
}
}
this is what im getting instead
It looks like you are missing this.setVisible(true); at the end of your constructor.
Your code should look like this:
public ComboGUI()
{
components();
panels();
actionListener();
this.setVisible(true);
}
incase anyone is trying to do something similar, this is the complete solution
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
public class ComboGUI extends JFrame implements ActionListener{
public void updateLabelText(){
size = fSize.getItemAt(fSize.getSelectedIndex());
font = fStyles.getItemAt(fStyles.getSelectedIndex());
updateLabel.setFont(new Font(font,Font.PLAIN,size));
}
public static BGPanel centrePanel;
public JComboBox<String> fStyles;
public JComboBox<Integer> fSize;
public JButton updateButton;
public JLabel updateLabel;
public JLabel fontLabel;
public JLabel sizeLabel;
public JTextField textField;
public JPanel BottomPanel;
public JPanel topPanel;
private String font;
private int size;
public ComboGUI() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(400,400);
this.setLocation(0, 0);
//Top
topPanel = new JPanel();
fontLabel = new JLabel("Font:");
sizeLabel = new JLabel("Font Size:");
fStyles = new JComboBox<String>();
fStyles.addItem("Arial");
fStyles.addItem("TimesRoman");
fStyles.addItem("Serif");
fStyles.addItem("Monospaced");
fStyles.addActionListener(this);
fSize = new JComboBox<Integer>();
fSize.addItem(10);
fSize.addItem(20);
fSize.addItem(30);
fSize.addItem(40);
fSize.addActionListener(this);
topPanel.add(fontLabel);
topPanel.add(fStyles);
topPanel.add(sizeLabel);
topPanel.add(fSize);
//CentrePanel setup
centrePanel = new BGPanel();
updateLabel = new JLabel("I love PDC :)");
centrePanel.add(updateLabel);
//Bottom
BottomPanel = new JPanel();
updateButton = new JButton("Update");
textField = new JTextField(20);
textField.setText("I love PDC :)");
updateButton.addActionListener(this);
BottomPanel.add(textField);
BottomPanel.add(updateButton);
this.add(centrePanel,BorderLayout.CENTER);
this.add(BottomPanel,BorderLayout.SOUTH);
this.add(topPanel,BorderLayout.NORTH);
updateLabelText();
}
public static void main(String[] args) {
ComboGUI combo = new ComboGUI();
combo.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == updateButton){
updateLabel.setText(textField.getText().trim());
}
if(e.getSource() == fStyles){
updateLabelText();
}
if (e.getSource() == fSize){
updateLabelText();
}
}
}
I have 2 windows at the moment. After a user clicks on the Submit button, the Main window appears but it appears as such:
The codes are:
LoginForm.java
package interfaceGUI;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginForm extends JFrame{
private JLabel loginEmail;
private JLabel loginPass;
private JTextField loginTextField;
private JPasswordField loginPassField;
private JButton submit;
private JPanel loginArea;
private JPanel buttonArea;
public LoginForm()
{
super("Party Supplies Rental");
setLayout(new FlowLayout());
loginEmail = new JLabel("Enter Your Email Address: ");
loginTextField = new JTextField(20);
loginPass = new JLabel("Enter Your Password: ");
loginPassField = new JPasswordField(20);
loginArea = new JPanel();
loginArea.setLayout(new GridLayout(2,2));
loginArea.add(loginEmail); //add to the JPanel
loginArea.add(loginTextField);
loginArea.add(loginPass);
loginArea.add(loginPassField);
add(loginArea); //add JPanel to the frame
submit = new JButton("Submit");
buttonArea = new JPanel();
buttonArea.setLayout(new GridLayout(1,2));
buttonArea.add(submit);
add(buttonArea);
ButtonHandler handler= new ButtonHandler();
submit.addActionListener(handler);
}
public class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if(event.getSource() == submit)
{
dispose();
new Main().setVisible(true);
}
}
}
}
And Main.java:
package interfaceGUI;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main extends JFrame{
private JLabel label;
private JPanel forLabel;
private JButton birthdayCategory;
private JButton summerCategory;
private JButton halloweenCategory;
private JPanel forCategory;
public Main()
{
super("Home");
setLayout(new FlowLayout());
label = new JLabel("Choose the Party Category");
forLabel = new JPanel();
forLabel.setLayout(new GridLayout(1,3));
forLabel.add(label);
add(forLabel);
birthdayCategory = new JButton("Birthday Party");
summerCategory = new JButton("Summer/Festive Party");
halloweenCategory = new JButton("Halloween Party");
forCategory = new JPanel();
forCategory.setLayout(new GridLayout(1,3));
forCategory.add(birthdayCategory);
forCategory.add(summerCategory);
forCategory.add(halloweenCategory);
add(forCategory);
}
}
The testMain.java:
package interfaceGUI;
import javax.swing.JFrame;
public class testMain {
public static void main(String[] args) {
Main myFrame = new Main();
myFrame.setSize(300,200); //not working
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
}
}
Can anybody suggest me what's wrong? Thanks.
I wouldn't call setSize() but rather would let my components and the layout managers set their own sizes by calling pack(). Occasionally you might want to override a component's getPreferredSize() but if you do so, do it with extreme care.
Calling pack() does seem to work for me with your code:
import java.awt.FlowLayout;
import java.awt.GridLayout;
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.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class TestMain {
private static void createAndShowGui() {
LoginForm loginForm = new LoginForm();
loginForm.pack();
loginForm.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class LoginForm extends JFrame {
private JLabel loginEmail;
private JLabel loginPass;
private JTextField loginTextField;
private JPasswordField loginPassField;
private JButton submit;
private JPanel loginArea;
private JPanel buttonArea;
public LoginForm() {
super("Party Supplies Rental");
setLayout(new FlowLayout());
loginEmail = new JLabel("Enter Your Email Address: ");
loginTextField = new JTextField(20);
loginPass = new JLabel("Enter Your Password: ");
loginPassField = new JPasswordField(20);
loginArea = new JPanel();
loginArea.setLayout(new GridLayout(2, 2));
loginArea.add(loginEmail); // add to the JPanel
loginArea.add(loginTextField);
loginArea.add(loginPass);
loginArea.add(loginPassField);
add(loginArea); // add JPanel to the frame
submit = new JButton("Submit");
buttonArea = new JPanel();
buttonArea.setLayout(new GridLayout(1, 2));
buttonArea.add(submit);
add(buttonArea);
ButtonHandler handler = new ButtonHandler();
submit.addActionListener(handler);
}
public class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == submit) {
dispose();
Main main = new Main();
main.pack();
main.setVisible(true);
}
}
}
}
class Main extends JFrame {
private JLabel label;
private JPanel forLabel;
private JButton birthdayCategory;
private JButton summerCategory;
private JButton halloweenCategory;
private JPanel forCategory;
public Main() {
super("Home");
setLayout(new FlowLayout());
label = new JLabel("Choose the Party Category");
forLabel = new JPanel();
forLabel.setLayout(new GridLayout(1, 3));
forLabel.add(label);
add(forLabel);
birthdayCategory = new JButton("Birthday Party");
summerCategory = new JButton("Summer/Festive Party");
halloweenCategory = new JButton("Halloween Party");
forCategory = new JPanel();
forCategory.setLayout(new GridLayout(1, 3));
forCategory.add(birthdayCategory);
forCategory.add(summerCategory);
forCategory.add(halloweenCategory);
add(forCategory);
}
}
Note that if this were my project, I'd change it to use a CardLayout to swap views, something like:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.*;
#SuppressWarnings("serial")
public class TestMain2 extends JPanel {
private static final String GUI_NAME = "My GUI";
private CardLayout cardLayout = new CardLayout();
private LoginPanel loginPanel = new LoginPanel();
private HomePanel homePanel = new HomePanel();
public TestMain2() {
setLayout(cardLayout);
add(loginPanel, LoginPanel.NAME);
add(homePanel, HomePanel.NAME);
for (PartyCategory partyCategory : PartyCategory.values()) {
PartyPanel partyPanel = new PartyPanel(partyCategory.getName());
partyPanel.addPropertyChangeListener(PartyPanel.RETURN, new PartyPanelListener());
add(partyPanel, partyCategory.getName());
}
loginPanel.addPropertyChangeListener(LoginPanel.NAME, new LoginPanelListener());
homePanel.addPropertyChangeListener(HomePanel.PARTY_CATEGORY, new HomeListener());
}
private class LoginPanelListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getNewValue() == Boolean.TRUE) {
System.out.println("Submit Pressed");
System.out.println("Login: " + loginPanel.getLogin());
// TODO: Dangerous code!!! Delete this!!!
System.out.println("Password: " + new String(loginPanel.getPassword()));
cardLayout.show(TestMain2.this, HomePanel.NAME);
} else {
System.out.println("Cancel Pressed");
}
}
}
private class HomeListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent evt) {
PartyCategory partyCategory = (PartyCategory) evt.getNewValue();
cardLayout.show(TestMain2.this, partyCategory.getName());
}
}
private class PartyPanelListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getNewValue() == Boolean.TRUE) {
cardLayout.show(TestMain2.this, HomePanel.NAME);
}
}
}
private static void createAndShowGui() {
TestMain2 mainPanel = new TestMain2();
JFrame frame = new JFrame(GUI_NAME);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings({"serial", "hiding"})
class LoginPanel extends JPanel {
public static final String NAME = "Login";
private static final int COLS = 10;
private static final String EMAIL_PROMPT = "Enter Your Email Address:";
private static final String PASSWORD_PROMPT = "Enter Your Password:";
private boolean submitPressed = false;
private JTextField textField = new JTextField(COLS);
private JPasswordField passField = new JPasswordField(COLS);
public LoginPanel() {
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 5));
buttonPanel.add(new JButton(new ButtonAction("Submit", KeyEvent.VK_S, true)));
buttonPanel.add(new JButton(new ButtonAction("Cancel", KeyEvent.VK_C, false)));
buttonPanel.add(new JButton(new ExitAction()));
JPanel innerPanel = new JPanel(new GridBagLayout());
innerPanel.setBorder(BorderFactory.createTitledBorder(NAME));
innerPanel.add(new JLabel(EMAIL_PROMPT, JLabel.LEADING), getGbc(0, 0));
innerPanel.add(textField, getGbc(1, 0));
innerPanel.add(new JLabel(PASSWORD_PROMPT, JLabel.LEADING), getGbc(0, 1));
innerPanel.add(passField, getGbc(1, 1));
innerPanel.add(buttonPanel, getGbc(0, 2, 2, 1));
add(innerPanel);
}
public boolean isLoginValid() {
return submitPressed;
}
public void setSubmitPressed(boolean submitPressed) {
this.submitPressed = submitPressed;
firePropertyChange(NAME, null, submitPressed);
}
public String getLogin() {
return textField.getText();
}
public char[] getPassword() {
return passField.getPassword();
}
private class ButtonAction extends AbstractAction {
private boolean submitPressed;
public ButtonAction(String name, int mnemonic, boolean submitPressed) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
this.submitPressed = submitPressed;
}
#Override
public void actionPerformed(ActionEvent e) {
setSubmitPressed(submitPressed);
}
}
private static GridBagConstraints getGbc(int x, int y, int width, int height) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = width;
gbc.gridheight = height;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
if (x == 1) {
gbc.insets = new Insets(5, 15, 5, 5);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.EAST;
} else {
gbc.insets = new Insets(5, 5, 5, 5);
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.WEST;
}
return gbc;
}
private static GridBagConstraints getGbc(int x, int y) {
return getGbc(x, y, 1, 1);
}
}
#SuppressWarnings({"serial", "hiding"})
class HomePanel extends JPanel {
public static final String NAME = "Home";
public static final String PARTY_CATEGORY = "Party Category";
private static final String PROMPT = "Choose Party Category:";
private PartyCategory partyCategory = null;
public HomePanel() {
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 5));
for (PartyCategory partyCategory : PartyCategory.values()) {
buttonPanel.add(new JButton(new ButtonListener(partyCategory)));
}
add(new JLabel(PROMPT));
add(buttonPanel);
}
public PartyCategory getPartyCategory() {
return partyCategory;
}
public void setPartyCategory(PartyCategory partyCategory) {
this.partyCategory = partyCategory;
firePropertyChange(PARTY_CATEGORY, null, partyCategory);
}
private class ButtonListener extends AbstractAction {
private PartyCategory partyCategory;
public ButtonListener(PartyCategory partyCategory) {
super(partyCategory.getName());
this.partyCategory = partyCategory;
int mnemonic = partyCategory.getName().charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
setPartyCategory(partyCategory);
}
}
}
enum PartyCategory {
BIRTHDAY_PARTY("Birthday Party"),
SUMMER_FESTIVE_PARTY("Summer/Festive Party"),
HALLOWEEN_PARTY("Halloween Party");
private String name;
private PartyCategory(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
#SuppressWarnings("serial")
class PartyPanel extends JPanel {
public static final String RETURN = "return";
private static final int PREF_W = 400;
private static final int PREF_H = PREF_W;
public PartyPanel(String name) {
JLabel label = new JLabel(name, SwingConstants.CENTER);
label.setFont(label.getFont().deriveFont(Font.BOLD, 48f));
JPanel returnButtonPanel = new JPanel();
returnButtonPanel.add(new JButton(new ReturnAction()));
returnButtonPanel.add(new JButton(new ExitAction()));
setLayout(new BorderLayout());
add(label);
add(returnButtonPanel, BorderLayout.PAGE_END);
}
#Override
public Dimension getPreferredSize() {
Dimension superSize = super.getPreferredSize();
if (isPreferredSizeSet()) {
return superSize;
}
int prefW = Math.max(superSize.width, PREF_W);
int prefH = Math.max(superSize.height, PREF_H);
return new Dimension(prefW, prefH);
}
private class ReturnAction extends AbstractAction {
public ReturnAction() {
super("Return Home");
putValue(MNEMONIC_KEY, KeyEvent.VK_R);
}
#Override
public void actionPerformed(ActionEvent e) {
PartyPanel.this.firePropertyChange(RETURN, null, true);
}
}
}
#SuppressWarnings("serial")
class ExitAction extends AbstractAction {
public ExitAction() {
super("Exit");
putValue(MNEMONIC_KEY, KeyEvent.VK_X);
}
#Override
public void actionPerformed(ActionEvent e) {
// this will not work for JMenuItem which would require a test to see if coming
// from a pop up first.
Component source = (Component) e.getSource();
Window win = SwingUtilities.getWindowAncestor(source);
win.dispose();
}
}
I have created 2 classes that are working together to show pictures by clicking different buttons. In my EventEvent class I tried to make it so that when you press the "Picture 1" button, the variable ImageIcon xpic gets the value of ImageIcon vpic (which holds an image), after xpic has the same value as vpic my frame is supposed to somehow refresh so that xpic's new value applies and gets then shows the picture.
Why doesn't my image show up even though the button press repaints the JPanel the image is in?
Main class:
import java.awt.*;
import javax.swing.*;
public class EventMain extends JFrame{
EventEvent obje = new EventEvent(this);
// Build Buttons
JButton picB1;
JButton picB2;
JButton picB3;
JButton picB4;
JButton picB5;
//Build Panels
JPanel row0;
//Build Pictures
ImageIcon xpic;
ImageIcon vpic;
public EventMain(){
super("Buttons");
setLookAndFeel();
setSize(470, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridLayout layout1 = new GridLayout(3,4);
setLayout(layout1);
picB1 = new JButton("Picture 1");
picB2 = new JButton("Picture 2");
picB3 = new JButton("Picture 3");
picB4 = new JButton("Picture 4");
picB5 = new JButton("Picture 5");
vpic = new ImageIcon(getClass().getResource("Images/vanessa.png"));
// Set up Row 0
row0 = new JPanel();
JLabel statement = new JLabel("Choose a picture: ", JLabel.LEFT);
JLabel picture = new JLabel(xpic);
// Set up Row 1
JPanel row1 = new JPanel();
// Set up Row 2
JPanel row2 = new JPanel();
//Listeners
picB1.addActionListener(obje);
FlowLayout grid0 = new FlowLayout (FlowLayout.CENTER);
row0.setLayout(grid0);
row0.add(statement);
row0.add(picture);
add(row0);
FlowLayout grid1 = new FlowLayout(FlowLayout.CENTER);
row1.setLayout(grid1);
row1.add(picB1);
row1.add(picB2);
add(row1);
FlowLayout grid2 = new FlowLayout(FlowLayout.CENTER);
row2.setLayout(grid2);
row2.add(picB3);
row2.add(picB4);
row2.add(picB5);
add(row2);
setVisible(true);
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.NimbusLookAndFeel");
} catch (Exception exc) {
}
}
public static void main(String[] args) {
EventMain con = new EventMain();
}
}
Class containing events:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class EventEvent implements ActionListener {
EventMain gui;
public EventEvent(EventMain in){
gui = in;
}
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
if (command.equals("Picture 1")){
gui.xpic = gui.vpic;
gui.row0.repaint();
}
}
}
You're confusing variables with objects. Just because you change the object associated with the xpic variable, don't assume that this will change the object (the Icon) held by the JLabel. There is no magic in Java, and changing the object that a variable refers to will have no effect on the prior object.
In other words, this:
gui.xpic = gui.vpic;
gui.row0.repaint();
will have no effect on the icon that the picture JLabel is displaying
To swap icons, you must call setIcon(...) on the JLabel. Period. You will need to make the picture JLabel a field, not a local variable, and give your GUI class a public method that allows outside classes to change the state of the JLabel's icon.
Also, you should not manipulate object fields directly. Instead give your gui public methods that your event object can call.
Edit
For example:
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.*;
#SuppressWarnings("serial")
public class MyGui extends JPanel {
public static final String IMAGE_PATH = "https://duke.kenai.com/cards/.Midsize/CardFaces.png.png";
private static final int ROWS = 4;
private static final int COLS = 13;
private BufferedImage largeImg;
private List<ImageIcon> iconList = new ArrayList<>();
private JLabel pictureLabel = new JLabel();
private JButton swapPictureBtn = new JButton(new SwapPictureAction(this, "Swap Picture"));
private int iconIndex = 0;
public MyGui() throws IOException {
add(pictureLabel);
add(swapPictureBtn);
URL imgUrl = new URL(IMAGE_PATH);
largeImg = ImageIO.read(imgUrl);
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
int x = (j * largeImg.getWidth()) / COLS;
int y = (i * largeImg.getHeight()) / ROWS;
int w = largeImg.getWidth() / COLS;
int h = largeImg.getHeight() / ROWS;
iconList.add(new ImageIcon(largeImg.getSubimage(x, y, w, h)));
}
}
pictureLabel.setIcon(iconList.get(iconIndex));
}
public void swapPicture() {
iconIndex++;
iconIndex %= iconList.size();
pictureLabel.setIcon(iconList.get(iconIndex));
}
private static void createAndShowGui() {
MyGui mainPanel;
try {
mainPanel = new MyGui();
JFrame frame = new JFrame("MyGui");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class SwapPictureAction extends AbstractAction {
private MyGui myGui;
public SwapPictureAction(MyGui myGui, String name) {
super(name);
this.myGui = myGui;
}
#Override
public void actionPerformed(ActionEvent e) {
myGui.swapPicture();
}
}
See the createAction() method below and how it creates an AbstractAction. See also the tutorial related to using actions with buttons. http://docs.oracle.com/javase/tutorial/uiswing/misc/action.html
import javax.swing.*;
import javax.swing.plaf.nimbus.NimbusLookAndFeel;
import java.awt.*;
import java.awt.event.ActionEvent;
public class EventMain {
private static final ImageIcon PICTURE_1 = new ImageIcon(EventMain.class.getResource("images/v1.png"));
private static final ImageIcon PICTURE_2 = new ImageIcon(EventMain.class.getResource("images/v2.png"));
private JFrame frame;
EventMain create() {
setLookAndFeel();
frame = createFrame();
frame.getContentPane().add(createContent());
return this;
}
void show() {
frame.setSize(470, 300);
frame.setVisible(true);
}
private JFrame createFrame() {
JFrame frame = new JFrame("Buttons");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
return frame;
}
private Component createContent() {
final JLabel picture = new JLabel();
JButton picB1 = new JButton(createAction("Picture 1", picture, PICTURE_1));
JButton picB2 = new JButton(createAction("Picture 2", picture, PICTURE_2));
JButton picB3 = new JButton(createAction("Picture 3", picture, PICTURE_1));
JButton picB4 = new JButton(createAction("Picture 4", picture, PICTURE_2));
JButton picB5 = new JButton(createAction("Picture 5", picture, PICTURE_1));
JLabel statement = new JLabel("Choose a picture: ", JLabel.LEFT);
// Create rows 1, 2, 3
JPanel panel = new JPanel(new GridLayout(3, 4));
panel.add(createRow(statement, picture));
panel.add(createRow(picB1, picB2));
panel.add(createRow(picB3, picB4, picB5));
return panel;
}
/**
* Create an action for the button. http://docs.oracle.com/javase/tutorial/uiswing/misc/action.html
*/
private Action createAction(String label, final JLabel picture, final Icon icon) {
AbstractAction action = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
picture.setIcon(icon);
}
};
action.putValue(Action.NAME, label);
return action;
}
private Component createRow(Component... componentsToAdd) {
JPanel row = new JPanel(new FlowLayout(FlowLayout.CENTER));
for (Component component : componentsToAdd) {
row.add(component);
}
return row;
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel(new NimbusLookAndFeel());
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new EventMain().create().show();
}
});
}
}
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);
}
}
}
}