无法使用Swing正确显示图像

时间:2016-05-19 15:58:03

标签: java user-interface

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

public class PhotoAlbum implements ActionListener {

JFrame frame;
JPanel contentPane;
JButton next;
JLabel pictures;

JLabel sticker;


public PhotoAlbum(){
/* Create and set up the frame */
    frame = new JFrame("Photo Album");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    /* Create a content pane with a BoxLayout and empty borders */
    contentPane = new JPanel();
    contentPane.setBorder(BorderFactory.createEmptyBorder(100, 100, 100, 100));
    contentPane.setBackground(Color.white);
    contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.PAGE_AXIS));

    /* Create a label that shows the start of the game */
    pictures = new JLabel(new ImageIcon("icecream.gif"));
    pictures.setAlignmentX(JLabel.CENTER_ALIGNMENT);
    pictures.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    contentPane.add(pictures);


    /* Create a next button */
    next = new JButton("Next");
    next.setActionCommand("Next");
    next.setAlignmentX(JButton.CENTER_ALIGNMENT);
    next.addActionListener(this);
    contentPane.add(next);


    /* Add content pane to frame */
    frame.setContentPane(contentPane);

    /* Size and then disnext the frame. */
    frame.pack();
    frame.setVisible(true);
}


/**
 * Handle the button click
 * pre: none
 * post: The appropriate image and message are disnexted.
 */
public void actionPerformed(ActionEvent event) {

     if (event.getSource() == "Next"){
 for ( int count = 0; count < 6; count ++){
    switch (count) {
        case 1: pictures.setIcon(new ImageIcon("icecream.gif")); 
                 break;
        case 2:  pictures.setIcon(new ImageIcon("coffee.gif"));
                 break;
        case 3: pictures.setIcon(new ImageIcon("giraffe.gif"));
                 break;
        case 4:  pictures.setIcon(new ImageIcon("jeep.gif"));
                 break;
        case 5:  pictures.setIcon(new ImageIcon("sunset.gif"));
                 break;
        default: 
    }
    }
 }
}








/**
 * Create and show the GUI.
 */
private static void runGUI() {
    JFrame.setDefaultLookAndFeelDecorated(true);

    PhotoAlbum Game = new PhotoAlbum();
}


public static void main(String[] args) {
    /* Methods that create and show a GUI should be
       run from an event-dispatching thread */
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            runGUI();
        }
    });
   }
}

此代码不显示任何图像。我该如何解决?我试图重写它或使用不同的声明,但它仍然没有显示图片。只有按钮

1 个答案:

答案 0 :(得分:0)

我尝试使用我知道的图标,例如:UIManager.getIcon("FileView.fileIcon");这包含在Java库中,因此,我们知道它存在并且我们可以使用它。

如果你这样使用它:pictures = new JLabel(UIManager.getIcon("FileView.fileIcon"));

这是输出:

Fixed

如果您使用缺少的图标(例如new ImageIcon("icecream.gif"))运行它,则输出结果为:

Wrong

当找不到图标时,没有图标,因此您无法访问正确的图标文件。