GUI程序图片随下拉菜单操作java而变化

时间:2012-10-11 05:37:39

标签: java swing action jframe jlabel

我写了一个程序,计算每加仑输入的里程数。它也可以通过下拉菜单切换到km。我试图这样做,以便当我选择下拉菜单时,每次切换时图片都可以切换。所以英里的不同画面和千米的不同画面。它很愚蠢但是它的任务要求之一。我该怎么做呢?这就是我现在所拥有的,我只想让图片在两个之间改变。

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

2 个答案:

答案 0 :(得分:2)

// in the action detection
labelPic1.setIcon(new ImageIcon(newImage));

答案 1 :(得分:2)

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

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

enter image description here enter image description here

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()]));
                }
            });


        }
    }
}