【问题标题】:Replace ImageIcon with JButton pressed用按下的 JButton 替换 ImageIcon
【发布时间】:2019-03-12 17:07:18
【问题描述】:

我在用第一个 ImageIcon 替换 ImageIcon 时遇到问题,此时按下了 Jbutton。到目前为止,我已经尝试更换框架、.setIcon(myNewImage); 和 .remove();。不知道现在该做什么......(我需要替换它们并调整它们的大小。)这是我的代码。 (它应该像那些日本约会游戏之一......请忽略图片是本地的,我还没有托管它们的网站。

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import java.util.Scanner;
import javax.swing.ImageIcon;
import javax.swing.*;
import java.awt.*;  

public class NestedPanels extends JPanel {

        JPanel southBtnPanel = new JPanel(new GridLayout(3, 2, 1, 1)); //grid layout of buttons and declaration of panel SoutbtnPanel
        JButton b = new JButton("Say Hello");//1
        JButton c = new JButton("Say You Look Good");//1
        JButton d = new JButton("Say Sorry I'm Late");//1
        JButton e2 = new JButton("So where are we headed?");//2
        JButton f = new JButton("Can we go to your place?");//2
        JButton g = new JButton("I don't have any money for our date...");//2

   public NestedPanels() { //implemeted class

            //add action listener
            b.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    button1Clicked(e);//when button clicked, invoke method
                }
            });
            c.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    button2Clicked(e);//when button clicked, invoke method
                }
            });
           d.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    button3Clicked(e);//when button clicked, invoke method
                }
            }); 

            e2.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    button4Clicked(e);//when button clicked, invoke method
                }
            });

            f.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    button5Clicked(e);//when button clicked, invoke method
                }
            });

            g.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    button6Clicked(e);//when button clicked, invoke method
                }
            });

      southBtnPanel.add(b);
      southBtnPanel.add(c);
      southBtnPanel.add(d);

      setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1)); //layout of buttons "Button text"
      setLayout(new BorderLayout());
      add(Box.createRigidArea(new Dimension(600, 600))); //space size of text box webapp over all
      add(southBtnPanel, BorderLayout.SOUTH);

}
   private static void createAndShowGui() {//class to show gui
        NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
        JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
        frame.getContentPane().add(mainPanel);
        ImageIcon icon = new ImageIcon("C:/Users/wchri/Pictures/10346538_10203007241845278_2763831867139494749_n.jpg");
        JLabel label = new JLabel(icon);
        mainPanel.add(label);
        frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    private void button1Clicked(ActionEvent e) {
        southBtnPanel.removeAll();
        southBtnPanel.add(e2);
        southBtnPanel.add(f);
        southBtnPanel.add(g);
        southBtnPanel.revalidate();
        southBtnPanel.repaint();
        String msg = ((JButton)e.getSource()).getActionCommand() ;
        JOptionPane.showMessageDialog(this, "Hey there! Ready to get started?", "Christian feels good!", JOptionPane.PLAIN_MESSAGE); //display button Action
    }

    private void button2Clicked(ActionEvent e) {

        southBtnPanel.removeAll();
        southBtnPanel.add(e2);
        southBtnPanel.add(f);
        southBtnPanel.add(g);
        southBtnPanel.revalidate();
        southBtnPanel.repaint();
        String msg = ((JButton)e.getSource()).getActionCommand() ;
        JOptionPane.showMessageDialog(this, "Ugh... thanks! You too ready?!", "Christian is a bit... Embarrased.", JOptionPane.PLAIN_MESSAGE); //display button Action
    }

    private void button3Clicked(ActionEvent e) {

        southBtnPanel.removeAll();
        southBtnPanel.add(e2);
        southBtnPanel.add(f);
        southBtnPanel.add(g);
        southBtnPanel.revalidate();
        southBtnPanel.repaint();
        String msg = ((JButton)e.getSource()).getActionCommand() ;
        JOptionPane.showMessageDialog(this, "It's ok! Just make sure it doesn't happen again!", "Christian is a bit angry!", JOptionPane.PLAIN_MESSAGE); //display button Action
    }

    private void button4Clicked(ActionEvent e) {
        NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
        JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
        frame.getContentPane().add(mainPanel);
        JLabel label = new JLabel();
        ImageIcon imageTwo = new ImageIcon("C:/Users/wchri/Documents/chrisferry.jpg");
        mainPanel.add(label);
        label.setIcon(imageTwo);
        frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
        frame.getContentPane().add(mainPanel);
          String msg = ((JButton)e.getSource()).getActionCommand() ;
        JOptionPane.showMessageDialog(this, "Let's take the ferry to NYC!", "Christian feels good!", JOptionPane.PLAIN_MESSAGE); //display button Action

    }

    private void button5Clicked(ActionEvent e) {
        NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
        JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
        frame.getContentPane().add(mainPanel);
        JLabel label = new JLabel();
        ImageIcon imageThree = new ImageIcon("C:/Users/wchri/Pictures/Screenshots/chrisart.jpg");
        mainPanel.add(label);
        label.setIcon(imageThree);
        frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
        frame.getContentPane().add(mainPanel);
        String msg = ((JButton)e.getSource()).getActionCommand() ;
        JOptionPane.showMessageDialog(this, "Don't you think it's a bit soon for that?", "Christian is embarrassed...", JOptionPane.PLAIN_MESSAGE); //display button Action

    }

    private void button6Clicked(ActionEvent e) {
        NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
        JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
        frame.getContentPane().add(mainPanel);
        JLabel label = new JLabel();
        ImageIcon imageFour = new ImageIcon("C:/Users/wchri/Downloads/chrismoney.jpg");
        mainPanel.add(label);
        label.setIcon(imageFour);
        frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
        frame.getContentPane().add(mainPanel);
        String msg = ((JButton)e.getSource()).getActionCommand() ;
        JOptionPane.showMessageDialog(this, "I got money!", "Christian is ballin'", JOptionPane.PLAIN_MESSAGE); //display button Action
        }

   public static void main(String[] args) {

        System.out.println("Welcome to Date Sim 1.0 with we1. Are you ready to play? Yes/No?");

        Scanner in = new Scanner(System.in);
        String confirm = in.nextLine();

        if (confirm.equalsIgnoreCase("Yes")) {
            System.out.println("Ok hot stuff... Let's start.");

            NestedPanels mainPanel = new NestedPanels();

        } else {

            System.out.println("Maybe some other time!"); 
            return;
        }

         SwingUtilities.invokeLater(new Runnable() {
         @Override
         public void run() {
            createAndShowGui();
         }
      });
   }
}

