Swing timers

Currently having difficultly with swing timers and getting it to update it's delay
We have a GUI app that will display screens for differing amounts of time, each screen has it's own time limit. The timer times out at 4000 for each screen( timerArray[0] );
//I create the timer
delay = timerArray[0];
timer = new Timer( delay, this );
//start the timer in the start buttons action performed.
timer.start();
//reset the timer in an inner class that repaints the JPanel
delay = timerArray[currentScreen];
timer.setDelay(delay);
// stop and reset the screen in actionPerformed for main window
System.out.println( currentScreen+" "+timer.getDelay() );
contentPane.add( new splashScreen() );
timer.stop();
And the print out is
1 4000
2 20000
3 60000
4 15000
So why is it not changing it's time?

Are you sure you have understand that the Timer works like this :
<---initialDelay--->fire ActionEvent<---delay--->fire ActionEvent<---delay--->fire Action Event<--- ...
while it is not stopped.
for example if you want the Timer to count 4 seconds you set the initial delay to 1000 (millis) and the delay to 1000 also.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SplashScreen extends JWindow {
     int duration = 0;
     int counter = 0;
     javax.swing.Timer timer;
     public SplashScreen() { 
          ImageIcon bg = new ImageIcon("image1.jpg");
          getContentPane().add(new JLabel(bg));
          pack();
          Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
          setLocation(screenSize.width/2 - getWidth()/2,
                          screenSize.height/2 - getHeight()/2);
          timer = new javax.swing.Timer(1000, new ActionListener() {
               public void actionPerformed(ActionEvent e) {
                    counter++;
                    if (counter>=duration) {
                         closeSplashScreen();
     public void showSplashScreen(int seconds) {
          duration = seconds;
          counter = 0;
          setVisible(true);
          timer.start();
     public void closeSplashScreen() {
          if (timer.isRunning()) {
               timer.stop();
          setVisible(false);
     public static void main(String[] args) {
          SplashScreen sp = new SplashScreen();
          sp.showSplashScreen(4);
}------ unformatted version ----
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SplashScreen extends JWindow {
     int duration = 0;
     int counter = 0;
     javax.swing.Timer timer;
public SplashScreen() { 
          ImageIcon bg = new ImageIcon("image1.jpg");
          getContentPane().add(new JLabel(bg));
          pack();
          Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
          setLocation(screenSize.width/2 - getWidth()/2,
                         screenSize.height/2 - getHeight()/2);
          timer = new javax.swing.Timer(1000, new ActionListener() {
               public void actionPerformed(ActionEvent e) {
                    counter++;
                    if (counter>=duration) {
                         closeSplashScreen();
     public void showSplashScreen(int seconds) {
          duration = seconds;
          counter = 0;
          setVisible(true);
          timer.start();
     public void closeSplashScreen() {
          if (timer.isRunning()) {
               timer.stop();
          setVisible(false);
     public static void main(String[] args) {
          SplashScreen sp = new SplashScreen();
          sp.showSplashScreen(4);
Hope this helps,
Denis

Similar Messages

  • Troubles with Swing Timers

    I am trying to learn how to use javax.swing.timer. I'm simply trying to update a JLabel on an interval. The code I have looks like this:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    class GUI extends JFrame implements ActionListener
    Timer clock;
    JLabel label;
    int numberFrames;
    GUI()
         clock = new Timer(25, this);
         JLabel label = new JLabel("0");
         getContentPane().add(label, BorderLayout.NORTH);
         numberFrames = 0;
         clock.setInitialDelay(0);
         clock.setCoalesce(true);
         clock.start();
    public void actionPerformed(ActionEvent e)
         numberFrames++;
         label.setText("" + numberFrames);
    public class Timed
    public static void main(String argv[])
         GUI window = new GUI();
         window.setSize(100,100);
         window.setVisible(true);     
    Unfortuantely, the ActionPerformed executes only once and throws a NullPointerException whenever it tries to update the label. I also looked at Java's site for learning how to use Swing Timers, but I didn't understand what they were doing when they put in multiple actionListeners.
    Please Help.

    The problem is with variable scoping:
    GUI()
    clock = new Timer(25, this);
    JLabel label = new JLabel("0"); <<<<<<<<<<<<<DONT DECLARE A JLABEL HERE
    getContentPane().add(label, BorderLayout.NORTH);
    numberFrames = 0;
    clock.setInitialDelay(0);
    clock.setCoalesce(true);
    clock.start();
    The JLabel declaration in the constructor means the 'real' JLabel never get initialised, hence the NullPointerException

  • Mulithreading 2 swing timers

    Hi, My first timer updation2 hangs and doesnt do anything. Looks like it is waiting for second thread to be completed or what ever. How can i multi thread these two ?
    public javax.swing.Timer updation2=new javax.swing.Timer(1000,new ActionListener()
              public void actionPerformed(ActionEvent evt)
                   //synchronized(this)
                        try
                             o_val2 = tabModel.getValueAt(indx,2);
                             rate = ((Integer)(o_val2)) - ((Integer)(o_val1));
                             //rate=0;
                             framing.repaint();
                        catch(Exception eee)
         public javax.swing.Timer updation=new javax.swing.Timer(1000,new ActionListener()
              public void actionPerformed(ActionEvent evt)
                   //synchronized(this)
                        try
                             jp.setString(String.valueOf(pack_siz + " Packets/sec"));
                             jp.setValue(pack_siz);                         
                             //JOptionPane.showMessageDialog(null,String.valueOf((Integer)(o_val2)) + "--" + String.valueOf((Integer)(o_val1)));
                             //framing.setTitle(String.valueOf((Integer)(o_val2)) + "--" + String.valueOf((Integer)(o_val1)));
                             //Setting Piegraph values here as it changes
                             long[] data1 = {100,arp_rate,udp_rate};                         
                             l.changeValue(data1);
                             try
                                  if(iptf.getText().length()==0)
                                       if(jp.getValue()==100)          
                                            jp.setForeground(Color.RED);
                                            jp.setString("Above 100 packets/sec");
                                            Toolkit.getDefaultToolkit().beep();
                                       else if(jp.getValue()<100)
                                            jp.setForeground(Color.green);
                                  else if(iptf.getText().length()!=0)
                                       prog_set = Integer.valueOf(iptf.getText());
                                       if(prog_set<=100)
                                            if(jp.getValue()>=prog_set)          
                                                 jp.setForeground(Color.RED);
                                                 jp.setString("Above "+prog_set+" packets/sec");
                                                 Toolkit.getDefaultToolkit().beep();
                                            else if(jp.getValue()<=prog_set)
                                                 jp.setForeground(Color.green);
                                       else if(prog_set>=100)
                                            JOptionPane.showMessageDialog(null,"Value must be between 0 - 100");
                                            iptf.setText("100");
                                  catch(Exception eee)
                                            if(iptf.getText().length()==0)
                                            else
                                                 JOptionPane.showMessageDialog(null,"Alarm value should be numeric");
                                                 iptf.setText("");
                             pBar2.setValue(rate);
                              pBar2.setString(rate + " Packets");          
                             f.repaint();
                             pack_siz=0;
                             arp_rate=0;
                             udp_rate=0;
                             framing.repaint();
                        catch(Exception ee)
         });

    Why would you do that? Just do this...
    javax.swing.Timer = new javax.swing.Timer(1000, this);where your class implements ActionListener (so you can have it--this--as your Listener for your Timer)
    and do the following in your actionPerformed
    public void actionPerformed(ActionEvent e){
      myThread1.myStuff();
      myThread2.myOtherStuff();
    };[How to use Swing Timers|http://java.sun.com/docs/books/tutorial/uiswing/misc/timer.html]

  • Swing Timer issues on a faster machine.

    Hi everyone,
    I'm having some trouble using Swing Timers. I have built a system which uses three javax.swing.Timers, these are as follows:
    timerLeft = new Timer(timerDelay, new ActionListener() {
    public void actionPerformed(ActionEvent evt)
    {if(pathPointerLeft==leftCyclePoints.length) {
    pathPointerLeft=0;
    leftHandX=leftCyclePoints[pathPointerLeft][0];
    leftHandY=leftCyclePoints[pathPointerLeft][1];
    pathPointerLeft++;
    jugglingPanel.repaint();
    timerRight = new Timer(timerDelay, new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
    if(pathPointerRight==rightCyclePoints.length) {
    pathPointerRight=0;
    rightHandX=rightCyclePoints[pathPointerRight][0];
    rightHandY=rightCyclePoints[pathPointerRight][1];
    pathPointerRight++;
    jugglingPanel.repaint();
    myApp.timerBalls = new Timer(myApp.timerDelay, new ActionListener() {
    public void actionPerformed(ActionEvent evt){
    for(int i=0;i<myApp.ballCycleVector.capacity();i++){
    myApp.ballPoints = (int[][])myApp.ballCycleVector.elementAt(i);
    if(myApp.startAnimatingBall){
    if(myApp.ballPoints[myApp.pathPointerBalls][2]==1 && myApp.transitionDone){
    for(int j=0;j<200;j++) {
    if(myApp.ballPoints[myApp.pathPointerBalls][2]!=1) {
    break;
    myApp.pathPointerBalls++;
    if(lastLocationX==myApp.ballPoints[myApp.pathPointerBalls][0] && lastLocationY==myApp.ballPoints[myApp.pathPointerBalls][1]) {
    myApp.pathPointerBalls++;
    if(myApp.pathPointerBalls!=myApp.ballPoints.length) {
    myApp.ballLocations[0]=myApp.ballPoints[myApp.pathPointerBalls][0];
    myApp.ballLocations[1]=myApp.ballPoints[myApp.pathPointerBalls][1];
    lastLocationX= myApp.ballPoints[myApp.pathPointerBalls][0];
    lastLocationY = myApp.ballPoints[myApp.pathPointerBalls][1];
    } else{
    myApp.pathPointerBalls=0;
    for(int j=0;j<200;j++) {
    if(myApp.ballPoints[myApp.pathPointerBalls][2]!=1) {
    break;
    myApp.pathPointerBalls++;
    if(myApp.pathPointerBalls!=0 && myApp.ballPoints[myApp.pathPointerBalls-1][2]==1) {
    myApp.pathPointerBalls++;
    myApp.ballLocations[0]=myApp.ballPoints[myApp.pathPointerBalls][0];
    myApp.ballLocations[1]=myApp.ballPoints[myApp.pathPointerBalls][1];
    lastLocationX= myApp.ballPoints[myApp.pathPointerBalls][0];
    lastLocationY = myApp.ballPoints[myApp.pathPointerBalls][1];
    myApp.pathPointerBalls++;
    if(myApp.pathPointerBalls==myApp.ballPoints.length) {
    myApp.pathPointerBalls=0;
    if(myApp.pathPointerBalls!=0 && myApp.ballPoints[myApp.pathPointerBalls][2]==0 && myApp.ballPoints[myApp.pathPointerBalls-1][2]==1) {
    myApp.transitionDone=true;
    myApp.jugglingPanel.repaint();
    Apologies if these do not coform to standard coding conventions. When I run these on my home PC (P4 2.56GHz, 512MB RAM, 64MB Graphics) it runs beautifully. The same on a laptop (P3 1.8GHz, 512MB RAM, 64MB Graphics card). However, when I run it on the campus machines (3.20GHz, 1.5GB RAM, 128MB Graphics), the animated display (as controlled by the Timers above) stutters and does not remain in sync. I'm guessing that this is because it is being ran on a faster machine. Could anyone suggest a solution to this problem so that the animation remains in sync for a faster machine, or even suggest another reason why this problem is occuring. This is a very important project and I really need to resolve this issue. Thanks in advance.

    The code you posted means nothing:
    a) it is not readable, since you didn't use the "Code Formatting Tags" when you posted the code
    b) its not executable, so we can't see what it is attempting to do.
    c) we don't know the frequency of event firing
    Obviously a faster machine will be able to repaint Components faster then slower machines.
    I use a 3.3Ghz machine and my TimerAnimation example here seems to keep in sync:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=631379

  • Timers

    ok, call me dumb or whatever but i just don't understand timers.
    how would i make a timer to fire every second and add 1 to an integer?
    I've tryed to understand it but there are swing timers and regular timers? and i keep getting confused and all the tuts i keep finding are just so confusing. I'm brand new to java so try not to use too many fancy things if you feel like helping.
    oh, and sorry if i'm in the wrong Forum

    Perhaps a working example would help.
    import java.util.*;
    public class TimerExample {
         public static void main(String[] args) {
              Timer timer = new Timer("Test Timer");
              timer.schedule(new TimerTask() {
                   private int counter = 0;
                   public void run() {
                        counter++;
                        System.out.println(new Date() + ": Counter=" + counter);
                        if (counter >= 10) {
                             System.out.println("Finished.");
                             System.exit(0);
              }, 0, 1000);
    }Prints
    Thu Oct 13 22:18:28 BST 2005: Counter=1
    Thu Oct 13 22:18:29 BST 2005: Counter=2
    Thu Oct 13 22:18:30 BST 2005: Counter=3
    Thu Oct 13 22:18:31 BST 2005: Counter=4
    Thu Oct 13 22:18:32 BST 2005: Counter=5
    Thu Oct 13 22:18:33 BST 2005: Counter=6
    Thu Oct 13 22:18:34 BST 2005: Counter=7
    Thu Oct 13 22:18:35 BST 2005: Counter=8
    Thu Oct 13 22:18:36 BST 2005: Counter=9
    Thu Oct 13 22:18:37 BST 2005: Counter=10
    Finished.BTW: If you are New to Java, in future, I suggest you post to the "New To Java" forum.
    This doesn't mean post this question again as this will only annoy people.

  • Memory leak with 1.6.0_07 in applet using Swing

    Java Plug-in 1.6.0_07
    Using JRE version 1.6.0_07 Java HotSpot(TM) Client VM
    Windows XP - SP2
    I have a commercial application that has developed a memory leak with the introduction of the latest plugin. The applets chew up memory and eventually freeze. They did not before. Using jvisualm I see a build up of native arrays, primarily int[][] and char[]. I'm still investigating. Anyone have a similar experience?
    The Applet uses a swing interface, uses buffered images and swing timers, and regularly performs http connections to the server which result in actions via the SwingUtil.invokeLater() method.

    I am Using Internet Explorer Browser Version 6.0.Huge security hole.
    Its not throwing Error / Exception Wrap a try/catch at the highest level possible.
    Catch 'Throwable'. And log/display it somewhere.

  • How to kill all swing.Timer(s) at end of App

    I am using a javax.swing.Timer to cause text to flash in the text field. However, I noticed that if this timer is running when I stop my app, the timer's thread is still running. It appears that the class that has the timer is not being garbage collected immediately upon application exit. Is there a way to kill all swing timers?
    Thanks,
    John

    No. This is a class whose implementation I was hoping the main application would not have to know about. I was hoping that since I was using swing timers that when the application on which thread the swing timers are executing exited, all the swing timers attached to that application would be stopped.
    Do you have a suggestion how I might be able to do this? I have an application "A" that uses a library class "B" method that happens to start a timer. I do not want "A" to have to explicitly stop "B" when the application is ending. Is there a way I can tag the timer so that it will stop when "A" exits? Or could I somehow link "B" to "A" so that a dispose method on "B" is called when "A" exits or disposes?
    Thanks,
    John

  • How to create a semi circuler slider using java swing or awt

    I am trying to create a Jslider like thing but in semicirculer shape. Thanks in advance for providing any help.

    Is it possible to create such UI in java swing?Just to further illustrate, Swing only provides the raw foundation you need to be able to build a GUI. With the stock components you can create static user interfaces with standard controls. If you want to go further, you need to either find a component that somebody else already wrote, or you go into custom painting as previous posters suggested. To do an animating component for example, you would need all the frames as BufferedImage objects and you would combine custom painting with a Swing timer to update the displayed frame at a specified framerate.
    if you search for "java swing animation" using google, I'm sure you can find the examples you need. And here is the trail about swing timers:
    http://java.sun.com/docs/books/tutorial/uiswing/misc/timer.html

  • Help with making JLabel visible for a few seconds only

    Hello guys,
    I need help with making a JLabel object visible for a few seconds only and disappear when a JButton has been clicked.
    Here is piece of code where I add mouse listener to the JButton object in my case is (jrbFigure1) and
    when is called sets icon and text to the JLabel jlbl object:
    jrbFigure1.addMouseListener(new MouseAdapter() {
    jrbFigure1.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    jlbl.setIcon(cross);
    jlbl.setText(wrong);
    This piece of code is in a switch statement, the statement is in a method.
    The JLabel jlbl object is added in a panel in the constructor of the class.
    I really hope someone could help me on this issue.
    I would like to thank you in advance for any help or advice given.

    Bobson wrote:
    Sorry for posting my issue twice, I thought, I posted it in a wrong forum:)It's OK. We'll ask the mods to delete the other thread.
    I want the label to appear for X seconds when then button is pressed and disappear after that.Then a Swing Timer is what you want to use.
    I need to do this in a number of cases from a switch statement because I several buttons.Better to have several ActionListeners, one for each button or each type of button, rather than one ActionListener with a large switch statement, a so-called switch-board listener. They're messy to debug and upgrade.
    I tried to use Swing Timer, but I cannot set it properly.Go through the Sun Swing tutorial on Swing Timers. It's all outlined for you there: [http://java.sun.com/docs/books/tutorial/uiswing/misc/timer.html]

  • How can I use the same thread to display time in both JPanel & status bar

    Hi everyone!
    I'd like to ask for some assistance regarding the use of threads. I currently have an application that displays the current time, date & day on three separate JLabels on a JPanel by means of a thread class that I created and it's working fine.
    I wonder how would I be able to use the same thread in displaying the current time, date & day in the status bar of my JFrame. I'd like to be able to display the date & time in the JPanel and JFrame synchronously. I am developing my application in Netbeans 4.1 so I was able to add a status bar in just a few clicks and codes.
    I hope somebody would be able to help me on this one. A simple sample code would be greatly appreciated.
    Thanks in advance!

    As you're using Swing, using threads directly just for this kind of purpose would be silly. You might as well use javax.swing.Timer, which has done a lot of the work for you already.
    You would do it something like this...
        ActionListener timerUpdater = new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                // DateFormat would be better, but this is an example.
                String timeString = new Date().toString();
                statusBar.setText(timeString);
                someOtherLabel.setText(timeString);
        new Timer(1000, timerUpdater).start();That code will update the time once a second. If you aren't going to display seconds, you might as well increase the delay.
    The advantage of using a timer over using an explicit thread, is that multiple Swing timers will share a single thread. This way you don't blow out your thread count. :-)

  • Making a digital clock

    Hello, I am learning java and i can make simple programs. i have only taken 2 years of java programmin in school.
    i wanted to try something harder, i don't know if i am ready for it or not.
    I want to make a digital clock in java, and maybe modify it by adding buttons to increase hours and mins.
    I have kinda starte it. but i need a lot of help.

    by the nature of your questions, it appears that you don't know much about swing, timers, and java date time functions. We can't just tell you what you need for your clock, otherwise we'd be building it for you. What you need to do is study these areas and learn for yourself. I suggest that you start with the Sun Java Swing tutorials. Start out here:
    http://java.sun.com/docs/books/tutorial/ui/index.html
    and
    http://java.sun.com/docs/books/tutorial/uiswing/index.html

  • Problem in displaying Icon on JButton

    Hi,
    I have a problem ..
    In my program I have to set Icon for a Jbutton and wait for 2 secs and then remove the Icon..
    I used jb.setIcon(Imageicon) (jb is button reference) to set the icon and jb.setIcon(null) to remove Icon
    Now no Icon is displayed on the button at all....
    My code looks like below mentioned
    jb.setIcon(Imageicon)
    Thread.sleep(2000);
    jb.setIcon(null)
    plz reply mee at the earliest...

    the code snipped is like this..
    the below mentioned code is in actionPerformed method
    pres.setIcon(iial.get(Integer.parseInt(pres.getName())));  //icon for prev is already set
              System.out.println("Icon for pres is set now");
    // need to wait for 2 seconds before both the icons are set to null
              prev.setIcon(null);
              pres.setIcon(null);Here prev and pres are references to JButtons.
    I tried the swing timers but couldnt succeed (i might be implemented them in an incorrect way coz im not familiar with them)
    plz cud you provide me with am example program or a solution to above scenario in a program.....
    Here is the actual program if you want you can run it with keeping atleast 9 images in tn folder and changing maxpics value to 9
    Game.java
    package com;
    //Concentration Game
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.lang.reflect.InvocationTargetException;
    import java.util.ArrayList;
    import java.util.Collections;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    public class Game extends JFrame implements ActionListener {
         private static final long serialVersionUID = 1L;
         public static void main(String args[]) throws InterruptedException,
                   InvocationTargetException {
    System.out.println();
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
             Game cg = new Game();
              cg.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         Logic logic;
         private int[][] arr;
         private Container contents;
         private JLabel controlLabel;
         private JPanel controlPanel;
         private JButton[][] gameBoardLabel;
         private JPanel gamePanel;
         private ArrayList<ImageIcon> iial;
         private boolean isNewAction = true, isFirstAction = true;
         private JButton prev, pres;
         private long s_time, e_time, t_time;
         private int SIZE, arrvalue, maxpics = 51, pairscount, no_of_pairs;
         public Game() {
              super("Concentration Game");
              logic = new Logic();
              logic.populateArray();
              logic.shuffle();
              logic.printArray();
              arr = logic.getArray();
              SIZE = logic.getSize();
              no_of_pairs = (SIZE * SIZE) / 2;
              iial = new ArrayList<ImageIcon>();
              for (int i = 1; i <= maxpics; i++) {
                   iial.add(new ImageIcon(this.getClass().getClassLoader()
                             .getResource("tn/image" + i + ".jpg")));
              Collections.shuffle(iial);
              System.out.println("Completed loading images");
              contents = getContentPane();
              contents.setLayout(new BorderLayout());
              gameBoardLabel = new JButton[SIZE][SIZE];
              new JPanel();
              gamePanel = new JPanel();
              controlPanel = new JPanel();
              gamePanel.setLayout(new GridLayout(SIZE, SIZE, 5, 5));
              controlLabel = new JLabel("Game not started");
              for (int r = 0; r < gameBoardLabel.length; r++) {
                   for (int c = 0; c < gameBoardLabel[r].length; c++) {
                        arrvalue = arr[r][c];
                        System.out.println(arrvalue);
                        if (arr[r][c] == 0) {
                             gameBoardLabel[r][c] = new JButton();
                             gameBoardLabel[r][c].setEnabled(false);
                        else
                             gameBoardLabel[r][c] = new JButton();
                        gameBoardLabel[r][c].addActionListener(this);
                        gameBoardLabel[r][c].setName("" + arrvalue);
                        gameBoardLabel[r][c].setPressedIcon(iial.get(arrvalue));
                        gamePanel.add(gameBoardLabel[r][c]);
              controlPanel.add(controlLabel);
              contents.add(gamePanel, BorderLayout.CENTER);
              contents.add(controlPanel, BorderLayout.SOUTH);
              setSize(400, 500);
              setVisible(true);
              System.out.println(this);
         @Override
         public void actionPerformed(ActionEvent e) {
              JButton jb = (JButton) e.getSource();
              // System.out.println(jb.getName());
              System.out.println(e.getSource());
              if (isFirstAction) {
                   controlLabel.setText("Game Started");
                   s_time = System.currentTimeMillis();
                   isFirstAction = false;
                   System.out.println(this);
              if (isNewAction) {
                   prev = pres = jb;
                   jb.setIcon(iial.get(Integer.parseInt(jb.getName())));
                   isNewAction = false;
                   return;
              prev = pres;
              pres = jb;
              if (pres == prev)
                   return;
              if (pres.getName().equals(prev.getName())) {
                   pres.setIcon(iial.get(Integer.parseInt(pres.getName())));
                   pres.removeActionListener(this);
                   prev.removeActionListener(this);
                   controlLabel.setText("pair matched");
                   resetAttributes();
                   System.out.println("haha----last count==" + ++pairscount);
                   if (pairscount == no_of_pairs) {
                        e_time = System.currentTimeMillis();
                        t_time = (e_time - s_time) / 1000;
                        controlLabel.setText("Game Over in " + t_time + " secs");
                        System.out.println("done");
              System.out.println(pres);
              pres.setIcon(iial.get(Integer.parseInt(pres.getName())));
              controlLabel.setText("pair didn't match");
              System.out.println("pres is set now");
              prev.setIcon(null);
              pres.setIcon(null);
              resetAttributes();
         private void resetAttributes() {
              prev = pres = null;
              isNewAction = true;
    Logic.java
    package com;
    import java.util.ArrayList;
    import java.util.Collections;
    import javax.swing.JOptionPane;
    public class Logic{
          ArrayList<Integer> al;
          int arr[][],arrlist[][],elements=1;
          int SIZE;
    int[][] getArray()
              return arrlist;
    int getSize(){
         return SIZE;
    public static void main(String args[]){
         Logic logic =new Logic();
                logic.populateArray();
               logic.shuffle();
               logic.printArray();
               //System.out.println(logic.elements);
    void populateArray(){
         String input=JOptionPane.showInputDialog(null,"Enter Size of the array (less than 11)" );
         SIZE=Integer.parseInt(input);
         int cnt = 0;
         arrlist=new int[SIZE][SIZE];
         al=new ArrayList<Integer>();
         for (int r = 0; r < SIZE; r++)
              for (int c = 0; c < SIZE; c++)
                   al.add(elements);
                   cnt++;
                   if (cnt == 2)
                        cnt = 0;
                        elements++;
    public  void printArray() {
         for (int i = 0; i < SIZE; i++)
          for (int j = 0; j < SIZE; j++)
            arrlist[i][j] = al.get(j + i * SIZE);
            System.out.print(" "+arrlist[i][j]);
          System.out.println();
    public  void shuffle() {
              Collections.shuffle(al);
         if(SIZE%2!=0)
              int cindex=(SIZE*SIZE)/2; //center index
              int celement=al.get(cindex); //center element
              int lindex=al.indexOf(elements); //index of large element
              //al.remove(cindex);
              //al.add(cindex, 0);
              al.remove(lindex);
              al.add(lindex, celement);
              al.remove(cindex);
              al.add(cindex, 0);
    }

  • Flashing Border in Java ...

    I've spent about three days looking for a way to make a flashing border in Java.
    I want to be able to play the game while this border flashes around the title.
    What is the best recommended method to do this .. and why .. and how? .. Swing timers ? background loop?
    Please help, I'm under the gun on an assignment!

    Yes I know about the Thread problems in swing ... but I'll let you fix up the code if you like - this will at least paint a Border and flash it:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class IsBorderOrNot {
      private JFrame jf;
      private JPanel jp;
      private EmptyBorder eb;
      private MatteBorder mb;
      public IsBorderOrNot() {
        jf = new JFrame("IsBorderOrNot");
        jp = new JPanel();
        eb = new EmptyBorder(5, 5, 5, 5);
        mb = new MatteBorder(5, 5, 5, 5, Color.BLUE);
        jp.add(new JTextArea(10,10));
        jf.getContentPane().add(jp);
        new Thread() {
          public void run() {
            boolean isRunning = true;
            while(isRunning) {
              try {
                jp.setBorder(eb);
                Thread.sleep(100);
                jp.setBorder(mb);
                Thread.sleep(100);
              } catch(InterruptedException ie) {
                System.out.println(ie);
        }.start();
        jf.pack();
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      public static void main(String[] argv) {
    //    new IsBorderOrNot();
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            new IsBorderOrNot();
    }

  • How to improve this timer code ??

    Dear Sir:
    I have following code, it can works and if I remove the line "new JFrame("New Test Timer").setVisible(true);"
    Then It did not show up timer message,
    What is wrong here??
    I want to remove this line but still keep timer moving,
    How to do this??
    Thanks
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JFrame;
    import javax.swing.Timer;
    public class TimerSample {
      public static void main(String args[]) {
        new JFrame("New Test Timer").setVisible(true);
        ActionListener actionListener = new ActionListener() {
          public void actionPerformed(ActionEvent actionEvent) {
            System.out.println("Hello World Timer");
        Timer timer = new Timer(1000, actionListener);
        timer.start();
    }

    Swing timers are called in the event dispatch thread. If you don't start the event dispatch thread (by setting your GUI visible) then they don't get called.
    If you want a timer but you don't want a GUI, then use a java.util.Timer.

  • Wait()

    Hi all,
    I am fairly new to JAVA and I'm just starting to get to grasps with it but I have a problem:
    What i need to do is create a method that will hang the system up for about 5 seconds and then when it has finished waiting it should perform a call to another method. I want to do this without having to implement a thread!
    Is there any way of doing this (Swing timers maybe?)?
    Thanks
    Z

    Is there anyway of doing it without a thread?
    Thread.sleep() doesn't create any new thread, it's just a static method in
    the Thread class ... read the API docs.
    kind regards,
    Jos

Maybe you are looking for

  • How do you change the Apple ID displayed on an iPhone to the correct one?

    I managed to change the Apple ID on all my devices except my wife's iPhone. When it tries to access the iCloud it still asks for out old Apple ID and I can't figure out how to change it. Any advice?

  • How to delete more data?

    I have done everything I can think of, cleaned out my email, emptied the "junk" folder and emptied the "trash" folder I turned the backup off on all my apps except for my camera roll which says consists of only 2.2 GB I deleted all the "cookies and d

  • Camera activityLevel in Air not updated

    Hi, I am facing a problem with the activityLevel property of my camera instance... In Flash (made a short test) it works as aspected, but in my AIR app the activityLevel is always 100... When I setLoopback true and adjust the quality it works, but th

  • Quick Free Way to find out where you Disk Space is being used.

    you can do the same search for files/directory sizes for free with a simple unix command. du -k ~ | sort -n this does your home drive sudo du -k / | sort -n this does the entire hdd du -ak ~ | sort -n this does your home drive with files and director

  • New contacts don't import to Windows Address Book groups

    I'm using Windows Address Book(WAB) as my contacts list on my laptop when I sync with the iPhone. I use WAB because it uses Groups and iPhone accepts it. Today I was browsing through one of my groups on the iPhone and added a new contact, while I was