试图压缩转换程序

时间:2015-04-15 22:38:52

标签: java swing

我目前是高中生,正在当地大学攻读DE课程。我正在上Java课程,正在研究一个项目。

我仍然是初学者,正如您在我的代码中看到的那样,我正在尝试找到压缩代码的方法,以便我可以尝试添加更多内容。如果你能帮助我,我真的很感激!

该程序是针对不同长度单位的转换程序。我自学了组合框的基础知识,虽然我对它不是很熟悉。

我也无法弄清楚为什么转换按钮会延伸到目前为止。最后,我需要一个复选框,因为我真的不能想到它的另一个用途,我把它放在代码中,你会在代码中看到它。

注意:只是说;不要太复杂,我需要理解它,因为我必须解释在程序中做了什么

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Converter extends JFrame {

public static void main(String[] args) {
    Converter myFrame = new Converter();
}

private JPanel myP1, myP2, myP3,myP4,myP5;
private JLabel myMessageLabel,myMessageLabel2,myMessageLabel3;
private JButton myButton;
private JComboBox myBox1,myBox2;
private JTextField myText;
private JCheckBox myCheck;

String combo1, combo2;
double inputNumber, convertedNumber;
char check;

public Converter()  {
        //Dimensions of Frame
        final int W_WIDTH = 450;
        final int W_HEIGHT = 200;

        //Title of Window
        setTitle("Unit Converter");
        //Size is set
        setSize(W_WIDTH, W_HEIGHT);
        //Close operation
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Set layout of frame
        setLayout(new BorderLayout());
        //Building and adding panels
        buildPanel1();
        add(myP1, BorderLayout.NORTH);
        buildPanel2();
        add(myP2, BorderLayout.CENTER);
        buildPanel3();
        buildPanel4();
        add(myP4, BorderLayout.SOUTH);
        buildPanel5();
        myP2.add(myP5);
        //Making the frame visible on the screen
        setVisible(true);

}


private void buildPanel1() {
    myMessageLabel = new JLabel("Welcome to the Master Creators Unit Converter!");
    myP1 = new JPanel();

    myP1.add(myMessageLabel);

}

private void buildPanel2() {
    //First Combo Box
    String[] units = { " ","Miles", "Feet", "Kilometers", "Meters" };
    myP2 = new JPanel();
    myBox1 = new JComboBox(units);
    myBox1.addActionListener(new ComboBoxListener1());
    myP2.add(myBox1);
}

private void buildPanel3() {
    //Entering the value to be converted and check box
    myP3 = new JPanel();
    myMessageLabel3 = new JLabel("Enter a value:");
    myText = new JTextField(10);
    myCheck = new JCheckBox("Keep checked to convert!");
    myCheck.addItemListener(new CheckBoxListener());

    myP3.add(myMessageLabel3);
    myP3.add(myText);
    myP3.add(myCheck);
}

private void buildPanel4() {
    //Button to convert
    myButton = new JButton("Convert");
    myButton.addActionListener(new myButtonListener());
    myP4 = new JPanel();
    myP4.setLayout(new GridLayout(2,1));
    myP4.add(myP3);
    myP4.add(myButton);

}
private void buildPanel5() {
    //Second Combo Box
    String[] units = { " ","Miles", "Feet", "Kilometers", "Meters" };
    myP5 = new JPanel();
    myMessageLabel2 = new JLabel("to");
    myBox2 = new JComboBox(units);
    myBox2.addActionListener(new ComboBoxListener2());

    myP5.add(myMessageLabel2);
    myP5.add(myBox2);

}

private class ComboBoxListener1 implements ActionListener {
    public void actionPerformed (ActionEvent e) {
        //Giving values to the different selections in the combo box
        String selection = (String) myBox1.getSelectedItem();
        if (selection.equals("Miles")) {
            combo1 = "a";
        }
        else if (selection.equals("Feet")) {
            combo1 = "b";
        }
        else if (selection.equals("Kilometers")) {
            combo1 = "c";
        }
        else if (selection.equals("Meters")) {
            combo1 = "d";
        }
        else {
            combo1 = "z";
        }
    }
}

private class ComboBoxListener2 implements ActionListener {
    public void actionPerformed (ActionEvent e) {
        //Giving values to the different selections in the combo box
        String selection = (String) myBox2.getSelectedItem();
        if (selection.equals("Miles")) {
            combo2 = "a";
        }
        else if (selection.equals("Feet")) {
            combo2 = "b";
        }
        else if (selection.equals("Kilometers")) {
            combo2 = "c";
        }
        else if (selection.equals("Meters")) {
            combo2 = "d";
        }
        else {
            combo2 = "z";
        }
    }
}
private class myButtonListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        String input;
        //Obtains value entered by user and converts to double
        input = myText.getText();
        inputNumber = Double.parseDouble(input);
        //Checks if the check box is checked before continuing
        if(check == 'y') {
        //Converts the value from the selected unit to the unit to convert to
        if(combo1.equals(combo2)) {
            JOptionPane.showMessageDialog(null, inputNumber);
        }
        else if (combo1 == "a" && combo2 == "b") {
            convertedNumber = inputNumber * 5280;
            JOptionPane.showMessageDialog(null, convertedNumber + " feet");
        }
        else if (combo1 == "a" && combo2 == "c") {
            convertedNumber = inputNumber * 1.60934;
            JOptionPane.showMessageDialog(null, convertedNumber + " kilometers");
        }
        else if (combo1 == "a" && combo2 == "d") {
            convertedNumber = inputNumber * 1609.34;
            JOptionPane.showMessageDialog(null, convertedNumber + " meters");
        }
        else if (combo1 == "b" && combo2 == "a") {
            convertedNumber = inputNumber * 0.000189394;
            JOptionPane.showMessageDialog(null, convertedNumber + " miles");
        }
        else if (combo1 == "b" && combo2 == "c") {
            convertedNumber = inputNumber * 0.0003048;
            JOptionPane.showMessageDialog(null, convertedNumber + " kilometers");
        }
        else if (combo1 == "b" && combo2 == "d") {
            convertedNumber = inputNumber * 0.3048;
            JOptionPane.showMessageDialog(null, convertedNumber + " meters");
        }
        else if (combo1 == "c" && combo2 == "a") {
            convertedNumber = inputNumber * 0.621371;
            JOptionPane.showMessageDialog(null, convertedNumber + " miles");
        }
        else if (combo1 == "c" && combo2 == "b") {
            convertedNumber = inputNumber * 3280.84;
            JOptionPane.showMessageDialog(null, convertedNumber + " feet");
        }
        else if (combo1 == "c" && combo2 == "d") {
            convertedNumber = inputNumber * 1000;
            JOptionPane.showMessageDialog(null, convertedNumber + " meters");
        }
        else if (combo1 == "d" && combo2 == "a") {
            convertedNumber = inputNumber * 0.000621371;
            JOptionPane.showMessageDialog(null, convertedNumber + " miles");
        }
        else if (combo1 == "d" && combo2 == "b") {
            convertedNumber = inputNumber * 3.28084;
            JOptionPane.showMessageDialog(null, convertedNumber + " feet");
        }
        else if (combo1 == "d" && combo2 == "c") {
            convertedNumber = inputNumber * 0.001;
            JOptionPane.showMessageDialog(null, convertedNumber + " kilometers");
        }
        }
    }
}
private class CheckBoxListener implements ItemListener {
    public void itemStateChanged (ItemEvent e) {
        //Checks if the check box is checked
        if (myCheck.isSelected()){
            check = 'y';
        }
        else {
            check = 'n';
        }
    }
}
}

2 个答案:

答案 0 :(得分:1)

如果您的主要目标是使您的代码更整洁,更明确,那么我建议从以下开始:将您的单位数据类型从字符串转换为Java enum并封装您的距离一个Distance课程。这将带来以下好处:

  • 分离演示文稿和转换逻辑
  • 将临时混淆转换移至combo1combo2
  • 移除您排长队的ifelse if语句
  • 允许添加新单元而不更改表示逻辑

以下是您可以使用的潜在结构示例:

public enum Unit {
    MILES (1609.344),
    FEET (0.3048),
    KILOMETRES (1000.0),
    METRES (1.0);

    private final float toMetreRate;
    Unit(float toMetreRate) {
        this.toMetreRate = toMetreRate;
    }

    public float convertTo(float value, Unit unit) {
        return value * toMetreRate / unit.toMetreRate;
    }
}

public class Distance {
    private final Unit unit;
    private final float value;

    public Distance(float value, Unit unit) {
        this.value = value;
        this.unit = unit;
    }

    public Distance convert(Unit newUnit) {
        return new Distance(unit.covertTo(value, newUnit), newUnit);
    }
}

答案 1 :(得分:0)

我将创建一个枚举,该枚举具有转换常量以及要与仪表转换的代码:

public enum Measure {
    METERS("meters", 1.0),
    KILOMETERS("kilometers", 1000),
    FEET("feet", 0.3048),
    MILES("miles", 1609.344);

    private String text;
    private double conversionConst;

    private Measure(String text, double conversionConst) {
        this.text = text;
        this.conversionConst = conversionConst;
    }

    public String getText() {
        return text;
    }

    @Override
    public String toString() {
        return text;
    }

    public double getConversionConst() {
        return conversionConst;
    }

    public double toMeter(double value) {
        return value * conversionConst;
    }

    public double fromMeter(double value) {
        return value / conversionConst;
    }
}

并使用此枚举创建组合框:

private JComboBox<Measure> fromCombo = new JComboBox<>(Measure.values());
private JComboBox<Measure> toCombo = new JComboBox<>(Measure.values());

在动作监听器中,使用以下方法:

String inputText = inputField.getText().trim();
try {
    double input = Double.parseDouble(inputText);
    Measure fromMeasure = (Measure) fromCombo.getSelectedItem();
    Measure toMeasure = (Measure) toCombo.getSelectedItem();

    double meter = fromMeasure.toMeter(input);
    double result = toMeasure.fromMeter(meter);
    String resultText = String.format("%.02f", result);
    resultField.setText(resultText);
}

例如:

import java.awt.event.KeyEvent;

import javax.swing.*;

public class Converter2 extends JPanel {
    private JComboBox<Measure> fromCombo = new JComboBox<>(Measure.values());
    private JComboBox<Measure> toCombo = new JComboBox<>(Measure.values());
    private JTextField inputField = new JTextField(10);
    private JTextField resultField = new JTextField(10);
    private JButton calculateButton = new JButton("Calculate");

    public Converter2() {
        calculateButton.setMnemonic(KeyEvent.VK_C);
        calculateButton.addActionListener(e -> calculate());

        resultField.setFocusable(false);
        add(createTitleWrapper(inputField, "Input"));
        add(createTitleWrapper(fromCombo, "From"));
        add(createTitleWrapper(toCombo, "To"));
        add(createTitleWrapper(resultField, "Result"));
        add(calculateButton);
    }

    private void calculate() {
        String inputText = inputField.getText().trim();
        try {
            double input = Double.parseDouble(inputText);
            Measure fromMeasure = (Measure) fromCombo.getSelectedItem();
            Measure toMeasure = (Measure) toCombo.getSelectedItem();

            double meter = fromMeasure.toMeter(input);
            double result = toMeasure.fromMeter(meter);
            String resultText = String.format("%.02f", result);
            resultField.setText(resultText);
        } catch (NumberFormatException e) {
            // e.printStackTrace();
            // display warning JOptionPane
            inputField.setText("");
            inputField.requestFocusInWindow();
        }
    }

    // creates a border with a title around a component
    private JComponent createTitleWrapper(JComponent component, String title) {
        JPanel wrapperPanel = new JPanel();
        wrapperPanel.add(component);
        wrapperPanel.setBorder(BorderFactory.createTitledBorder(title));
        return wrapperPanel;
    }

    private static void createAndShowGui() {
        Converter2 mainPanel = new Converter2();

        JFrame frame = new JFrame("Converter2");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}