-3

I have been trying to display a number of jpanels after one another with different timings between each. I have used swing timer, thread.sleep and int++ counters to try and create spacing between the display of each jpanel, each without success.

In a previous post, I was told that timers would be the best option. I have tried many different tutorials and have had no luck at all, tbh I really do not understand its implementation.

my button that initiates the whole process uses a mouseListener, whereas all tutorials I have read refer to using ActionListeners which has confused me further.

Could I ask that someone enlightens me with how this process would be achieved.

What would be coded in my comment parts?

if (a.getSource() == button){
    panel1.setVisible(true);

    ActionListener listener = new ActionListener(){
        public void actiinPerformed(ActionEvent event){
            panel1.setVisible(false);
            panel2.setVisible(true);
        }
    };
    Timer timer = new Timer(4000, listener);
    timer.start();

   // This is one method I tried, and even ifit had worked I wouldnt know where to begin timing the following panels.Would I create a new timer for each part of the panel exchange?
   // panel1.setVisible(false);
   // panel2.setVisible(true);
   // panel2.setVisible(false);
   // panel3.setVisible(true);
   // panel3.setVisible(false);
   // menu.setVisible(true);
}

Thanks in advance guys.

dazbrad
  • 182
  • 1
  • 12
  • 1
    Please show us your Swing Timer attempt. Else, how will we know what you're doing wrong? And note that *nothing* goes in the commented regions of your code. You would use a CardLayout, and you'd swap your cards in your Swing Timer, but again, we can help you better if you show us more of your attempted code. – Hovercraft Full Of Eels Sep 07 '14 at 13:48
  • I have asked this because when I use the tutorials I really dont know where I would put it in my code I already have, off the top of my head what I attempted was as follows... – dazbrad Sep 07 '14 at 13:53
  • *"I really dont know where I would put it in my code"* If you don't have enough idea to try something, then perhaps you really should't pursue programming. – Andrew Thompson Sep 07 '14 at 13:55
  • @AndrewThompson: a little harsh perhaps (I know, it's the pot calling the kettle black), but let's see what he tried. Let's see how he can improve this question. – Hovercraft Full Of Eels Sep 07 '14 at 13:58
  • Off the top of my head, this is how the tutorial went... ActionListener listener = new ActionListener(){ public void actionPerformed(actionEvent event){ System.out.println("hello"); } }; Timer timer = new Timer(4000, listener); timer.start(); The thing is, I realy do not know where this goes within my code I already have, neither do I understand timers enough to modify it for my panel exchange purpose. I know this code is correct because evert tutorial is very similar. Thats good to know, thanks, knowing not where the code goes is half my problem. – dazbrad Sep 07 '14 at 14:09
  • Please don't post code in comments since it loses its formatting making it unreadable. Instead, post any new code to the bottom of your original question by [editing your question](http://stackoverflow.com/posts/25710812/edit). And don't show us "off the top of your head stuff". Please let's see an honest decent effort at this. – Hovercraft Full Of Eels Sep 07 '14 at 14:09
  • @AndrewThompson: We all had to start somewhere, somethings I have struggled with, a huge majority of my project I have achieved myself with experimenting and trial and error. If it was possible to show you what I have done so far, I think that you would realise that I make the best attempt to solve my own problems first before relying on the community to do my work for me. This isnt a dig at you by the way, just trying to show that this is a simple misunderstanding of learning. – dazbrad Sep 07 '14 at 14:55
  • If you aren't use it **[javax.swing.Timer](http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html)** exists for a reason! –  Sep 07 '14 at 15:39

1 Answers1

2

Again some general suggestions with more specific ones once I see your improved question and code:

  • Swap your JPanels using a CardLayout. The CardLayout tutorial will show you how.
  • Do the swapping inside of your Timer's ActionListener. You do not want to code it like you have shown us initially -- in a linear fashion. The ActionListener will have to know what card you want to show next with each tick of the timer, and so you will have to give it this logic.
  • If all you want to do is to cycle through your JPanels in order, then the swapping code could be as simple as calling next(...) on your CardLayout.
  • If however you want to flip around through JPanels in a non-cyclical way, then you'll have to use CardLayout's show(...) method, passing in the appropriate constant that corresponds to the JPanel that you wish to display at that time.

For example,

import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.*;

@SuppressWarnings("serial")
public class PanelSwap extends JPanel {
   private static final int CARD_COUNT = 5;
   private static final String CARD = "card";
   private static final int TIMER_DELAY = 1000;
   private CardLayout cardlayout = new CardLayout();
   private Random random = new Random();

   public PanelSwap() {
      setLayout(cardlayout);
      for (int i = 0; i < CARD_COUNT; i++) {
         add(createCardPanel(i), CARD + i);
      }

      new Timer(TIMER_DELAY, new TimerListener()).start();;
   }

   private JPanel createCardPanel(int i) {
      JPanel cardPanel = new JPanel(new GridBagLayout());
      String name = "Card Number " + i;
      JLabel label = new JLabel(name);
      cardPanel.add(label, SwingConstants.CENTER);
      cardPanel.setName(name);

      Dimension preferredSize = new Dimension(300, 200);
      cardPanel.setPreferredSize(preferredSize);

      // just to give the JPanels different background colors
      int[] rgb = new int[3];
      for (int j = 0; j < rgb.length; j++) {
         rgb[j] = random.nextInt(256);
      }
      Color background = new Color(rgb[0], rgb[1], rgb[2]);
      Color foreground = new Color(256 - rgb[0], 256 - rgb[1], 256 - rgb[2]);
      cardPanel.setBackground(background);
      label.setForeground(foreground);
      return cardPanel;
   }

   class TimerListener implements ActionListener {

      @Override
      public void actionPerformed(ActionEvent e) {
         cardlayout.next(PanelSwap.this);
      }
   }

   private static void createAndShowGui() {
      PanelSwap mainPanel = new PanelSwap();

      JFrame frame = new JFrame("PanelSwap");
      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();
         }
      });
   }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373