简体   繁体   English

在JFrame中添加图像,单击图像

[英]adding images in JFrame, image when clicked

I want to make a "simple" program. 我想做一个“简单”的程序。 it consists of three buttons and when you click on one of them i want a picture to show up, but i don't know how to add the image properly. 它由三个按钮组成,当你点击其中一个按钮时,我想要一张图片显示,但我不知道如何正确添加图像。 If anyone has played pokemon i want to make the start where you select your starter pokemon. 如果有人玩过口袋妖怪,我想在你选择起始口袋妖怪的地方开始。

Here is my code. 这是我的代码。

public LayoutLek(){

    super("Starter");
    panel=new JPanel();
    panel.setLayout(new GridLayout(2,1));
    top_p=new JPanel();                             

    label1=new JLabel("Make a choice");
    label1.setFont(new Font("Arial", Font.BOLD, 30));
    label1.setForeground(Color.black);

    ImageIcon green = new ImageIcon("Bilder/bulbasaur.jpg");   //Dont know if it is correct but...
    JLabel label2 = new JLabel(green);

    top_p.setBackground(Color.yellow);
    top_p.add(label1);
    bottom_p=new JPanel();                          
    bottom_p.setLayout(new GridLayout(1,3));

    panel.add(top_p);
    panel.add(bottom_p);

    button1=new JButton("Button 1");
    button1.setBackground(Color.green);
    button1.setForeground(Color.black);
    button1.setFont(new Font("Arial", Font.BOLD, 24));
    button2=new JButton("Button 2");
    button2.setBackground(Color.red);
    button2.setForeground(Color.black);
    button2.setFont(new Font("Arial", Font.BOLD, 24));
    button3=new JButton("Button 3");
    button3.setBackground(Color.blue);
    button3.setForeground(Color.black);
    button3.setFont(new Font("Arial", Font.BOLD, 24));

    bottom_p.add(button1);
    bottom_p.add(button2);
    bottom_p.add(button3);

    button1.addActionListener(this);
    button2.addActionListener(this);
    button3.addActionListener(this);

    this.add(panel);
    //this.setSize(350, 300);
    this.pack();
    this.setVisible(true);
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setAlwaysOnTop(true);

}

public static void main(String[] args) {
    new LayoutLek();

}

public void actionPerformed(ActionEvent e) {
    System.out.println("Clicked");      //Just to test
    Object src = e.getSource();
    if(src==button1){
                       //Here should the image show up
    }
    else if(src==button2){

    }
    else if(src==button3){

    }

}

