开发者

How can I create a short version of this code block

开发者 https://www.devze.com 2023-03-08 01:25 出处:网络
new java.util.Timer().schedule( new java.util.TimerTask() { 开发者_如何学JAVA@Override public void run() {
new java.util.Timer().schedule(
  new java.util.TimerTask() {
开发者_如何学JAVA    @Override
    public void run() {
      // my code is here card.getJLabel().setVisible(false);
      }
    }, 3000 // < my parameter);

How can I create a short function of this one, I use it in different functions so it would be clean if I can create short version of this one.

One more, I'm quite new to java, so what material i should read to know more about this particular subject. Thanks man :)


Presuming what can change from one call to the other is the card to be hidden and the delay before it gets hidden :

public void hideCard(MyCard card, long delay){
  new java.util.Timer().schedule(
     new java.util.TimerTask() {
       @Override
       public void run() {
         card.getJLabel().setVisible(false);
       }
     }, delay);
  }

Here is a good start to refactoring, and refactoring with Eclipse.


Just put that snippet of code in a separate method and call the method each time you want to run the snippet of code:

public void scheduleHideCard() {
    new java.util.Timer().schedule(
        new java.util.TimerTask() {
            @Override
            public void run() {
                // my code is here card.getJLabel().setVisible(false);
            }
        }, 3000 // < my parameter);
}

...and call the method by doing scheduleHideCard().

If you're using Eclipse you can even select the snippet of code and do Source -> Refactor -> Extract Method and it will take care of extracting the appropriate parameters for you.

As a side-note: If you're using several classes from the java.util package, you may mant to import those classes at the top of the file:

import java.util.*;


If I understand correctly, you want to extract this code into a separate method like this?

void scheduleSomeActivity() {
  new java.util.Timer().schedule(...);
}

or possibly turning e.g. the delay into a parameter:

void scheduleSomeActivityWithDelay(long delay) {
  new java.util.Timer().schedule(..., delay);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消