在JFrame中切换图片

Switching picture in JFrame

您好,我在 JFrame 中切换图片时遇到问题。我将 JFrame 初始化为黑色图片,接下来我想加载一个 ''sample2.jpg'' 到它:

Display.java

public class Display extends Canvas  implements Runnable{
/**
 * 
 */
private static final long serialVersionUID = 1L;



public static int WIDTH=1280;
public static int HEIGHT=720;
public static final String TITLE = "rainbow";


private Thread thread;
private boolean running = false;
private Render render;
private Screen screen;
private BufferedImage img;
private int pixels[];


public Display(){
    Dimension size = new Dimension(WIDTH,HEIGHT);
    setPreferredSize(size);
    setMinimumSize(size);
    setMaximumSize(size);
    screen = new Screen(WIDTH, HEIGHT);
    img = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
    pixels = ((DataBufferInt)img.getRaster().getDataBuffer()).getData();


}


public synchronized void start(){
    if(running) 
        return;
    running = true;
    thread = new Thread(this);
    thread.start();

    //System.out.println("working...");
}

public synchronized void stop(){
    if(!running)
        return;
    running = false;
    try{
        thread.join();
    } catch(Exception e){
        e.printStackTrace();
        System.exit(0);
    }
}   

public void run(){

    while(running){
        render();
    }
}

private void render(){
BufferStrategy bs = this.getBufferStrategy();
if(bs == null)
{
    createBufferStrategy(3);
    return;
}
screen.render();
for(int i=0; i<WIDTH*HEIGHT; i++)
{
    pixels[i] = screen.pixels[i];

}

Graphics g = bs.getDrawGraphics();
g.drawImage(img, 0, 0, WIDTH, HEIGHT, null);
g.dispose();
bs.show();
}

public static void main(String[] args){
    Display game = new Display();
    JFrame frame = new JFrame();
    frame.add(game);

    frame.setTitle(TITLE);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(false);
    frame.pack();
    frame.setVisible(true);

    System.out.println("running ...");

    game.start();
}

}

Render.java

public class Render {
public final int width, height;
public final int [] pixels;
public static int tick;

public Render(int width, int height){
    this.width = width;
    this.height = height;
    pixels = new int[width * height];
    tick=0;
}

public void draw(Render render, int xOffset, int yOffset){
    for(int y=0; y<render.height; y++){
        int yPix = y+yOffset;
        if(yPix<0 || yPix >=height){
            continue;
        }
        for(int x=0; x < render.width; x++){
            int xPix = x+xOffset;
            if(xPix < 0 ||yPix >=width){
                continue;
            }
            int alpha = render.pixels[x+y*render.width];
            if(alpha >0)
            {
                pixels[xPix+yPix*width]=alpha;
            }
        }
    }
}

public void drawRainbow(){
    for(int i =0 ; i <width*height;i++){
        pixels[i] = Image.floor.pixels[i];
    }
    //System.out.println("draw rainbow: " + pixels[1200]);

}
}

Screen.java

public class Screen extends Render {

private Render test;


public Screen(int width, int height) {
    super(width, height);
    Random random = new Random();
    test = new Render(width,height);
    for(int i=0; i<width*height; i++){
        pixels[i] = 0;
    }


}

public void render(){
    for(int i =0 ; i <width*height;i++){
        pixels[i]= 0;
    }

    test.drawRainbow();
    draw(test,0,0);
}

}

Image.java

public class Image {
public static Render floor = loadBitmap("/Images/sample2.jpg");

public static Render loadBitmap(String fileName){
    try{
        BufferedImage image = ImageIO.read(Image.class.getResource(fileName));
        int width = image.getWidth();
        int height = image.getHeight();
        Render result = new Render(width, height);
        image.getRGB(0, 0, width, height, result.pixels, 0 ,width);
        return result;
    }catch(Exception e){
        System.out.println("crash");
        throw new RuntimeException(e);

    }
}

}

在 class 屏幕中的函数 render 中,当我这样做时:

public void render(){
    for(int i =0 ; i <width*height;i++){
        pixels[i]= Image.floor.pixels[i];
    }

    test.drawRainbow();
    draw(test,0,0);
}

图像加载正确,但我需要通过 class Render 中的函数“'drawRainbow'”设置此图像,如何实现?

您创建 Swing GUI 的方法是倒退的。

这是一个 Swing GUI,显示了 6 张来自互联网的图片。

以下是创建 Swing GUI 的方法。

  1. 创建一个保存图像信息的 GUI 模型。我创建了一个 ImageInformation class 来保存(您猜对了)一张图像的信息。我创建了一个 ImageInformation 列表来保存所有图像。

  2. 我创建了一个 JFrame 来保存所有 Swing 组件。

  3. 我通过调用 SwingUtilities invokeLater 方法将 Swing 组件的创建和使用放在 Event Dispatch thread 上。 Oracle 和我要求您在事件调度线程上启动所有 Swing 应用程序。

  4. 我创建了一个图像 JPanel 来保存图像信息,并创建了一个控件 JPanel fpr JRadioButtons。