If anyone can help i would be thankful! 如果有人可以提供帮助,我会感激不尽!

  1. Images that are embedded into your program should be loaded from the class path, not the file system. 应该从类路径而不是文件系统加载嵌入到程序中的图像。 When you pass a String to the ImageIcon your telling the program to look in the file system. 将String传递给ImageIcon告诉程序查看文件系统。 To load from the class path, use 要从类路径加载,请使用

     new ImageIcon(getClass().getResource("/Bilder/bulbasaur.jpg"); 

    where Bilder need to be in the src Bilder需要在src

  2. Your JLabel label2 is locally scoped within the constructor, so you can't access it from outside the constructor, ie the actionPerformed . 您的JLabel label2在构造函数中是本地作用域的,因此您无法从构造函数外部访问它,即actionPerformed You need to declare it outside the constructor, as class members, as you seem to have done with your other objects. 您需要在构造函数外部声明它,作为类成员,就像您似乎已经使用其他对象一样。

  3. Have all three ImageIcons already initialized As class members also. 已经初始化了所有三个 ImageIcons作为类成员。

  4. Just use label2.setIcon(oneOfTheImageIcons); 只需使用label2.setIcon(oneOfTheImageIcons); in the actionPerformed to change the icon of the JLabel actionPerformed中更改JLabel的图标

  5. Swing apps should be run from the Event Dispatch Thread. Swing应用程序应该从Event Dispatch Thread运行。 You can do so by wrapping your new LayoutLek(); 您可以通过包装new LayoutLek(); in a SwingUtilities.invokeLater.. . SwingUtilities.invokeLater.. See Initial Threads for complete details. 有关完整详细信息,请参阅初始线程

  6. You never add your label2 to a visible conainter. 您永远不会将label2添加到可见的conainter。

After fixing all the above mentioned points, here is a runnable refactor. 在修复了上述所有要点之后,这里是一个可运行的重构器。 You just need to change your file paths accordingly. 您只需相应地更改文件路径。

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class LayoutLek extends JFrame implements ActionListener {

    JPanel panel;
    JPanel top_p;
    JLabel label1;
    JPanel bottom_p;
    JButton button1;
    JButton button2;
    JButton button3;

    ImageIcon green;
    ImageIcon blue;
    ImageIcon red;
    JLabel label2;

    public LayoutLek() {
        super("Starter");

        green = new ImageIcon(getClass().getResource("/path/to/imgage"));
        blue = new ImageIcon(getClass().getResource("/path/to/imgage"));
        red = new ImageIcon(getClass().getResource("/path/to/imgage"));
        label2 = new JLabel(green);

        panel = new JPanel();
        panel.setLayout(new GridLayout(2, 1));
        top_p = new JPanel();

        label1 = new JLabel("Make a choice");
        label1.setFont(new Font("Arial", Font.BOLD, 30));
        label1.setForeground(Color.black);

        top_p.setBackground(Color.yellow);
        top_p.add(label1);
        bottom_p = new JPanel();
        bottom_p.setLayout(new GridLayout(1, 3));

        panel.add(top_p);
        panel.add(bottom_p);

        button1 = new JButton("Button 1");
        button1.setBackground(Color.green);
        button1.setForeground(Color.black);
        button1.setFont(new Font("Arial", Font.BOLD, 24));
        button2 = new JButton("Button 2");
        button2.setBackground(Color.red);
        button2.setForeground(Color.black);
        button2.setFont(new Font("Arial", Font.BOLD, 24));
        button3 = new JButton("Button 3");
        button3.setBackground(Color.blue);
        button3.setForeground(Color.black);
        button3.setFont(new Font("Arial", Font.BOLD, 24));

        bottom_p.add(button1);
        bottom_p.add(button2);
        bottom_p.add(button3);

        button1.addActionListener(this);
        button2.addActionListener(this);
        button3.addActionListener(this);

        this.add(panel);
        this.add(label2, BorderLayout.PAGE_START);
        //this.setSize(350, 300);
        this.pack();
        this.setVisible(true);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setAlwaysOnTop(true);

    }

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

    public void actionPerformed(ActionEvent e) {
        System.out.println("Clicked");      //Just to test
        Object src = e.getSource();
        if (src == button1) {
            label2.setIcon(green);
        } else if (src == button2) {
            label2.setIcon(blue);
        } else if (src == button3) {
            label2.setIcon(red);
        }
    }
}

Firstly, src.equals(button1) . 首先, src.equals(button1) It's better practise to use the object-based equals method, == is better applied to primitive comparison (ie int , long , boolean , etc). 最好使用基于对象的equals方法,==更好地应用于原始比较(即intlongboolean等)。

Secondly, you can do a couple of things. 其次,你可以做几件事。

  1. Add the image to a container, then remove it and add another each time a button is clicked. 将图像添加到容器中,然后将其删除,并在每次单击按钮时添加另一个图像。

  2. Add all three images to a container, set them all to invisible ( setVisible(false) ) and then in src.equals(button1/2/3) you set the appropriate image to visible. 将所有三个图像添加到容器中,将它们全部设置为不可见( setVisible(false) ),然后在src.equals(button1/2/3)中将相应的图像设置为可见。 Container may need to be repainted. 容器可能需要重新粉刷。

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM