简体   繁体   中英

Need Java Help with Combining Multiple Classes in Gui

I have prepared 2 classes which perform a function that I would like to wrap up in one nice easy to use GUI.

Here is the first class:

import java.util.Scanner;
import java.text.*;

public class inputDecimal {

    Scanner input = new Scanner( System.in );    
DecimalFormat  decConv =  new DecimalFormat("00.00");

double dec;
double remain;
double remaindb;
double mindb;
int deg;
int min;
double sec;

System.out.print("Enter the Decimal Coordinate: ");
dec = input.nextDouble();

deg = (int)dec;
remain = dec - deg;
remaindb = remain * 60;
min = (int)remaindb;
mindb = remaindb - min;
sec = mindb * 60;

System.out.printf("Your Coordinate Equals "+deg+"\u00b0"+min+"'"+decConv.format(sec)+"\"\n");

}

Here is the second class:

import java.util.Scanner;
import java.text.*;

class inputDegree {

   Scanner input = new Scanner( System.in );            
   DecimalFormat  decConv =  new DecimalFormat("000.000");

double deg;
double min;
double sec;
double degadd;
double minup;
double minadd;
double dec;

System.out.print("Enter the Degrees: ");
deg = input.nextDouble();

System.out.print("Enter the Minutes: ");
min = input.nextDouble();

System.out.print("Enter the Seconds: ");
sec = input.nextDouble();   

degadd = sec / 60;
minup = degadd + min;
minadd = minup / 60;
dec = deg + minadd;

System.out.printf("Your Converted Coordinate Equals "+ decConv.format(dec) +"\n");



 }

Okay, so that lays out the 2 main functions that I need to fill. Now, the piece I am looking to have help with is to create a main class which would call on these two classes as necessary. Pretty much I just want the gui to present 2 buttons. One button says "Input Degree" and the other says "Input Decimal." Then, when the user clicks on one of the buttons it will call the corresponding class and ask for the input.

Thank you for helping me with this issue. I am new to Java and coding for that matter, so this is really going to help connect some of the pieces of this process that I have been struggling with recently.

================================

This rest are follow-up comments as this question has developed:

I have followed along through your answer (Aleksi) and there are a few quick follow-up questions:

(1) In response to the question "are you sure you want a GUI not just a text interface?" My answer is no, I am not sure. I would like to ultimately create a GPS converter that I can embed on a website. So, whatever format I can do that with best is what I am after.

(2) When I try to compile the final code that you provided titled 'AwesomeGUI.java' I get the following errors:

