在JFrame中切换图片

时间:2016-04-16 16:56:43

标签: java swing jframe awt

我很难在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);

    }
}

}

在类Screen中的函数render中,当我这样做时:

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

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

图像正确加载,但是我需要这个图像由类Render中的''drawRainbow''设置,如何实现呢?

1 个答案:

答案 0 :(得分:2)

您创建Swing GUI的方法是向后的。

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

Image Display

以下是创建Swing GUI的方法。

  1. 创建一个包含图像信息的GUI模型。我创建了一个ImageInformation类来保存,你猜对了,一个图像的信息。我创建了一个ImageInformation列表来保存所有图像。

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

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

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

  5. 以下是代码:

    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;
            }
    
        }
    }