1

我写了一个程序来计算每加仑输入的英里数。它也可以通过下拉菜单切换到公里。我正在努力做到这一点,以便当我选择下拉菜单时,每次切换时图片都可以切换。所以英里和公里的图片不同。它很愚蠢,但它是作业的要求之一。我该怎么做呢?这是我目前拥有的,我只想让图片在我拥有的两个之间切换。

import java.awt.Component;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import static javax.swing.GroupLayout.Alignment.*;
import net.miginfocom.swing.MigLayout;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class mpg_mig extends JFrame {
   public mpg_mig() {

     JLabel titleLabel = new JLabel("Fuel Calculator");
     titleLabel.setFont(new Font("Serif", Font.BOLD, 18));
     titleLabel.setForeground(Color.blue);

     final JLabel distLabel = new JLabel("Miles:");
    final JTextField distText = new JTextField(10);
     JLabel traveledLabel = new JLabel("traveled");

     final JLabel fuelLabel = new JLabel("Gas:");
     final JTextField fuelText = new JTextField(10);

     final JLabel mpgLabel = new JLabel("Miles per gallon:");
     final JTextField mpgText = new JTextField(10);      

     JButton clearButton = new JButton("Clear");
     JButton calcButton = new JButton("Calculate");

    String[] actStrings = { "Miles", "kiloMeters" };
     JComboBox jComboBox1 = new JComboBox(actStrings);
    jComboBox1.setEditable(true);      

     String sFileName = "circuit1.png";

       BufferedImage image = null;
       try {                 
       image = ImageIO.read(new File(sFileName)); 
     } catch (IOException ex) { 

       System.out.println (ex.toString());
       System.out.println(sFileName);

       JOptionPane.showMessageDialog(null,ex.toString() + " " + sFileName);

       System.exit(0); 

     } 

     JLabel labelPic1 = new JLabel(new ImageIcon(image));


    setResizable( false );

    JPanel p = new JPanel(new MigLayout("", "[] [] []",     
                                        "[] [] [] [] []")); 

    p.setBackground(Color.WHITE);
    setContentPane(p);

     p.add(labelPic1,   "cell 0 0 1 3"); //(column 0, row 0, width 1, height 3) 
     p.add(clearButton, "cell 0 3");     //(column 0, row 3)
     p.add(calcButton,  "cell 0 4");     //(column 0, row 4)

     p.add(titleLabel, "cell 1 0");  //(column 1, row 0)
     p.add(distLabel,  "cell 1 1");  //(column 1, row 1)
     p.add(fuelLabel,  "cell 1 2");  //(column 1, row 2)
     p.add(mpgLabel,   "cell 1 3");  //(column 1, row 3)        
     p.add(jComboBox1, "cell 1 4");  //(column 1, row 4)

     p.add(distText, "cell 2 1");    //(column 2, row 1)
     p.add(fuelText, "cell 2 2");    //(column 2, row 2)
     p.add(mpgText,  "cell 2 3");    //(column 2, row 3)

       clearButton.addActionListener(new ActionListener()
       {  public void actionPerformed(ActionEvent event)
          {  
            distText.setText("");
            fuelText.setText("");
            mpgText.setText("");
          }
       });

       calcButton.addActionListener(new ActionListener()
       {  public void actionPerformed(ActionEvent event)
          {  

             if(isNumeric(distText.getText()) && 
                isNumeric(fuelText.getText()))
             {
                 double fuel;
                 double dist;
                 double result;

                 fuel = Double.parseDouble(fuelText.getText());
                 dist = Double.parseDouble(distText.getText());
                 result = dist/fuel;
                 result = Round(result,2);

                 mpgText.setText(String.format("%f", result));
             }
             else
             {
              JOptionPane.showMessageDialog(null, "Enter distance traveled and fuel used");
             }  
           }                   

       });

      jComboBox1.addActionListener(new ActionListener()
       {  public void actionPerformed(ActionEvent event)
          {  
             //JComboBox jComboBox1 = (JComboBox)event.getSource();
              JComboBox jComboBox1 = (JComboBox)event.getSource();


             if(jComboBox1.getSelectedItem() == "Miles")
             {
                 distLabel.setText("Miles");
                 mpgLabel.setText("Miles per gallon:");
             }
              else
             {
               distLabel.setText("KiloMeters");
                 mpgLabel.setText("KM per liter:");
             }

          }
       });      

       setTitle("MPG and KML");
       pack(); //pack disables setting frames size...
          setLocationRelativeTo(null);//center frame and showMessageDialog
       setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);      
   }

   private static boolean isNumeric(String text)
   {  try
      {  Double.parseDouble(text);  }
      catch (Exception e)
      {  return false;  }
      return true;
   }

  public  double Round(double val, int plc)
  {
      double pwr = Math.pow(10,plc);  
      val = val * pwr;   //shift to the left
      double tmp = (int) val;     

      if( ((int)(val + .5)) == (int) val)
        return (tmp/pwr); //don't round up
      else
        return((tmp + 1.0)/pwr); //round up
  }

   public static void main(String args[]) {
       java.awt.EventQueue.invokeLater(new Runnable() {
           public void run() {
               try {
                   UIManager.setLookAndFeel(

                        UIManager.getCrossPlatformLookAndFeelClassName());
               } catch (Exception ex) {
                   ex.printStackTrace();
               }
               new mpg_mig().setVisible(true);
           }
       });
   }
   }
4

2 回答 2

2

您需要将一个附加ItemListener到您的组合框。更改时,您需要确定所选项目(JComboBox.getSelectedItemJComboBox.getSelectedIndex)并根据需要更新图像...

您也可以使用您现有的ActionListener来代替

在此处输入图像描述 在此处输入图像描述

public class SwitchPicture {

    public static final String[] IMAGES = new String[]{
        "path/to/your/first/image",
        "path/to/your/second/image"
    };

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

    public SwitchPicture() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new SwitcherPane());
                frame.pack();
                frame.setVisible(true);
            }
        });

    }

    protected class SwitcherPane extends JPanel {

        private BufferedImage[] images;
        private JLabel lblBackground;
        private JComboBox comboBox;

        public SwitcherPane() {

            try {
                images = new BufferedImage[2];
                for (int index = 0; index < 2; index++) {
                    images[index] = ImageIO.read(new File(IMAGES[index]));
                }
            } catch (IOException ex) {
                ex.printStackTrace();;
            }

            setLayout(new BorderLayout());
            lblBackground = new JLabel();
            lblBackground.setIcon(new ImageIcon(images[0]));

            add(lblBackground);

            comboBox = new JComboBox();
            comboBox.getSelectedItem()
            // I did this because the images where so large
            // you couldn't see the combo box :P
            comboBox.setFont(comboBox.getFont().deriveFont(48f));
            DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>();
            model.addElement("Happy");
            model.addElement("Happier");
            comboBox.setModel(model);
            comboBox.setSelectedIndex(0);

            lblBackground.setLayout(new GridBagLayout());
            lblBackground.add(comboBox);

            comboBox.addItemListener(new ItemListener() {

                @Override
                public void itemStateChanged(ItemEvent e) {
                    lblBackground.setIcon(new ImageIcon(images[comboBox.getSelectedIndex()]));
                }
            });


        }
    }
}
于 2012-10-11T05:59:11.917 回答
2
// in the action detection
labelPic1.setIcon(new ImageIcon(newImage));
于 2012-10-11T05:43:49.540 回答