按下Jbutton时需要显示ImageIcon

时间:2018-04-14 21:24:36

标签: java swing jbutton jlabel imageicon

当我点击我的Jbutton时,我无法显示我的图像,测试sysoutprint可以正常工作但Image不能。关于做什么的任何想法我很丢失! Image是学校项目的复活节彩蛋,随时发表评论。我应该使用ImageIcon以外的东西吗? 如果还有其他任何错误,请告诉我们!

package GUI;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class mainView{
private static JFrame main; //main frame we add everything too
private static JPanel newGame; //panel for new game        
private static JPanel dropDownPanel; //panel for the combobox 

private static CardLayout clayout; //cardlayout for new game
private static JComboBox dropDown; //dropdown combobox  
ImageIcon eastImg;





public void codeNameView(){
    main = new JFrame("CodeNames");
    main.setSize(600, 900);
    main.setVisible(true);

    //dropdown menu for quit and new game
    String[] choice = {" " , "NewGame" , "Quit"};
    dropDown = new JComboBox(choice);

    //below is the panel where we add new game and quit options too
    dropDownPanel = new JPanel();
    dropDownPanel.setSize(100, 100);
    dropDownPanel.add(dropDown);
    main.getContentPane().add(dropDownPanel,BorderLayout.NORTH);

    //easter egg
    JButton easterButt = new JButton("Pass CSE 116");
    JLabel eastLbl = new JLabel();
    //added button to JLabel
    eastLbl.add(easterButt);
    try{
        String path = "/Users/nabeelkhalid/git/s18semesterproject-b4-zigzag1/src/GUI/MatthewPhoto.jpg";
        eastImg = new ImageIcon(path);

    }catch(Exception ex){
        System.out.print(ex);
    }
    //added label to Panel
    dropDownPanel.add(eastLbl);
    eastLbl.addMouseListener(new MouseListener(){

        @Override
        public void mouseClicked(MouseEvent e) {
            // TODO Auto-generated method stub
            eastLbl.setIcon(eastImg);
            System.out.print("test");

        }
        //Ignore
        @Override
        public void mousePressed(MouseEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mouseReleased(MouseEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mouseEntered(MouseEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mouseExited(MouseEvent e) {
            // TODO Auto-generated method stub

        }

    });

    //action listener for dropdown combobox
    dropDown.addActionListener(new ActionListener(){

      /**
       * Allows for the user to select New Game or Quit and have the game perform said action
       */
        @Override
        public void actionPerformed(ActionEvent e) {

            // TODO Auto-generated method stub
            JComboBox cb = (JComboBox) e.getSource();
            Object selectedOption = dropDown.getSelectedItem();

            if (selectedOption.equals("Quit")) {
                 main.dispose();    
            }else if(selectedOption.equals("NewGame")){

                codeNameView();
                System.out.print("yolo");

            }
                }

    });

}


public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            mainView x = new mainView();

            // create a instance on mainview to run instead of using static methods

        }
    });
}

}

2 个答案:

答案 0 :(得分:0)

主要问题似乎就在这里

try{
    String path = "/Users/nabeelkhalid/git/s18semesterproject-b4-zigzag1/src/GUI/MatthewPhoto.jpg";
    eastImg = new ImageIcon(path);

}catch(Exception ex){
    System.out.print(ex);
}

该路径引用了src路径上下文中的资源。你永远不应该在你的代码中引用src,一旦导出程序(到Jar或在不同的计算机上运行)它就不会存在

相反,您应该考虑使用Class#getResource来获取对图片的引用,并且我个人会ImageIO.read使用ImageIcon作为个人偏好。

try{
    String path = "/GUI/MatthewPhoto.jpg";
    eastImg = new ImageIcon(ImageIO.read(this.getClass().getResource(path)));
}catch(Exception ex){
    System.out.print(ex);
}

而且,您的下一个问题是,您尝试向JLabel添加JButton,期待JButton没有布局管理员且JButton已经拥有支持显示图像,所以相反,你应该做更像......的事情。

JButton easterButt = new JButton("Pass CSE 116");
//JLabel eastLbl = new JLabel();
//added button to JLabel
//eastLbl.add(easterButt);
try {
    String path = "/GUI/MatthewPhoto.jpg";
    eastImg = new ImageIcon(ImageIO.read(this.getClass().getResource(path)));

} catch (Exception ex) {
    System.out.print(ex);
}
//added label to Panel
dropDownPanel.add(easterButt);
easterButt.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        easterButt.setIcon(eastImg);
    }
});

你真的应该仔细看看How to Use Buttons, Check Boxes, and Radio Buttons

测试代码

这是我用来测试上面提出的解决方案的代码

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class mainView {

    private static JFrame main; //main frame we add everything too
    private static JPanel newGame; //panel for new game        
    private static JPanel dropDownPanel; //panel for the combobox 

    private static CardLayout clayout; //cardlayout for new game
    private static JComboBox dropDown; //dropdown combobox  
    ImageIcon eastImg;

    public void codeNameView() {
        main = new JFrame("CodeNames");
        main.setSize(600, 900);

        //dropdown menu for quit and new game
        String[] choice = {" ", "NewGame", "Quit"};
        dropDown = new JComboBox(choice);

        //below is the panel where we add new game and quit options too
        dropDownPanel = new JPanel();
        dropDownPanel.setSize(100, 100);
        dropDownPanel.add(dropDown);
        main.getContentPane().add(dropDownPanel, BorderLayout.NORTH);

        //easter egg
        JButton easterButt = new JButton("Pass CSE 116");
//      JLabel eastLbl = new JLabel();
//      //added button to JLabel
//      eastLbl.add(easterButt);
        try {
            String path = "/GUI/MatthewPhoto.jpg";
            eastImg = new ImageIcon(ImageIO.read(this.getClass().getResource(path)));

        } catch (Exception ex) {
            System.out.print(ex);
        }
        //added label to Panel
        dropDownPanel.add(easterButt);
        easterButt.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                easterButt.setIcon(eastImg);
            }
        });

        //action listener for dropdown combobox
        dropDown.addActionListener(new ActionListener() {

            /**
             * Allows for the user to select New Game or Quit and have the game
             * perform said action
             */
            @Override
            public void actionPerformed(ActionEvent e) {

                // TODO Auto-generated method stub
                JComboBox cb = (JComboBox) e.getSource();
                Object selectedOption = dropDown.getSelectedItem();

                if (selectedOption.equals("Quit")) {
                    main.dispose();
                } else if (selectedOption.equals("NewGame")) {

                    codeNameView();
                    System.out.print("yolo");

                }
            }

        });
        main.setVisible(true);

    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                System.out.println("Hello");
                mainView x = new mainView();
                x.codeNameView();
                // create a instance on mainview to run instead of using static methods
            }
        });
    }
}

答案 1 :(得分:-1)

尝试使用以下内容:
String path =“C:\\ Users \\ nabeelkhalid \\ git \\ s18semesterproject-b4-zigzag1 \\ src \\ GUI \\ MatthewPhoto.jpg”;