代码如下:

package com.ggl.testing;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;

public class ImageDisplay implements Runnable {

    private ItemListener listener;

    private JFrame frame;

    private JLabel titleLabel;
    private JLabel imageLabel;
    private JLabel descriptionLabel;

    private List<ImageInformation> images;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new ImageDisplay());
    }

    public ImageDisplay() {
        this.images = setImageInformation();
    }

    @Override
    public void run() {
        frame = new JFrame("Image Display");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(createControlPanel(), BorderLayout.WEST);
        frame.add(createImagePanel(), BorderLayout.CENTER);

        frame.pack();
        frame.setVisible(true);
    }

    private JPanel createImagePanel() {
        JPanel imagePanel = new JPanel();
        imagePanel.setLayout(new BorderLayout());

        ImageInformation defaultImageInformation = images.get(0);

        titleLabel = new JLabel(defaultImageInformation.getTitle());
        titleLabel.setHorizontalAlignment(JLabel.CENTER);
        imagePanel.add(titleLabel, BorderLayout.NORTH);

        imageLabel = new JLabel(new ImageIcon(
                defaultImageInformation.getImage()));
        JScrollPane scrollPane = new JScrollPane(imageLabel);
        imagePanel.add(scrollPane, BorderLayout.CENTER);

        descriptionLabel = new JLabel(defaultImageInformation.getDescription());
        descriptionLabel.setHorizontalAlignment(JLabel.CENTER);
        imagePanel.add(descriptionLabel, BorderLayout.SOUTH);
        return imagePanel;
    }

    private JPanel createControlPanel() {
        JPanel panel = new JPanel();
        panel.setBorder(new TitledBorder(new EtchedBorder(), "Images"));
        panel.setLayout(new GridLayout(0, 1));

        ButtonGroup group = new ButtonGroup();

        listener = new ImageListener();

        for (int i = 0; i < images.size(); i++) {
            ImageInformation imageInformation = images.get(i);
            JRadioButton button = new JRadioButton(imageInformation.getTitle());
            if (i == 0) {
                button.setSelected(true);
            }
            button.addItemListener(listener);
            group.add(button);
            panel.add(button);
        }

        return panel;
    }

    private List<ImageInformation> setImageInformation() {
        List<ImageInformation> images = new ArrayList<ImageInformation>();

        // Here, you would get your images
        Image image1 = getImage("http://4.bp.blogspot.com/-vfRL5DamWFs/"
                + "T2nn6D_EUfI/AAAAAAAABB8/Kc9Y33qYWJo/s1600/People-Power.jpg");
        Image image2 = getImage("http://www.jeffjonesillustration.com/images/"
                + "illustration/00601-group-of-people.jpg");
        Image image3 = getImage("http://www.careersusa.com/portals/0/BusinessPeopleImage2.png");
        Image image4 = getImage("http://www.druginfo.sl.nsw.gov.au/images/teens.jpg");
        Image image5 = getImage("http://www.pesconsulting.co.uk/wp-content/uploads/"
                + "2013/03/kevin-thom-2010-people-collage.jpg");
        Image image6 = getImage("http://www.emcdda.europa.eu/attachements.cfm/"
                + "att_77302_EN_young-people-480px.jpg");

        images.add(new ImageInformation(image1, "Image 1",
                "Image 1 Description"));
        images.add(new ImageInformation(image2, "Image 2",
                "Image 2 Description"));
        images.add(new ImageInformation(image3, "Image 3",
                "Image 3 Description"));
        images.add(new ImageInformation(image4, "Image 4",
                "Image 4 Description"));
        images.add(new ImageInformation(image5, "Image 5",
                "Image 5 Description"));
        images.add(new ImageInformation(image6, "Image 6",
                "Image 6 Description"));

        return images;
    }

    private Image getImage(String fileName) {
        try {
            return ImageIO.read(new URL(fileName));
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private ImageInformation getImageInformation(String title) {
        for (ImageInformation imageInformation : images) {
            if (title.equals(imageInformation.getTitle())) {
                return imageInformation;
            }
        }

        return null;
    }

    public class ImageListener implements ItemListener {

        @Override
        public void itemStateChanged(ItemEvent event) {
            if (event.getStateChange() == ItemEvent.SELECTED) {
                JRadioButton button = (JRadioButton) event.getItem();
                String labelText = button.getText();
                ImageInformation imageInformation = getImageInformation(labelText);
                if (imageInformation != null) {
                    titleLabel.setText(imageInformation.getTitle());
                    imageLabel.setIcon(new ImageIcon(imageInformation
                            .getImage()));
                    descriptionLabel.setText(imageInformation.getDescription());
                }
            }
        }

    }

    public class ImageInformation {

        private final Image image;

        private final String title;
        private final String description;

        public ImageInformation(Image image, String title, String description) {
            this.image = image;
            this.title = title;
            this.description = description;
        }

        public Image getImage() {
            return image;
        }

        public String getTitle() {
            return title;
        }

        public String getDescription() {
            return description;
        }

    }
}