1

Lets say I created a thread with button in twitterpanel class e.g

public class twitterpanel extends javax.swing.JFrame {
Thread oto;
/....
 private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { 
        oto = new Thread(new Runnable() {

        @Override
        public void run() {
            ArrayList<String> textler = new ArrayList<String>();
            textler.add(jTextField1.getText());
            textler.add(jTextField2.getText())

            new Twitter(textler);

        }
    });
    oto.start();
} }

Method is, e.g :

  public void twittermethod() { 
   for (;;) {
    System.out.println("Close me please..");
   }

  }

And i want to close this Thread with another button and the button is in twitterpanel class . Maybe it is simple but i couldn't find anything, like my brain stopped. Hope i could explain myself clearly. Thanks in advance..

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Farukest
  • 1,498
  • 21
  • 39

2 Answers2

3

Use Swing Timer that is most suitable for swing application in two ways:

  • To perform a task once, after a delay.
  • To perform a task repeatedly.

Read more How to Use Swing Timers

Simply call timer#start() and timer#stop()

Sample code:

// wait for 2 seconds
Timer timer=new Timer(2000,new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent arg0) {
       // do your action here
    }
});
timer.setRepeats(false); // if needed then repeat it
timer.start();

Read more...

Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76
3

Again, as noted in your prior deleted question,

  1. Your code is not thread safe as you are making Swing calls that change the state of Swing components off of the Swing event thread.
  2. Your question is an XY Problem in that you are asking about specific code solutions that may be wrong, and you have not discussed your over all goal.

    • You will want to read this article about Swing thread safety: Concurrency in Swing.
    • You should consider going into greater detail into just what behaviors you'd like your users to experience with your GUI, so we can perhaps be able to provide a better more robust solution.
    • For better help, consider creating and posting a minimal example program, code for us to review, test, and possibly fix.

For instance, you could often start and stop Threads with a SwingWorker background thread. For details on how to use this tool, please read the SwingWorker tutorial which I've linked to above, and which you can find here.

An example of a minimal Swing program with a SwingWorker that sort of does what you're trying to do (I think!):

import java.awt.event.*;
import javax.swing.*;

@SuppressWarnings("serial")
public class StopThreadGui extends JPanel {
   private JTextField field1 = new JTextField("Hello", 10);
   private JTextField field2 = new JTextField("Goodbye", 10);
   private JButton startButton = new JButton(new StartAction("Start", KeyEvent.VK_S));
   private JButton endButton = new JButton(new EndAction("End", KeyEvent.VK_E));
   private MySwingWorker myWorker;

   public StopThreadGui() {
      add(field1);
      add(field2);
      add(startButton);
      add(endButton);
   }

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

      JFrame frame = new JFrame("StopThreadGui");
      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();
         }
      });
   }

   private class StartAction extends AbstractAction {
      public StartAction(String name, int mnemonic) {
         super(name);
         putValue(MNEMONIC_KEY, mnemonic);
      }

      @Override
      public void actionPerformed(ActionEvent evt) {
         if (myWorker != null && !myWorker.isDone()) {
            return;
         }
         String text1 = field1.getText();
         String text2 = field2.getText();

         myWorker = new MySwingWorker(text1, text2);
         myWorker.execute();
      }
   }

   private class EndAction extends AbstractAction {
      public EndAction(String name, int mnemonic) {
         super(name);
         putValue(MNEMONIC_KEY, mnemonic);
      }

      @Override
      public void actionPerformed(ActionEvent evt) {
         if (myWorker == null || myWorker.isDone()) {
            return;
         }
         myWorker.cancel(true);
      }
   }

}

class MySwingWorker extends SwingWorker<Void, Void> {
   private static final long SLEEP_TIME = 400;
   private String text1;
   private String text2;

   public MySwingWorker(String text1, String text2) {
      this.text1 = text1;
      this.text2 = text2;
   }

   @Override
   protected Void doInBackground() throws Exception {
      boolean foo = true;
      while (foo) {
         System.out.printf("Text1: %s;   Text2: %s%n", text1, text2);
         System.out.println("Close me please..");
         Thread.sleep(SLEEP_TIME);
      }
      return null;
   }
}
Community
  • 1
  • 1
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Just a question, though not related, how can one see previously deleted questions? Only the __trusted users like yourself__ or a __non-trusted user like me__ too can find them on the site!!! I enjoyed reading this __XY-Problem__ thingy long before, from one of your posts. – nIcE cOw Jul 12 '14 at 08:35
  • thank you for your answer.Swing worker.. I understood, its like Android `doingBackground()`, `onPreExecute()`, `OnPostExecute()`. but for me your example is to complicated because i'm new at java. But now i'll look at SwingWorker first.. and then try to understand your example. thank you again. – Farukest Jul 12 '14 at 10:36
  • @nIcEcOw: I had previously flagged his deleted question as a "favorite" prior to deletion to check on its status. – Hovercraft Full Of Eels Jul 12 '14 at 11:10