AwesomeGUI.java:137: cannot find symbol
symbol  : method isEmpty()
location: class java.lang.String
  if (textField.getText().isEmpty()) {
                       ^
AwesomeGUI.java:146: method does not override a method from its superclass
@Override
 ^
AwesomeGUI.java:161: method does not override a method from its superclass
@Override
 ^
3 errors

(3) Otherwise, I was able to compile the program through the stepwise process you provided. Really I just want to make a program which asks the user if they would like to convert either a decimal or degree based GPS unit. Then they click on the appropriate button and they are asked to fill in the form to convert.

I know I am getting a bit too detailed with my needs rather than asking a specific question, but it is my hope that by providing what I ultimately want to have here then you may be able to point me in the right direction.

Many many thanks to all who have helped me with this.

================================

Second Follow-Up Round

I have been trying to upgrade to Java 6 with no luck, so I am stuck with 5. With that being the case, could you please elaborate on the addition of

java.util.regex.Pattern.matches("^\\s*$", textField.getText());

Do I import it at the start of the code? If so, do I only import on the AwesomeGUI.java class?

Or, does this code function in a different manner?

many thanks, presto

I will try to find time to dig into this a bit further but we'll start with the minimal solution to get things working together.

First of we'll need to get the classes to compile. In Java, all processing should be done inside methods. You are already familiar with public static void main(String[] args) {} method. Now we are going to make methods inside your classes

import java.util.Scanner;
import java.text.*;

public class InputDecimal {

  Scanner input = new Scanner(System.in);
  DecimalFormat decConv = new DecimalFormat("00.00");

  public void askForDecimalCoordinateAndPrintDegrees() {

    double dec;
    double remain;
    double remaindb;
    double mindb;
    int deg;
    int min;
    double sec;

    System.out.print("Enter the Decimal Coordinate: ");
    dec = input.nextDouble();

    deg = (int) dec;
    remain = dec - deg;
    remaindb = remain * 60;
    min = (int) remaindb;
    mindb = remaindb - min;
    sec = mindb * 60;

    System.out.printf("Your Coordinate Equals " + deg + "\u00b0" + min + "'"
        + decConv.format(sec) + "\"\n");

  }
}

and

import java.util.Scanner;
import java.text.*;

class InputDegree {

  Scanner input = new Scanner(System.in);
  DecimalFormat decConv = new DecimalFormat("000.000");

  double deg;
  double min;
  double sec;
  double degadd;
  double minup;
  double minadd;
  double dec;

  public void askForDegreesAndPrintDecimal() {

    System.out.print("Enter the Degrees: ");
    deg = input.nextDouble();

    System.out.print("Enter the Minutes: ");
    min = input.nextDouble();

    System.out.print("Enter the Seconds: ");
    sec = input.nextDouble();

    degadd = sec / 60;
    minup = degadd + min;
    minadd = minup / 60;
    dec = deg + minadd;

    System.out.printf("Your Converted Coordinate Equals " + decConv.format(dec)
        + "\n");

  }

}

You'll see that we've added a method called askForDecimalCoordinateAndPrintDegrees to the class InputDecimal and askForDegreesAndPrintDecimal to the class InputDegrees. These methods contain all the functionality you had before in your main method.

Then we start work with our GUI (are you sure you want a GUI not just a text interface). In the GUI we'll have the main-method that calls both InputDecimal and InputDegree. Before calling them, we have to create instances of them as the methods we added aren't declared static.

The first version might look something like this

public class TheAwesomeGUI {

  public static void main(String[] args) {
    InputDecimal decimalInput = new InputDecimal();
    InputDegree degreeInput = new InputDegree();

    decimalInput.askForDecimalCoordinateAndPrintDegrees();
    degreeInput.askForDegreesAndPrintDecimal();
  }

}

Now we immediately notice that the code has a bit of an odor: we have too methods with an and in their name. It easy to see that these methods do more than one thing. After a while of thought we might come to the conclusion that we have a concept called a coordinate in our hands. Let's specify what it is?

  • A coordinate represent either the latitude or the longitude
  • A coordinate may be represented as a decimal number
  • A coordinate may be represented as degrees
  • The user should be able to enter the coordinate using either of its representations
  • The user should be able to print the coordinate using either of its representations
  • There exists formulas to convert between the two that you have implemented in your code.

Now, we might create a class that represents the concept of a coordinate:

import java.text.DecimalFormat;

public class Coordinate {

  DecimalFormat decConv = new DecimalFormat("00.00");

  double dec;
  double remain;
  double remaindb;
  double mindb;
  int deg;
  int min;
  double sec;

  double degadd;
  double minup;
  double minadd;

  public static Coordinate createFromDecimal(double decimalValue) {
    return new Coordinate(decimalValue);
  }

  public static Coordinate createFromDegrees(int degrees, int minutes,
      double seconds) {
    return new Coordinate(degrees,minutes,seconds);
  }

  private Coordinate(double decimalValue) {
    dec = decimalValue;
    deg = (int) dec;
    remain = dec - deg;
    remaindb = remain * 60;
    min = (int) remaindb;
    mindb = remaindb - min;
    sec = mindb * 60;
  }

  private Coordinate(int degrees, int minutes, double seconds) {
    deg = degrees;
    min = minutes;
    sec = seconds;
    degadd = sec / 60;
    minup = degadd + min;
    minadd = minup / 60;
    dec = deg + minadd;
  }

  public void printCoordinateAsDegrees() {
    System.out.printf("Your Coordinate Equals " + deg + "\u00b0" + min + "'"
        + decConv.format(sec) + "\"\n");

  }

  public void printCoordinateAsDecimal() {
    System.out.printf("Your Converted Coordinate Equals " + decConv.format(dec)
        + "\n");
  }

}

What we've done is we have combined the InputDegree and InputDecimal classes in a way that we have two separate methods for Coordinate, one creates a new coordinate based on a decimal coordinate and the other uses degrees. I did some magic back there as well: I hid the constructors from sight and used static methods instead because it seemed more legible to have Coordinate.createFromDecimal(decimal) that new Coordinate(decimal).

Now that we have changed the InputDegree and InputDecimal classes we have to change our GUI class.

import java.util.Scanner;

public class TheAwesomeGUI {

  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    Coordinate coordinate;

    coordinate = askCoordinateInDecimal(input);
    coordinate.printCoordinateAsDegrees();

    coordinate = askCoordinateInDegrees(input);
    coordinate.printCoordinateAsDecimal();
  }

  protected static Coordinate askCoordinateInDecimal(Scanner input) {
    System.out.print("Enter the Decimal Coordinate:  ");
    double dec = input.nextDouble();
    return Coordinate.createFromDecimal(dec);
  }

  protected static Coordinate askCoordinateInDegrees(Scanner input) {
    System.out.print("Enter the Degrees: ");
    int deg = input.nextInt();

    System.out.print("Enter the Minutes: ");
    int min = input.nextInt();

    System.out.print("Enter the Seconds: ");
    double sec = input.nextDouble();

    return Coordinate.createFromDegrees(deg, min, sec);
  }

}

You might notice that we've moved the input to the GUI class. We've also created convenience methods to create the coordinates based on user input. To the user the program looks exactly the same as before. As an added benefit, we can now print the coordinate that has been defined in decimal both in decimal and in degrees. Fancy that!

Next we'll do a very small change. There are a couple of variables that are used to help convert degrees to decimal and vice versa. I'd like to reduce their scope ie I'd like to hide them from sight if we don't need them.

import java.text.DecimalFormat;

public class Coordinate {

  DecimalFormat decConv = new DecimalFormat("00.00");

  double dec;
  int deg;
  int min;
  double sec;

  public static Coordinate createFromDecimal(double decimalValue) {
    return new Coordinate(decimalValue);
  }

  public static Coordinate createFromDegrees(int degrees, int minutes,
      double seconds) {
    return new Coordinate(degrees,minutes,seconds);
  }

  private Coordinate(double decimalValue) {
    dec = decimalValue;
    deg = (int) dec;
    double remain = dec - deg;
    double remaindb = remain * 60;
    min = (int) remaindb;
    double mindb = remaindb - min;
    sec = mindb * 60;
  }

  private Coordinate(int degrees, int minutes, double seconds) {
    deg = degrees;
    min = minutes;
    sec = seconds;
    double degadd = sec / 60;
    double minup = degadd + min;
    double minadd = minup / 60;
    dec = deg + minadd;
  }

  public void printCoordinateAsDegrees() {
    System.out.printf("Your Coordinate Equals " + deg + "\u00b0" + min + "'"
        + decConv.format(sec) + "\"\n");

  }

  public void printCoordinateAsDecimal() {
    System.out.printf("Your Converted Coordinate Equals " + decConv.format(dec)
        + "\n");
  }

}

Then we notice that there are still two responsibilities in the Coordinate class. It has to convert coordinates between decimals and degrees AND print them. Let's get rid of printing. When we get rid of printing, we must make sure that we can get to the coordinates data somehow. That's why we'll add methods that will tell us the coordinates value as decimal and the coordinates value in degrees, minutes and seconds.

public class Coordinate {

  double dec;
  int deg;
  int min;
  double sec;

  public static Coordinate createFromDecimal(double decimalValue) {
    return new Coordinate(decimalValue);
  }

  public static Coordinate createFromDegrees(int degrees, int minutes,
      double seconds) {
    return new Coordinate(degrees,minutes,seconds);
  }

  private Coordinate(double decimalValue) {
    dec = decimalValue;
    deg = (int) dec;
    double remain = dec - deg;
    double remaindb = remain * 60;
    min = (int) remaindb;
    double mindb = remaindb - min;
    sec = mindb * 60;
  }

  private Coordinate(int degrees, int minutes, double seconds) {
    deg = degrees;
    min = minutes;
    sec = seconds;
    double degadd = sec / 60;
    double minup = degadd + min;
    double minadd = minup / 60;
    dec = deg + minadd;
  }

  public int getDegrees() {
    return deg;
  }

  public int getMinutes() {
    return min;
  }

  public double getSeconds() {
    return sec;
  } 

  public double asDecimal() {
    return dec;
  }

}

Now the printing has to be done in our GUI

import java.text.DecimalFormat;
import java.util.Scanner;

public class TheAwesomeGUI {

  static DecimalFormat decConv = new DecimalFormat("00.00");

  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    Coordinate coordinate;