【问题讨论】:

  • 什么按钮?什么图片?

标签: java swing jbutton action imageicon


【解决方案1】:

这里是MCVE,它演示了在单击JButton 时更改图标:

import java.io.IOException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

public class ChangeButtonIcon extends JPanel{

    private URL[] urls = {
      new URL("https://findicons.com/files/icons/345/summer/128/cake.png"),
      new URL("http://icons.iconarchive.com/icons/atyourservice/service-categories/128/Sweets-icon.png"),
      new URL("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS_FkBgG3_ux0kCbfG8mcRHvdk1dYbZYsm2SFMS01YvA6B_zfH_kg"),
      };

    private int iconNumber = 0;
    private JButton button;

    public ChangeButtonIcon() throws IOException {

        button = new JButton();
        button.setIcon(new ImageIcon(urls[iconNumber]));
        button.setHorizontalTextPosition(SwingConstants.CENTER);
        button.addActionListener(e -> swapIcon());
        add(button);
    }

    private void swapIcon() {

        iconNumber = iconNumber >= (urls.length -1) ? 0 : iconNumber+1;
        button.setIcon(new ImageIcon(urls[iconNumber]));
    }

    public static void main(String[] args) throws IOException{
        JFrame window = new JFrame();
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.add(new ChangeButtonIcon());
        window.pack();
        window.setVisible(true);
    }
}

我发现编写 MCVE 是一种非常有用的技术。它不仅使帮助变得更容易,而且 是一个强大的调试工具。很多情况下,在准备一个时,您很可能会发现问题。
它应该代表问题或提出的问题。 不是您的应用程序。

【讨论】:

  • 谢谢。我会解决的。
猜你喜欢
  • 1970-01-01
  • 2013-05-14
  • 2015-07-25
  • 2013-12-21
  • 2012-06-08
  • 2012-10-24
  • 2014-11-30
  • 2011-02-20
  • 1970-01-01
相关资源
最近更新 更多