2012-10-11 2 views
1

입력 한 갤런 당 마일을 계산하는 프로그램을 작성했습니다. 드롭 다운 메뉴를 사용하여 km로 전환 할 수도 있습니다. 사진을 전환 할 때마다 전환 할 수있는 드롭 다운 메뉴를 선택하면되도록 노력하고 있습니다. 그래서 마일을위한 다른 그림과 km를위한 다른 하나. 그것의 바보 같지만 임무의 요구 사항 중의 하나. 어떻게해야합니까? 여기에 내가 현재 갖고있는 것, 나는 단지 내가 가지고있는 두 가지 사이에서 그림을 바꾸기를 원한다.GUI 프로그램 사진이 드롭 다운 메뉴 동작으로 변경됨 java

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

enter image description hereActionListener 기존 사용할 수 있습니다 ... 선택한 항목 (JComboBox.getSelectedItem 또는 JComboBox.getSelectedIndex)를 결정하고 필요에 따라 이미지를 업데이트 할 필요가 "바보 같지만 과제의 요구 사항 중 하나입니다."* MigLayout이 코드에서 허용된다는 사실에 놀랐습니다. –

답변

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

이 코드를 어디에 넣어야합니까? 나는 시도하고 약간의 오류가 발생했습니다 ... – user1730008

+0

더 나은 도움을 위해 [SSCCE] (http://sscce.org/) (MigLayout 없음)를 게시하십시오. –

2

당신은 당신의 콤보 상자에 ItemListener를 첨부해야합니다. 변화에, 당신은 *

또한 대신 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()])); 
       } 
      }); 


     } 
    } 
}