    coordinate = askCoordinateInDecimal(input);
    printCoordinateAsDegrees(coordinate);
    coordinate = askCoordinateInDegrees(input);
    printCoordinateAsDecimal(coordinate);
  }

  public static void printCoordinateAsDecimal(Coordinate coordinate) {
    System.out.printf("Your Converted Coordinate Equals " + decConv.format(coordinate.asDecimal())
        + "\n");
  }

  private static void printCoordinateAsDegrees(Coordinate coordinate) {
    System.out.printf("Your Coordinate Equals " + coordinate.getDegrees() + "\u00b0" + coordinate.getMinutes() + "'"
        + decConv.format(coordinate.getSeconds()) + "\"\n");
  }

  private static Coordinate askCoordinateInDecimal(Scanner input) {
    System.out.print("Enter the Decimal Coordinate:  ");
    double dec = input.nextDouble();
    return Coordinate.createFromDecimal(dec);
  }

  private static Coordinate askCoordinateInDegrees(Scanner input) {
    System.out.print("Enter the Degrees: ");
    int deg = input.nextInt();

    System.out.print("Enter the Minutes: ");
    int min = input.nextInt();

    System.out.print("Enter the Seconds: ");
    double sec = input.nextDouble();

    return Coordinate.createFromDegrees(deg, min, sec);
  }

}

We have added convenience methods printCoordinateAsDegrees and printCoordinateAsDecimal to contain the implementation we just took from the Coordinate class. But having a method that boths prints and formats will make our job harder when we create an actual GUI - let's separate these tasks! The following is just an excerpt from the GUI class

private static void printCoordinateAsDecimal(Coordinate coordinate) {
    System.out.printf("Your Converted Coordinate Equals "
        + asDecimal(coordinate) + "\n");
  }

  private static void printCoordinateAsDegrees(Coordinate coordinate) {
    System.out.printf("Your Coordinate Equals " + asDegrees(coordinate) + "\n");
  }

  private static String asDegrees(Coordinate coordinate) {
    return coordinate.getDegrees() + "\u00b0" + coordinate.getMinutes() + "'"
        + decConv.format(coordinate.getSeconds()) + "\"";
  }

  private static String asDecimal(Coordinate coordinate) {
    return decConv.format(coordinate.asDecimal());
  }

Now I feel a bit more confident about writing a GUI for this. Make sure to read about Swing in you spare time because some magical steps are about to happen. So here's the messy version

import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;

