Results 1 to 12 of 12
  1. #1
    danborgir is offline Member
    Join Date
    Jan 2011
    Posts
    26
    Rep Power
    0

    Default setting JButton setEnabled() outside of main class

    Hi guys,

    I am developing a program called Faceblock to block Facebook.

    When a user clicks the 'block facebook button' and initiates the block a class time is called and times the block (however long the user specified). Once this has been called the JButton is set to disabled.

    Java Code:
    button.setEnable(false);
    in the class time there is a method using java Timer, (I know it is quite primitive) that times how long the user inputted to block facebook and then when that time ends it runs the configuration to unblock facebook inside an actionlistener.

    Inside this configuration I create a new instance of a class called setButton.

    Java Code:
    new setButton();
    The setButton class includes this code:

    Java Code:
    public class setButton extends Faceblock {
    	public setButton() {
    	
    	button.setEnabled(true);
    	
    	
    	}
    }
    Inside the main global Faceblock class I have created the instance of the button:

    Java Code:
    	final JButton button = new JButton("BLOCK FACEBOOK");
    Then inside the class runner (this class does everything) the button is created.

    Java Code:
    public class Faceblock {
    
    
    	int timeResultInt;
    	int possibleTime;
    	final JButton button = new JButton("BLOCK FACEBOOK");
    	
    	
    void runner()
    {
    // all other code
    inside runner if I set the button
    Java Code:
    button.setEnabled(false);
    It will disable the button however using my class setButton it wont set it back to enabled :(

    If you guys want all the code I am happy to supply if need be...

    Thanks in advance,

    Dan

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by danborgir View Post
    If you guys want all the code I am happy to supply if need be...
    You're not running some long-running process on Swing's EDT (event dispatch thread) by chance are you?

    Speaking for myself, I wouldn't want all the code, but I'd like a small compilable runnable program that doesn't block anything (perhaps instead has a Thread.sleep to simulate), but that shows your problem.

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Hm, looking again at your post, do you have two same-named variables that hold similar instances of the JButton? If so, making changes to the non-displayed JButton will of course have no effect on the displayed one. I think you may think that by extending a call you have control over variables in other instances of the class, and this simply doesn't work and is not how inheritance works.

    I think we need to see more code.

  4. #4
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,184
    Rep Power
    19

    Default

    In this particular case, it looks more likely that a blocking method is being called on the EDT rather than than a long-running process.

    db

  5. #5
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,184
    Rep Power
    19

    Default

    This also looks like a gross misuse of inheritance
    Java Code:
    public class setButton extends Faceblock {
    db

  6. #6
    danborgir is offline Member
    Join Date
    Jan 2011
    Posts
    26
    Rep Power
    0

    Default

    Faceblock class
    Java Code:
    /*    Faceblock 0.2
          Copyright (C) 2011 Daniel Pilch
    
          This program is free software: you can redistribute it and/or modify
          it under the terms of the GNU General Public License as published by
          the Free Software Foundation, either version 3 of the License, or
          (at your option) any later version.
    
          This program is distributed in the hope that it will be useful,
          but WITHOUT ANY WARRANTY; without even the implied warranty of
          MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
          GNU General Public License for more details.
    
          You should have received a copy of the GNU General Public License
          along with this program.  If not, see <http://www.gnu.org/licenses/>. */
    
    
    /* 0.3 Updates:
    
    // Added a drop down list to block time & custom time
    // Set warning for if hosts file is not editable
    */	  
    
    /* TO DO 
    
    // make unblock button enable after unblock
    // JOption box asking how long faceblock wants to be blocked for cancel doesn't work
    // add unblock button
    // add registration
    // add faceblock group to button
    */
    
    import java.io.*;
    import java.io.File;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.InputEvent;
    import java.awt.TrayIcon;
    import javax.swing.Icon;
    import java.util.regex.*;
    
    
    public class Faceblock {
    
    
    	int timeResultInt;
    	int possibleTime;
    	final JButton button = new JButton("BLOCK FACEBOOK");
    	
    	
    void runner()
    {
    // Clear any instances of faceblock from hosts
    	new clearInstances();
    	new ExecCommand();
    	
    // Alert beep
    	Toolkit tk = Toolkit.getDefaultToolkit();
        tk.beep();
    	
    	
    // Create new frame & set default close  
       final JFrame frame = new JFrame("Faceblock 0.2");
        
    	
    // Add Systemtray 
    		
              final SystemTray tray = SystemTray.getSystemTray();
              Image image = Toolkit.getDefaultToolkit().getImage("http://www.java-forums.org/images/tray.png");
    							PopupMenu popup = new PopupMenu();
    							MenuItem item = new MenuItem("Exit");
    							popup.add(item);
    		  final TrayIcon trayIcon = new TrayIcon(image, "Faceblock", popup);
    							trayIcon.addActionListener(new ActionListener() {
    							public void actionPerformed(ActionEvent e) {
    							frame.setVisible(true);
    							
    
    
    							}	});
    							
    							item.addActionListener(new ActionListener() {
    		  public void actionPerformed(ActionEvent e) {
    							tray.remove(trayIcon);	
    							System.exit(0);
    							}	});
    							
    							
    											
            
     // SYSTEM EXIT & MINIMISE SETTINGS
    
    frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    
    	final JLabel check = new JLabel("Do you want to quit Faceblock? \n Remember if Facebook is blocked it will be until you have completed another block cycle!");
    	frame.addWindowListener(new WindowAdapter() {
    		public void windowClosing(WindowEvent we) {
    			if( JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(frame, check)) {
    				System.exit(0);
    				}
    			}	
    			public void windowClosed(WindowEvent we) {}
    			public void windowDeactivated(WindowEvent we) {}
    			public void windowOpened(WindowEvent we) {}
    		}); 
    	
    // Create JPanel
    	JPanel panel = new JPanel(new BorderLayout());
    	
    // Set layout
    	FlowLayout layout = new FlowLayout();
    	
    
    	
    // Create Menu Bar
    	JMenuBar menuBar = new JMenuBar();
    	
    // Faceblock icon
    	final ImageIcon icon = new ImageIcon("http://www.java-forums.org/images/face.png");
    	JLabel fbimage = new JLabel(icon);
    
    //Faceblock banner
    	final ImageIcon bannerIcon = new ImageIcon("http://www.java-forums.org/images/banner.png");
    	JLabel fbanner = new JLabel(bannerIcon);
    	
    // Top left icon
    	ImageIcon topimage = new ImageIcon("http://www.java-forums.org/images/lefticon.png");
    	
    // Create Faceblock Title
    	JLabel title = new JLabel("Faceblock");
    		
    // Create FILE MENU	
    	JMenu menu = new JMenu( "File" );
    	menuBar.add( menu );
    	
    // Create Exit item 
    	JMenuItem exit = new JMenuItem( "Exit" );
    	ActionListener exitAction = new ActionListener()	{
    		public void actionPerformed( ActionEvent actionEvent ) {
    		
    		//ADD CONFIRM EXIT HERE
    		final JLabel check = new JLabel("Do you want to quit Faceblock? \n Remember if Facebook is blocked it will be until you have completed another block cycle!");
    
    		if( JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(frame, check)) {
    				System.exit(0);
    				}
    		}
    	};	
    	exit.addActionListener(exitAction);
    	menu.add( exit );
    	
    // Install the menu bar into the frame
    	frame.setJMenuBar( menuBar );
    	
    // Create HELP menu
    	JMenu helpMenu = new JMenu( "Help" );
    	menuBar.add( helpMenu );
    	
    // Create HELP item
    	JMenuItem help = new JMenuItem( "Help" );
    	ActionListener helpAction = new ActionListener()	{
    		public void actionPerformed( ActionEvent actionEvent ) {
    		String url = "http://faceblock.co.uk/faceblockman/"; 
    		try	{
    		java.awt.Desktop.getDesktop().browse(java.net.URI.create(url));
    		} catch (IOException ex) { 
    		 System.err.println(); }
    		}
    	};
    	
    	help.addActionListener( helpAction );
    	helpMenu.add( help );
    	
    // Create ABOUT & ADD LIKE BUTTON
    // LIKE BUTTON
    
    	final ImageIcon likeButton = new ImageIcon("http://www.java-forums.org/images/like.png");
    	JButton likeImage = new JButton(likeButton);
    
    		likeImage.addMouseListener(new MouseAdapter() {
    		public void mouseClicked(MouseEvent e) {
    			
    		
    		String url = "http://www.facebook.com/pages/Faceblock/196227340414887"; 
    		try	{
    		java.awt.Desktop.getDesktop().browse(java.net.URI.create(url));
    		} catch (IOException ex) { 
    		 System.err.println(); }
    		} });
    
    
    
    	JMenuItem about = new JMenuItem( "About" );
    	ActionListener aboutAction = new ActionListener()	{
    		public void actionPerformed( ActionEvent actionEvent ) {
    		JOptionPane fr = new JOptionPane();
    		JOptionPane.showMessageDialog(fr, "Faceblock \u00a9 2011 - Dan Pilch\nLogo design by Jason Mortimer", "Faceblock - Please donate", JOptionPane.INFORMATION_MESSAGE,
        icon);
    	
    		
    
    		}
    	};	
    	about.addActionListener( aboutAction );
    	helpMenu.add( about );
    
    // Create FEEDBACK item
    	JMenuItem feedback = new JMenuItem( "Feedback" );
    	ActionListener feedbackAction = new ActionListener()	{
    		public void actionPerformed( ActionEvent actionEvent ) {
    		String url = "http://faceblock.co.uk/report.php"; 
    		try	{
    		java.awt.Desktop.getDesktop().browse(java.net.URI.create(url));
    		} catch (IOException ex) { 
    		 System.err.println(); }
    		}
    	};
    	feedback.addActionListener( feedbackAction );
    	helpMenu.add( feedback );
    	
    	
    // BUTTON PRESSED	
    	
        ActionListener actionListener = new ActionListener() {
          public void actionPerformed(ActionEvent actionEvent) {
    	  
    //validation	    		
    		Object[] possibleValues = { "1 Minute", "5 Minutes", "15 Minutes", "30 Minutes", "1 Hour", "Other" };
    		Object selectedValue = JOptionPane.showInputDialog(null, "How Long do you want to block Facebook?", "Block Time", JOptionPane.INFORMATION_MESSAGE, null, possibleValues, possibleValues[0]);
    		
    				
    		if(selectedValue == null) {
    			return;
    			} else 
    		if(selectedValue == "1 Minute") { 
    			possibleTime = 1;
    			timeResultInt = possibleTime;
    			if(JOptionPane.showConfirmDialog(new JFrame(),
    			"Are you sure you want to block Facebook for " + possibleTime + " Minute?","Faceblock",
    			JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION);	
    			} else 
    		if(selectedValue == "5 Minutes") { 
    			possibleTime = 5; 
    			timeResultInt = possibleTime;
    			if(JOptionPane.showConfirmDialog(new JFrame(),
    			"Are you sure you want to block Facebook for " + possibleTime + " Minutes?","Faceblock",
    			JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION);	
    			} else
    		if(selectedValue == "15 Minutes") { 
    			possibleTime = 15; 
    			timeResultInt = possibleTime;
    			if(JOptionPane.showConfirmDialog(new JFrame(),
    			"Are you sure you want to block Facebook for " + possibleTime + " Minutes?","Faceblock",
    			JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION);	
    			} else
    		if(selectedValue == "30 Minutes") { 
    			possibleTime = 30;
    			timeResultInt = possibleTime;
    			if(JOptionPane.showConfirmDialog(new JFrame(),
    			"Are you sure you want to block Facebook for " + possibleTime + " Minutes?","Faceblock",
    			JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION);	
    			} else
    		if(selectedValue == "1 Hour") { 
    			possibleTime = 60;
    			timeResultInt = possibleTime;
    			if(JOptionPane.showConfirmDialog(new JFrame(),
    			"Are you sure you want to block Facebook for " + "1 Hour?","Faceblock",
    			JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION);	
    			} else
    			
    		if(selectedValue == "Other") { 
    			
    		JFrame timeInput = new JFrame();
    		String timeResult = JOptionPane.showInputDialog(timeInput,"Enter ammount of time in minutes to block.\ne.g. 15 = 15 minutes:");
    		Pattern p = Pattern.compile("[A-Z,a-z,&%$#@!()*^]");
    		Matcher m = p.matcher(timeResult);
    		
    // Convert String of numbers to int for time()		
    			
    		if(m.find()) { 
    		JOptionPane error = new JOptionPane();
    		
    		JOptionPane.showMessageDialog(error, "You entered an incorrect value");
    		timeResult = JOptionPane.showInputDialog(timeInput,"Enter ammount of time in minutes to block.\ne.g. 15 = 15 minutes:");
    		} 
    		
    		timeResultInt = Integer.parseInt(timeResult);
    		
    // Confirm BLOCK TIME	
    		if(JOptionPane.showConfirmDialog(new JFrame(),
    			"Are you sure you want to block Facebook for " + timeResult + " Minute(s)?","Faceblock",
    			JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION);
    			
    						
    		} 
    		
    			
    			
    		
    		
    		
    		
    // Add hosts info to block Facebook		
    		
    		File TestWrite = new File("C:\\Windows\\System32\\drivers\\etc\\hosts");
    		if(!TestWrite.canWrite()) {
    		JOptionPane adminerror = new JOptionPane();
    		JOptionPane.showMessageDialog(adminerror, "You have not ran Faceblock as an Administrator!", "Error", JOptionPane.ERROR_MESSAGE);
    		return;
    		} else { 
    		try {
    		FileWriter fstream = new FileWriter("c:\\Windows\\System32\\drivers\\etc\\hosts", true);
            BufferedWriter out = new BufferedWriter(fstream);
    		out.write("\n178.63.127.253 facebook.com \n178.63.127.253 www.facebook.com\n178.63.127.253 www.facebook.com/home.php?\n178.63.127.253 m.facebook.com");
    		out.close();
    		} catch  (IOException ex) { 
    		System.err.println();
    		JOptionPane Eerror = new JOptionPane();
    		JOptionPane.showMessageDialog(Eerror, "Unknown Error, please restart the program.", "Error", JOptionPane.ERROR_MESSAGE);
    		return;	}  } 
    
    // ExecCommand FLUSHES DNS			
    		new ExecCommand();
    		Toolkit tk = Toolkit.getDefaultToolkit();
    		tk.beep();
    		
    // Restart browser info box		
    		if(JOptionPane.showConfirmDialog(new JFrame(),
    			"Do you want to restart your browser now?","Faceblock",
    			JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)	
    
    // Kill Browser IF yes is selected			
    			new ExecKill();
    
    // Start time functions and pass time and hide faceblock frame
    
    		if(frame.isShowing() && timeResultInt == 1)	{
    			frame.setVisible(false);
    			
    			trayIcon.displayMessage("Faceblock minimised", 
               "Facebook has been blocked for " + timeResultInt + " minute",
               TrayIcon.MessageType.INFO);
    		   time timeFunction = new time();
    			timeFunction.timer(timeResultInt);
    			button.setEnabled(false);
    		} else { 
    		if(frame.isShowing())	{
    			frame.setVisible(false);
    			
    			trayIcon.displayMessage("Faceblock minimised", 
               "Facebook has been blocked for " + timeResultInt + " minutes",
               TrayIcon.MessageType.INFO);
    		   time timeFunction = new time();
    			timeFunction.timer(timeResultInt);
    			button.setEnabled(false);
    		   }}
    		
    			
          }
        };
    	
    		button.addActionListener(actionListener);
    
    
    		Container contentPane = frame.getContentPane();
    		contentPane.setLayout(new FlowLayout());
    	
    		contentPane.add(fbimage);
    		contentPane.add(fbanner);
    		contentPane.add(button);
    		contentPane.add(likeImage);
    		frame.setSize(310, 180);
    		frame.setVisible(true);
    		frame.setResizable(false);
    		frame.setIconImage(new ImageIcon("http://www.java-forums.org/images/tray.png").getImage());
    
    		try{
    		tray.add(trayIcon);}
    		catch(Exception e)
    		{}
    		
    
    		// Center screen
    // Get the size of the screen
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        
    // Determine the new location of the window
        int w = frame.getSize().width;
        int h = frame.getSize().height;
        int x = (dim.width-w)/2;
        int y = (dim.height-h)/2;
        
    // Move the window
        frame.setLocation(x, y);
    	
    
    
    //  To tell user faceblock has been minimized
    	
    	}
    	
    
    	
      public static void main(String args[]) throws Exception
      {
    	Faceblock myrun = new Faceblock();
    	myrun.runner();
    	} 	
    	}
    Time class:

    Java Code:
    import java.util.*;
    import java.util.Scanner;
    import java.io.*;
    import sun.audio.*;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.Timer;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    public class time extends Faceblock {
    
    	
    
    
    	public void timer(int i) {
    	
    				
    
    		int sleepTime = i * 60000;
    								
    		ActionListener taskPerformer = new ActionListener() {
    		public void actionPerformed(ActionEvent evt) {
    		FileUtil util = new FileUtil();
            util.removeLineFromFile("c:\\Windows\\System32\\drivers\\etc\\hosts", "178.63.127.253 facebook.com");
            util.removeLineFromFile("c:\\Windows\\System32\\drivers\\etc\\hosts", "178.63.127.253 www.facebook.com");    
            util.removeLineFromFile("c:\\Windows\\System32\\drivers\\etc\\hosts", "178.63.127.253 www.facebook.com/home.php?");  
    		util.removeLineFromFile("c:\\Windows\\System32\\drivers\\etc\\hosts", "178.63.127.253 m.facebook.com");
    
    		System.out.println("Facebook Unblocked");
    		
    // ExecCommand FLUSHES DNS			
    		new ExecCommand();
    		Toolkit tk = Toolkit.getDefaultToolkit();
    		tk.beep();
    		
    // Restart browser info box		
    		if(JOptionPane.showConfirmDialog(new JFrame(),
    			"Facebook unblocked! Do you want to restart your browser now?","Facebook Unblocked",
    			JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)	
    			new setButton();
    			
    			
    			
    // Kill Browser IF yes is selected			
    			new ExecKill();
    			new setButton();
    						
    	}
    		
    	};
    
    				Timer time = new Timer(sleepTime, taskPerformer);
    				time.setRepeats(false);
    				time.start();
    				
    				
    				
    		
    	}
    	
    	
    	
    	  
          
      
    }
    setButton class:

    Java Code:
    public class setButton extends Faceblock {
    	public setButton() {
    	
    	button.setEnabled(true);
    	
    	
    	}
    }
    Sorry for so much code!!!

    The other classes used are of no real use to yourselves, only if you're compiling the code yourself.

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Yeah, Darryl and my fears are correct at least for one of your problems -- you are misusing inheritance. While setButton extends Faceblock, any instances of setButton are completely distinct from instances of Faceblock and calling methods that change the button state in setButton will have absolutely no effect on your visualized instances in your Faceblock object. If you want another class to change the state of a field of a Faceblock instance, that other class must have a reference to that instance, not a completely distinct other object from an inherited class.

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Next I have to wonder what new ExecCommand() and new ExecKill() do. Both Darryl and I fear that you may be running long processes here on the Swing event dispatch thread effectively freezing your application. Read up on Concurrency in Swing for more on this.

  9. #9
    danborgir is offline Member
    Join Date
    Jan 2011
    Posts
    26
    Rep Power
    0

    Default

    ExecKill:

    Java Code:
    import java.io.*;
    public class ExecKill {
    public ExecKill() {  
            try {  
                 String firefox = "taskkill /IM firefox.exe "; 
    			 String iexplore = "taskkill /IM iexplore.exe ";
    			 String chrome = "taskkill /IM chrome.exe ";
    			 String safari = "taskkill /IM safari.exe ";
    			 
    			 
    			 
                 Process processff = Runtime.getRuntime().exec(firefox);  
    			 Process processie = Runtime.getRuntime().exec(iexplore);  
    			 Process processchr = Runtime.getRuntime().exec(chrome);  
    			 Process processsaf = Runtime.getRuntime().exec(safari);
    
    			 
    			 
    			 System.out.println("Executing command: " + firefox + iexplore + chrome + safari);
    		
    
                } catch (IOException e) {  
                  System.err.println(e);  
             }  
          }  
    	  
    	 }
    ExecCommand:

    Java Code:
    import java.io.*;
    public class ExecCommand {
    public ExecCommand() {  
            try {  
                 String command = "ipconfig /flushdns";  
                 Process process = Runtime.getRuntime().exec(command);  
    			 System.out.println("Executing command: " + command);  
                } catch (IOException e) {  
                  System.err.println(e);  
             }  
          }  
    	  
    	 
    }
    Both these classes run their processes and finish.

    How could I create a reference to the instance of button in the Time class? Sorry for what seems like quite a trivial question however I am still pretty new to java and yes it does look like I have misused inheritance by extending Faceblock!

  10. #10
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,184
    Rep Power
    19

    Default

    Additional to anything said so far: read and implement all the recommendations in all sections of When Runtime.exec() won't

    db

  11. #11
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Suppose I had a class ButtonPanel that had a JButton, button, that I wanted outside classes to be able to enable/disable, I'd give that class a public method that would allow it to do this:

    Java Code:
    class ButtonPanel extends JPanel {
       //...
    
       private JButton button = new JButton("Do it");
    
       // ...
       
       public void setButtonEnabled(boolean enabled) {
          button.setEnabled(enabled);
       }
       
    }

    Then in the other class that needs to re-enable the button, I'd pass a reference to this class's object into it, say in a constructor parameter. For example:

    Java Code:
    class MyTimerListener implements ActionListener {
       ButtonPanel btnPanel;
       
       public MyTimerListener(ButtonPanel btnPanel) {
          this.btnPanel = btnPanel; // set the reference in the constructor
       }

    I could then use these classes like so:

    Java Code:
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.*;
    
    public class DisableAndEnableButton {
    
       private static void createAndShowUI() {
          JFrame frame = new JFrame("Disable/Enable");
          frame.getContentPane().add(new ButtonPanel());
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          java.awt.EventQueue.invokeLater(new Runnable() {
             public void run() {
                createAndShowUI();
             }
          });
       }
    }
    
    class ButtonPanel extends JPanel {
       private static final int MAX = 10;
       private JButton button = new JButton("Do it");
       private JSpinner spinner = new JSpinner(new SpinnerNumberModel(1, 1, MAX, 1));
       
       public ButtonPanel() {
          button.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                int delay = ((Integer)spinner.getValue()).intValue() * 1000;
    
                // **** here I create the object, passing in the reference to the ButtonPanel
                new Timer(delay, new MyTimerListener(ButtonPanel.this)).start();
                button.setEnabled(false);
             }
          });
          add(new JLabel("Seconds to disable:"));
          add(spinner);
          add(Box.createHorizontalStrut(10));
          add(button);
       }
       
       public void setButtonEnabled(boolean enabled) {
          button.setEnabled(enabled);
       }
       
    }
    
    class MyTimerListener implements ActionListener {
       private ButtonPanel btnPanel;
       
       public MyTimerListener(ButtonPanel btnPanel) {
          this.btnPanel = btnPanel;
       }
    
       public void actionPerformed(ActionEvent e) {
          btnPanel.setButtonEnabled(true);
          ((Timer)e.getSource()).stop();
       }
    }

  12. #12
    danborgir is offline Member
    Join Date
    Jan 2011
    Posts
    26
    Rep Power
    0

    Default

    Thanks a lot guys! Your knowledge is incredibly valuable and I really appreciate your help, I'll try out your recommendations and post back the results!:)

Similar Threads

  1. JButton setEnabled
    By kbro3 in forum New To Java
    Replies: 5
    Last Post: 03-23-2011, 12:53 AM
  2. Running main method class from another main class
    By tlrocketman in forum New To Java
    Replies: 3
    Last Post: 12-06-2010, 08:30 AM
  3. Setting up main method
    By katherine_93 in forum New To Java
    Replies: 2
    Last Post: 03-08-2010, 05:57 AM
  4. Replies: 3
    Last Post: 05-25-2009, 03:33 AM
  5. Replies: 4
    Last Post: 02-26-2009, 11:46 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •