为什么我的布局中会显示我的图像?

时间:2015-08-08 20:57:46

标签: java image applet

我正在使用Java进行这个项目,需要一个图像来显示,还有一个生物和一个播放歌曲/声音的按钮。我完成了按钮和bio,但我可以弄清楚如何在布局的NORTH部分显示图像以及中间部分的按钮,任何帮助都会很棒。

这是我的错误:Container类型中的方法add(String,Component)不适用于参数(Image,String)

public void init() {
    // image
    myPicture = getImage(getCodeBase(), "sample.jpg");
    // THIS IS WHERE MY PROBLEM IS vvvvvvv      
    add(myPicture, BorderLayout.NORTH);

    add(bio);

    paneSouth.add(play);
    getContentPane().add(paneSouth, BorderLayout.SOUTH);
    mySound = getAudioClip(getDocumentBase(), "sample.wav");
    play.addActionListener(new  ActionListener() {
        public void actionPerformed(ActionEvent e) {
            mySound.play();
        }});    
}

public void paint(Graphics g){
    g.drawImage(myPicture, 10, 10, this);
}

private JPanel paneSouth = new JPanel();
private TextArea bio = new TextArea("bio thing");
private JButton play = new JButton("Play");
private AudioClip mySound;
private Image myPicture;

}

编辑:

public void init() {
    // image
    ImageIcon icon = new ImageIcon(myPicture);
    JLabel myLabelImage = new Image(icon);
    add(myLabelImage, BorderLayout.NORTH);

    // bio
    add(bio);
    add(bio, BorderLayout.CENTER);

    // sound
    paneSouth.add(play);
    getContentPane().add(paneSouth, BorderLayout.SOUTH);
    mySound = getAudioClip(getDocumentBase(), "sample.wav");
    play.addActionListener(new  ActionListener() {
        public void actionPerformed(ActionEvent e) {
            mySound.play();
        }});    
}

private JPanel paneSouth = new JPanel();
private TextArea bio = new TextArea("bio.");
private JButton play = new JButton("Play");
private AudioClip mySound;
private Image myPicture;
}

1 个答案:

答案 0 :(得分:3)

我猜您使用的是JApplet,因为您使用的是Swing组件。尝试这样的事情:

public class ImageApplet extends JApplet {

    private JPanel paneSouth = new JPanel();
    private JTextArea bio = new JTextArea("bio thing");
    private JButton play = new JButton("Play");
    private Image myPicture;
    private ImageIcon icon;
    private JLabel label;

    public void init() {
        try {
            URL pic = new URL(getDocumentBase(), "sample.jpg");
            myPicture = ImageIO.read(pic);
            icon = new ImageIcon(myPicture);
            label = new JLabel(icon);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // add image
        add(label, BorderLayout.NORTH);
        // bio
        add(bio, BorderLayout.CENTER);
        // sound
        paneSouth.add(play);
        add(paneSouth, BorderLayout.SOUTH);

        // here add your sound declaration and button event...
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
    }
}

并尝试将TextArea更改为JTextArea,因为您只使用了摇摆组件。