import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class AwesomeGUI {

  private JFormattedTextField minutesInput;
  private JFormattedTextField decimalInput;
  private JFormattedTextField secondsInput;
  private JFormattedTextField degreesInput;

  private final class DecimalToDegreesListener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent event) {
      if (decimalInput.getText().isEmpty()) {
        return;
      }
      try {
        JFormattedTextField.AbstractFormatter f = decimalInput.getFormatter();
        Coordinate coordinate = Coordinate.createFromDecimal(((Number) f
            .stringToValue(decimalInput.getText())).doubleValue());
        degreesInput.setText(String.valueOf(coordinate.getDegrees()));
        minutesInput.setText(String.valueOf(coordinate.getMinutes()));
        secondsInput.setText(decConv.format(coordinate.getSeconds()));
      } catch (ParseException e) {
        throw new IllegalArgumentException(
            "Decimal input was not a decimal number");
      }
    }
  }

  private final class DegreesToDecimalListener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent event) {
      // Require all input fields to be filled
      if (degreesInput.getText().isEmpty() || minutesInput.getText().isEmpty()
          || secondsInput.getText().isEmpty()) {
        return;
      }
      try {
        int degrees = Integer.valueOf(degreesInput.getText());

        int minutes = Integer.valueOf(minutesInput.getText());
        JFormattedTextField.AbstractFormatter f = secondsInput.getFormatter();

        double seconds = ((Number) f.stringToValue(secondsInput.getText()))
            .doubleValue();
        Coordinate coordinate = Coordinate.createFromDegrees(degrees, minutes,
            seconds);
        decimalInput.setText(decConv.format(coordinate.asDecimal()));
      } catch (ParseException e) {
        throw new IllegalArgumentException(
            "Seconds input was not a decimal number");
      }
    }
  }

  static DecimalFormat decConv = new DecimalFormat("00.00");
  private JButton convertDegreesToDecimal;
  private JButton convertDecimalToDegreesButton;

  public AwesomeGUI() {
    JFrame window = new JFrame();
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setVisible(true);

    window.setLayout(new GridLayout(2, 1));

    window.add(createDecimalInputPanel());
    window.add(createDegreesInputPanel());

    convertDecimalToDegreesButton
        .addActionListener(new DecimalToDegreesListener());
    convertDegreesToDecimal.addActionListener(new DegreesToDecimalListener());

    window.pack();

  }

  protected JPanel createDecimalInputPanel() {
    JPanel decimalPanel = new JPanel();
    decimalPanel.setLayout(new FlowLayout());
    decimalInput = new JFormattedTextField(
        DecimalFormat.getInstance());
    decimalInput.setColumns(5);
    convertDecimalToDegreesButton = new JButton("convert");
    decimalPanel.add(new JLabel("Decimal Coordinate"));
    decimalPanel.add(decimalInput);
    decimalPanel.add(convertDecimalToDegreesButton);
    return decimalPanel;
  }

  private JPanel createDegreesInputPanel() {
    JPanel degreesPanel = new JPanel();
    degreesPanel.setLayout(new FlowLayout());
    degreesInput = new JFormattedTextField(
        NumberFormat.getIntegerInstance());
    degreesInput.setColumns(2);
    minutesInput = new JFormattedTextField(
        NumberFormat.getIntegerInstance());
    minutesInput.setColumns(2);
    secondsInput = new JFormattedTextField(
        DecimalFormat.getInstance());
    secondsInput.setColumns(5);

    convertDegreesToDecimal = new JButton("convert");
    degreesPanel.add(new JLabel("degrees"));
    degreesPanel.add(degreesInput);
    degreesPanel.add(new JLabel("\u00b0 minutes"));
    degreesPanel.add(minutesInput);
    degreesPanel.add(new JLabel("' seconds"));
    degreesPanel.add(secondsInput);
    degreesPanel.add(new JLabel("\""));
    degreesPanel.add(convertDegreesToDecimal);

    return degreesPanel;
  }

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

}

And after a bit of a clean up we get the following. It is a bit longer and hopefully a lot clearer. What I've done is I've tried to raise the level of abstraction by creating more methods for recurring tasks and to group instructions together. For example, when I want the decimal value of an JFormattedTextField, I'd rather say asDouble(textField) or doubleValueOf(textField) than ((Number)(textField.getFormatter().stringAsValue(textField.getText())).doubleValue()

import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.text.Format;
import java.text.NumberFormat;
import java.text.ParseException;

