废弃的方法,应该使用什么替代方法?

5

Java.awt类中的Windows类中的方法show();已经被弃用。我应该使用什么替代品?

package adventure;
import java.awt.*;

import java.awt.image.*;
import java.awt.event.*;
import java.net.URL;
import java.net.MalformedURLException;
import java.io.*;
import java.applet.*;
// Infogar testkommentar mvh Holger 2012-06-20 kl 19.03
public class Adventure extends Frame  {
    private static final long serialVersionUID=100L;
    public Adventure() {        
    setSize(850, 440);    
    World world = new DungeonWorld ( this );        

    Person me = new Person( world, "You", null );    
    show();
    me.goTo("Dungeon");     
    add( new Player( world, me ) );    
    addWindowListener(new MyWindowAdapter ());    
    }

    class MyWindowAdapter extends WindowAdapter {

    public void windowClosing (WindowEvent e) {
        System.exit(0);
    }
    }


    // Load an image from the net, making sure it has already been
    // loaded when the method returns
    public Image loadPicture ( String imageName ) {
    Image im = null;

    // Load the image from the net
    try {
        URL imageSource = new URL( "http://www...xxx/"
                       + imageName );

        try {
        im = createImage( (ImageProducer) imageSource.getContent());
        } catch (IOException e) {}

    } catch (MalformedURLException e ) { }

    // Wait to ensure that the image is loaded
    MediaTracker imageTracker = new MediaTracker( this );
    imageTracker.addImage( im, 0 );
    try {
        imageTracker.waitForID( 0 );
    }
    catch( InterruptedException e ) { }

    return im;
    }


    // Load and play a sound from /usr/local/hacks/sounds/

    public void playSound (String name) {
    URL u = null;

    try {
        u = new URL("file:" +  "/usr/local/hacks/sounds/" + name + ".au");
    } catch (MalformedURLException e ) { }

    AudioClip a = Applet.newAudioClip(u);
    a.play();
    }

    public static void main (String[] args) {       
    System.out.println("test"); 
      new Adventure();
    }
}

2
正如您所知,该方法已被弃用,您必须对API有一定的访问权限。如果您阅读第一个短语,您将会知道应该使用什么替代方法... - brimborium
2
我猜你应该先开始阅读Javadoc文档。 - Buhake Sindi
3
我知道有文档可供参考,但我想要一个人的回答。有时候人比文档更懂情况。例如,这里有一些未记录的东西。感谢您的评论。 - Niklas Rosencrantz
2个回答

24

让我们查看Java API中Window#show()的说明:这里

@Deprecated
public void show()

已废弃。自JDK版本1.5起,已被setVisible(boolean)替换。

使窗口可见。如果窗口及/或其所有者尚未显示,则都将显示出来。在使窗口可见之前,将对其进行验证。如果窗口已经可见,则会将其置于最前面。

因此,您应该使用Window#setVisible(boolean) - 对于show()方法,请使用setVisible(true)

编辑

在某些环境中,仅用setVisible(true)替换show()可能会更改应用程序的行为。这种情况发生在您编写的Window子类覆盖了show()(同样适用于hide())时。

因此,在您的代码示例中,setVisible(true)show()完全相同。但通常请确保没有人覆盖show(),否则使用setVisible(true)时将不再执行覆盖的方法。在这种情况下,您还需要更改覆盖的方法。


5

如果您查看API,您会看到:

void show()       

已过时。自JDK 1.5版本起,被setVisible(boolean)所取代。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接