import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class AwesomeGUI {

  private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("00.00");
  private static final int COLUMNS_IN_INTEGER_INPUT_TEXTFIELD = 2;
  private static final int COLUMNS_IN_DECIMAL_INPUT_TEXTFIELD = 4;

  private JFormattedTextField degreesInDecimalInput;

  private JFormattedTextField degreesInput;
  private JFormattedTextField minutesInput;
  private JFormattedTextField secondsInput;

  private JButton convertDegreesToDecimalButton;
  private JButton convertDecimalToDegreesButton;

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

  public AwesomeGUI() {
    final JFrame window = new JFrame();
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    window.setLayout(new GridLayout(2, 1));
    window.add(createDecimalInputPanel());
    window.add(createDegreesInputPanel());

    convertDecimalToDegreesButton
        .addActionListener(new DecimalToDegreesListener());
    convertDegreesToDecimalButton.addActionListener(new DegreesToDecimalListener());

    window.setVisible(true);
    window.pack();
  }

  private JPanel createDecimalInputPanel() {
    final JPanel decimalPanel = createElementsInDecimalInputPanel();
    layoutElementInDecimalInputPanel(decimalPanel);
    return decimalPanel;
  }

  private JPanel createElementsInDecimalInputPanel() {
    final JPanel decimalPanel = new JPanel();
    degreesInDecimalInput = createDecimalInput();
    convertDecimalToDegreesButton = new JButton("convert");
    return decimalPanel;
  }

  private void layoutElementInDecimalInputPanel(final JPanel decimalPanel) {
    decimalPanel.setLayout(new FlowLayout());
    decimalPanel.add(new JLabel("Decimal Coordinate"));
    decimalPanel.add(degreesInDecimalInput);
    decimalPanel.add(convertDecimalToDegreesButton);
  }

  private JPanel createDegreesInputPanel() {
    final JPanel degreesPanel = createElementsInDegreesInputPanel();
    layoutElementsInDegreesInputPanel(degreesPanel);
    return degreesPanel;
  }

  private JPanel createElementsInDegreesInputPanel() {
    final JPanel degreesPanel = new JPanel();
    degreesInput = createIntegerInput();
    minutesInput = createIntegerInput();
    secondsInput = createDecimalInput();
    convertDegreesToDecimalButton = new JButton("convert");
    return degreesPanel;
  }

  private void layoutElementsInDegreesInputPanel(final JPanel degreesPanel) {
    degreesPanel.setLayout(new FlowLayout());
    degreesPanel.add(new JLabel("Degrees: "));
    degreesPanel.add(degreesInput);
    degreesPanel.add(new JLabel("\u00b0"));
    degreesPanel.add(minutesInput);
    degreesPanel.add(new JLabel("'"));
    degreesPanel.add(secondsInput);
    degreesPanel.add(new JLabel("\""));
    degreesPanel.add(convertDegreesToDecimalButton);
  }

  private JFormattedTextField createDecimalInput() {
    return createFormattedTextInput(DecimalFormat.getInstance(),
        COLUMNS_IN_DECIMAL_INPUT_TEXTFIELD);
  }

  private JFormattedTextField createIntegerInput() {
    return createFormattedTextInput(NumberFormat.getIntegerInstance(),
        COLUMNS_IN_INTEGER_INPUT_TEXTFIELD);
  }

  private JFormattedTextField createFormattedTextInput(Format format,
      int columns) {
    final JFormattedTextField textField = new JFormattedTextField(format);
    textField.setColumns(columns);
    return textField;
  }

  private double asDouble(final JFormattedTextField decimalInput) {
    return formattedValueOf(decimalInput).doubleValue();
  }

  private int asInteger(final JFormattedTextField integerInput) {
    return formattedValueOf(integerInput).intValue();
  }

  private Number formattedValueOf(final JFormattedTextField numericInput) {
    try {
      final JFormattedTextField.AbstractFormatter f = numericInput
          .getFormatter();
      return ((Number) f.stringToValue(numericInput.getText()));
    } catch (ParseException e) {
      throw new IllegalStateException(
          "Text field did not contain a number with the correct format. Value found was "
              + numericInput.getText(), e);
    }
  }

  private boolean containsAnEmptyValue(JFormattedTextField... textFields) {
    for (JFormattedTextField textField : textFields) {
      if (textField.getText().isEmpty()) {
        return true;
      }
    }
    return false;
  }

  private final class DecimalToDegreesListener implements ActionListener {

    @Override
    public void actionPerformed(final ActionEvent event) {
      if (containsAnEmptyValue(degreesInDecimalInput)) {
        return;
      }
      final Coordinate coordinate = Coordinate
          .createFromDecimal(asDouble(degreesInDecimalInput));
      degreesInput.setText(String.valueOf(coordinate.getDegrees()));
      minutesInput.setText(String.valueOf(coordinate.getMinutes()));
      secondsInput.setText(DECIMAL_FORMAT.format(coordinate.getSeconds()));
    }
  }

  private final class DegreesToDecimalListener implements ActionListener {

    @Override
    public void actionPerformed(final ActionEvent event) {
      if (containsAnEmptyValue(degreesInput, minutesInput, secondsInput)) {
        return;
      }
      final Coordinate coordinate = Coordinate.createFromDegrees(
          asInteger(degreesInput), asInteger(minutesInput),
          asDouble(secondsInput));
      degreesInDecimalInput.setText(DECIMAL_FORMAT.format(coordinate.asDecimal()));
    }
  }

}

The main thing to notice when we change to a Swing based GUI is that the control flow is inverted. At first we defined for ourselves what methods were called and in which order. By using Swing we give control to the Swing framework that calls our methods on user generated events eg click of a button. For each event you want to process, you must define a listener that gets notified of the event.

The other thing is that we have to write quite a lot of code to describe the user interface. The UI is defined using a set of hierarchical elements. At the top we have a window. The window is split into a grid with two rows and a column. The upper cell in the grid is populated with three elements flowing from left to right. The lower cell is similar but with a few more items.

Does your code even compile? You should do your best to post runnable or at least compilable code when asking a quesion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM