2015-10-05 2 views
-2

Изучение, будьте любезны ... First Swing Gui. Я пытаюсь сделать этот графический интерфейс преобразования температуры с помощью SWING. Общий кадр, кажется, работает, и кнопки там, где я хочу, и т. Д. Моя проблема связана с кнопками ... Я не могу заставить их читать температурное поле и отображать их в неизменяемых текстовых полях. У меня есть рабочая версия AWT, но сейчас я пытаюсь это сделать.Преобразование температуры Java Java Swing

public class HandleEvent extends JFrame { 



public double fCalc; 
public double cCalc; 
public double kCalc; 
public Object kTextField = kCalc; 
public Object fTextField = fCalc; 
public Object cTextField = cCalc; 
public Object temperature = new JTextField(12); 




public HandleEvent() { 


    Font font1 = new Font("Arial", Font.BOLD, 12); 

    //Flow layout setup 
    setLayout(new FlowLayout(FlowLayout.LEADING,10,20)); 

    //Temperature label and text field 
    JTextField temperature = new JTextField(12); 
    add(new JLabel("Temperature: ")); 
    temperature.setBackground(Color.WHITE); 
    add(temperature); 

    //Fahrenheit text field and label 
    JTextField fTextField = new JTextField(12); 
    add(fTextField); 
    add(new JLabel("Fahrenheit")); 
    fTextField.setCursor(new Cursor(Cursor.HAND_CURSOR)); 
    fTextField.setEditable(false); 

    //Centrigrade text field and label 
    JTextField cTextField = new JTextField(12); 
    add(cTextField); 
    add(new JLabel("Centigrade")); 
    cTextField.setCursor(new Cursor(Cursor.HAND_CURSOR)); 
    cTextField.setEditable(false); 

    //Kelvin text field and label 
    JTextField kTextField = new JTextField(12); 
    add(kTextField); 
    add(new JLabel("Kelvin")); 
    kTextField.setCursor(new Cursor(Cursor.HAND_CURSOR)); 
    kTextField.setEditable(false); 

    //Creating Fahrenheit, Centigrade, Kelvin buttons 
    JButton centigrade = new JButton("Centigrade"); 
    JButton fahrenheit = new JButton("Fahrenheit"); 
    JButton kelvin = new JButton("Kelvin"); 



    //Fahrenheit properties 
    fahrenheit.setForeground(Color.RED); 
    fahrenheit.setFont(font1); 

    //Centigrade properties 
    centigrade.setForeground(Color.BLUE); 
    centigrade.setFont(font1); 

    //Kelvin properties 
    kelvin.setForeground(Color.MAGENTA); 
    kelvin.setFont(font1); 


    // Create a panel to hold buttons 
    JPanel panel = new JPanel(); 
    panel.add(fahrenheit); 
    panel.add(centigrade); 
    panel.add(kelvin); 


    add(panel); // Add panel to the frame 

    // Register listeners 
    fahrenheitListener listener1 = new fahrenheitListener(); 
    centigradeListener listener2 = new centigradeListener(); 
    kelvinListener listener3 = new kelvinListener(); 


    fahrenheit.addActionListener(listener1); 
    centigrade.addActionListener(listener2); 
    kelvin.addActionListener(listener3); 




} 

public static void main(String[] args) { 
    JFrame frame = new HandleEvent(); 
    frame.setTitle("Temperature Converter"); 
    frame.setSize(309, 259); 
    frame.setLocationRelativeTo(null); // Center the frame 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setVisible(true); 


} 


class fahrenheitListener implements ActionListener { 


    public double fCalc; 
    public double cCalc; 
    public double kCalc; 
    public Object kTextField = kCalc; 
    public Object fTextField = fCalc; 
    public Object cTextField = cCalc; 
    public Object temperature = new JTextField(12); 

    public void actionPerformed(ActionEvent e) { 
     //returns the object on which the Event initially occurred 

     // FAHRENHEIT CALC 
     if (e.getSource() == temperature) { 
      try { 
       fCalc = Double.parseDouble(((AbstractButton) temperature).getText()); 
      } //ends try 
      catch (NumberFormatException nfe) { 
       JOptionPane.showMessageDialog(null,"Invalid Input Try Again","Non-numeric",JOptionPane.ERROR_MESSAGE); 
      } //ends catch 

     cCalc = (fCalc - 32)/1.8; 
      kCalc = cCalc + 273.16; 
      DecimalFormat df = new DecimalFormat("#,##0"); 

      ((AbstractButton) fTextField).setText(df.format(fTextField)); 
      ((AbstractButton) cTextField).setText(df.format(cTextField)); 
      ((AbstractButton) kTextField).setText(df.format(kTextField)); 
     } //ends if 
    } 
} 

class centigradeListener implements ActionListener { 


    public double fCalc; 
    public double cCalc; 
    public double kCalc; 
    public Object kTextField = kCalc; 
    public Object fTextField = fCalc; 
    public Object cTextField = cCalc; 
    public Object temperature = new JTextField(12); 

    public void actionPerformed(ActionEvent e) { 
     //returns the object on which the Event initially occurred 


     // CENTIGRADE CALC 
     if (e.getSource() == temperature) { 
      try { 
       cCalc = Double.parseDouble(((JTextComponent) temperature).getText()); 
      } //ends try 
      catch (NumberFormatException nfe) { 
       JOptionPane.showMessageDialog(null,"Invalid Input Try Again","Non-numeric",JOptionPane.ERROR_MESSAGE); 
      } //ends catch 

      fCalc = (cCalc * 9)/5 + 32; 
      kCalc = cCalc + 273.16; 


      DecimalFormat df = new DecimalFormat("#,##0"); 

      ((JTextComponent) fTextField).setText(df.format(fTextField)); 
      ((JTextComponent) cTextField).setText(df.format(cTextField)); 
      ((JTextComponent) kTextField).setText(df.format(kTextField)); 
     } //ends if 
    } 
} 

class kelvinListener implements ActionListener { 

    public double fCalc; 
    public double cCalc; 
    public double kCalc; 
    public Object kTextField = kCalc; 
    public Object fTextField = fCalc; 
    public Object cTextField = cCalc; 
    public Object temperature = new JTextField(12); 

    public void actionPerformed(ActionEvent e) { 
     //returns the object on which the Event initially occurred 



     // KELVIN CALC 
     if (e.getSource() == temperature) { 
      try { 
       kCalc = Double.parseDouble(((JLabel) temperature).getText()); 
      } //ends try 
      catch (NumberFormatException nfe) { 
       JOptionPane.showMessageDialog(null,"Invalid Input Try Again","Non-numeric",JOptionPane.ERROR_MESSAGE); 
      } //ends catch 

      cCalc = kCalc - 273.16; 
      fCalc = 1.8*(kCalc - 273) + 32;  
      DecimalFormat df = new DecimalFormat("#,##0"); 

      ((JLabel) fTextField).setText(df.format(fTextField)); 
      ((JLabel) cTextField).setText(df.format(cTextField)); 
      ((JLabel) kTextField).setText(df.format(kTextField)); 
     } //ends if 
    } //ends method 
} 

}

+0

The 'JTextField's имеет локальный контекст для' HandleEvent' конструктора, это означает, что они будут недоступны для любой другой части программы/класса. Попробуйте сделать их экземплярами полей уровня. Вы также затеняете переменные кнопки (повторное объявление их как локальных переменных) – MadProgrammer

+0

Выполнение 'HandleEvent event3 = new HandleEvent();' внутри вас слушателя бессмысленно, поскольку экземпляр 'event3' не имеет ничего общего с экземпляром, который является на экране и сгенерировал исходное событие – MadProgrammer

+0

MadProgrammer: Спасибо! Я даже не понял, что я это сделал. Исправлено это и удалено событие 3. Также удалены переменные кнопки, должны ли они быть экземплярами? – CodedMe

ответ

1

Там есть несколько способов, вы можете достичь этого, но позволяет работать с концепцией внешних обработчиков событий.

В этом случае, мы только хотим, чтобы выставить функциональные возможности, которые обработчики действительно нужно, чтобы достичь этого, мы можем использовать простой интерфейс

public interface Tempatures { 

    public double getValue(); 
    public void setFahrenheit(double value); 
    public void setCentigrade(double value); 
    public void setKelvin(double value); 

} 

Таким образом, обработчики не нужно заботиться о как генерируется значение или что делается с результатами, только чтобы они могли получить значение и установить результаты.

Хотя вы все еще можете использовать ActionListener, большая часть функций одинакова для каждого обработчика, который просто кричит о лучшем дизайне. Вместо этого я буду использовать Action API и создать abstractAction, который выполняет основные функции, которые являются общими для всех обработчиков

public abstract class TempatureAction extends AbstractAction { 

    private Tempatures tempatures; 

    public TempatureAction(Tempatures tempatures) { 
     this.tempatures = tempatures; 
    } 

    public void actionPerformed(ActionEvent e) { 

     double value = tempatures.getValue(); 
     tempatures.setFahrenheit(toFahrenheit(value)); 
     tempatures.setCentigrade(toCentigrade(value)); 
     tempatures.setKelvin(toKelvin(value)); 

    } 

    public abstract double toFahrenheit(double value); 
    public abstract double toCentigrade(double value); 
    public abstract double toKelvin(double value); 

} 

Теперь это в основном говорит, что реализация этого класса должны обеспечивать функциональные возможности для преобразования заданное значение для разных значений, исходя из его внутренних требований.

Для каждого из обработчиков, они могут просто вернуть value как их переведенной стоимости и использовать другие методы для выполнения фактического перевода, например ...

public class FahrenheitListener extends TempatureAction { 

    public FahrenheitListener(Tempatures tempatures) { 
     super(tempatures); 
     putValue(NAME, "Fahrenheit"); 
    } 

    public double toFahrenheit(double value) { 
     return value; 
    } 

    public double toCentigrade(double value) { 
     return (value - 32)/1.8; 
    } 

    public double toKelvin(double value) { 
     return toCentigrade(value) + 273.16; 
    } 

} 

public class CentigradeListener extends TempatureAction { 

    public CentigradeListener(Tempatures tempatures) { 
     super(tempatures); 
     putValue(NAME, "Centigrade"); 
    } 

    public double toFahrenheit(double value) { 
     return (value * 9)/5 + 32; 
    } 

    public double toCentigrade(double value) { 
     return value; 
    } 

    public double toKelvin(double value) { 
     return toCentigrade(value) + 273.16; 
    } 

} 

public class KelvinListener extends TempatureAction { 

    public KelvinListener(Tempatures tempatures) { 
     super(tempatures); 
     putValue(NAME, "Kelvin"); 
    } 

    public double toFahrenheit(double value) { 
     return 1.8 * (value - 273) + 32; 
    } 

    public double toCentigrade(double value) { 
     return value - 273.16; 
    } 

    public double toKelvin(double value) { 
     return value; 
    } 

} 

И, наконец, мы можем поставить его все вместе ...

public class TestPane extends JPanel implements Tempatures { 

    public JButton fahrenheit; 
    public JButton centigrade; 
    public JButton kelvin; 
    private final JSpinner temperature; 
    private final JFormattedTextField fahrenheitTextField; 
    private final JFormattedTextField centigradeField; 
    private final JFormattedTextField kelvinField; 

    public TestPane() { 
     Font font1 = new Font("Arial", Font.BOLD, 12); 

     //Flow layout setup 
     setLayout(new FlowLayout(FlowLayout.LEADING, 10, 20)); 

     //Temperature label and text field 
     temperature = new JSpinner(new SpinnerNumberModel(0d, null, null, 0.5d)); 
     add(new JLabel("Temperature: ")); 
     temperature.setBackground(Color.WHITE); 
     add(temperature); 

     //Fahrenheit text field and label 
     fahrenheitTextField = new JFormattedTextField(NumberFormat.getNumberInstance()); 
     add(fahrenheitTextField); 
     add(new JLabel("Fahrenheit")); 
     fahrenheitTextField.setCursor(new Cursor(Cursor.HAND_CURSOR)); 
     fahrenheitTextField.setEditable(false); 
     fahrenheitTextField.setColumns(8); 

     //Centrigrade text field and label 
     centigradeField = new JFormattedTextField(NumberFormat.getNumberInstance()); 
     add(centigradeField); 
     add(new JLabel("Centigrade")); 
     centigradeField.setCursor(new Cursor(Cursor.HAND_CURSOR)); 
     centigradeField.setEditable(false); 
     centigradeField.setColumns(8); 

     //Kelvin text field and label 
     kelvinField = new JFormattedTextField(NumberFormat.getNumberInstance()); 
     add(kelvinField); 
     add(new JLabel("Kelvin")); 
     kelvinField.setCursor(new Cursor(Cursor.HAND_CURSOR)); 
     kelvinField.setEditable(false); 
     kelvinField.setColumns(8); 

     //Creating Fahrenheit, Centigrade, Kelvin buttons 
     centigrade = new JButton("Centigrade"); 
     fahrenheit = new JButton("Fahrenheit"); 
     kelvin = new JButton("Kelvin"); 

     //Fahrenheit properties 
     fahrenheit.setForeground(Color.RED); 
     fahrenheit.setFont(font1); 

     //Centigrade properties 
     centigrade.setForeground(Color.BLUE); 
     centigrade.setFont(font1); 

     //Kelvin properties 
     kelvin.setForeground(Color.MAGENTA); 
     kelvin.setFont(font1); 

     // Create a panel to hold buttons 
     JPanel panel = new JPanel(); 
     panel.add(fahrenheit); 
     panel.add(centigrade); 
     panel.add(kelvin); 

     add(panel); // Add panel to the frame 

     fahrenheit.setAction(new FahrenheitListener(this)); 
     centigrade.setAction(new CentigradeListener(this)); 
     kelvin.setAction(new KelvinListener(this)); 
    } 

    @Override 
    public double getValue() { 
     return (Double) temperature.getValue(); 
    } 

    @Override 
    public void setFahrenheit(double value) { 
     fahrenheitTextField.setValue(value); 
    } 

    @Override 
    public void setCentigrade(double value) { 
     centigradeField.setValue(value); 
    } 

    @Override 
    public void setKelvin(double value) { 
     kelvinField.setValue(value); 
    } 

} 

См How to Use Actions для более подробной информации

Также посмотрите на How to Use Spinners в й How to Use Formatted Text Fields, которые имеют дело с большей частью проверки пользовательского ввода и автоматическим форматированием для вас

Runnable примера ...

import java.awt.Color; 
import java.awt.Cursor; 
import java.awt.Dimension; 
import java.awt.EventQueue; 
import java.awt.FlowLayout; 
import java.awt.Font; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.event.ActionEvent; 
import java.text.NumberFormat; 
import javax.swing.AbstractAction; 
import javax.swing.JButton; 
import javax.swing.JFormattedTextField; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.JSpinner; 
import javax.swing.SpinnerNumberModel; 
import javax.swing.UIManager; 
import javax.swing.UnsupportedLookAndFeelException; 

public class TempatureCalculator { 

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

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

       JFrame frame = new JFrame("Testing"); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.add(new TestPane()); 
       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }); 
    } 

    public class TestPane extends JPanel implements Tempatures { 

     public JButton fahrenheit; 
     public JButton centigrade; 
     public JButton kelvin; 
     private final JSpinner temperature; 
     private final JFormattedTextField fahrenheitTextField; 
     private final JFormattedTextField centigradeField; 
     private final JFormattedTextField kelvinField; 

     public TestPane() { 
      Font font1 = new Font("Arial", Font.BOLD, 12); 

      //Flow layout setup 
      setLayout(new FlowLayout(FlowLayout.LEADING, 10, 20)); 

      //Temperature label and text field 
      temperature = new JSpinner(new SpinnerNumberModel(0d, null, null, 0.5d)); 
      add(new JLabel("Temperature: ")); 
      temperature.setBackground(Color.WHITE); 
      add(temperature); 

      //Fahrenheit text field and label 
      fahrenheitTextField = new JFormattedTextField(NumberFormat.getNumberInstance()); 
      add(fahrenheitTextField); 
      add(new JLabel("Fahrenheit")); 
      fahrenheitTextField.setCursor(new Cursor(Cursor.HAND_CURSOR)); 
      fahrenheitTextField.setEditable(false); 
      fahrenheitTextField.setColumns(8); 

      //Centrigrade text field and label 
      centigradeField = new JFormattedTextField(NumberFormat.getNumberInstance()); 
      add(centigradeField); 
      add(new JLabel("Centigrade")); 
      centigradeField.setCursor(new Cursor(Cursor.HAND_CURSOR)); 
      centigradeField.setEditable(false); 
      centigradeField.setColumns(8); 

      //Kelvin text field and label 
      kelvinField = new JFormattedTextField(NumberFormat.getNumberInstance()); 
      add(kelvinField); 
      add(new JLabel("Kelvin")); 
      kelvinField.setCursor(new Cursor(Cursor.HAND_CURSOR)); 
      kelvinField.setEditable(false); 
      kelvinField.setColumns(8); 

      //Creating Fahrenheit, Centigrade, Kelvin buttons 
      centigrade = new JButton("Centigrade"); 
      fahrenheit = new JButton("Fahrenheit"); 
      kelvin = new JButton("Kelvin"); 

      //Fahrenheit properties 
      fahrenheit.setForeground(Color.RED); 
      fahrenheit.setFont(font1); 

      //Centigrade properties 
      centigrade.setForeground(Color.BLUE); 
      centigrade.setFont(font1); 

      //Kelvin properties 
      kelvin.setForeground(Color.MAGENTA); 
      kelvin.setFont(font1); 

      // Create a panel to hold buttons 
      JPanel panel = new JPanel(); 
      panel.add(fahrenheit); 
      panel.add(centigrade); 
      panel.add(kelvin); 

      add(panel); // Add panel to the frame 

      fahrenheit.setAction(new FahrenheitListener(this)); 
      centigrade.setAction(new CentigradeListener(this)); 
      kelvin.setAction(new KelvinListener(this)); 
     } 

     @Override 
     public Dimension getPreferredSize() { 
      return new Dimension(200, 200); 
     } 

     protected void paintComponent(Graphics g) { 
      super.paintComponent(g); 
      Graphics2D g2d = (Graphics2D) g.create(); 
      g2d.dispose(); 
     } 

     @Override 
     public double getValue() { 
      return (Double) temperature.getValue(); 
     } 

     @Override 
     public void setFahrenheit(double value) { 
      fahrenheitTextField.setValue(value); 
     } 

     @Override 
     public void setCentigrade(double value) { 
      centigradeField.setValue(value); 
     } 

     @Override 
     public void setKelvin(double value) { 
      kelvinField.setValue(value); 
     } 

    } 

    public interface Tempatures { 

     public double getValue(); 

     public void setFahrenheit(double value); 

     public void setCentigrade(double value); 

     public void setKelvin(double value); 

    } 

    public abstract class TempatureAction extends AbstractAction { 

     private Tempatures tempatures; 

     public TempatureAction(Tempatures tempatures) { 
      this.tempatures = tempatures; 
     } 

     public void actionPerformed(ActionEvent e) { 

      double value = tempatures.getValue(); 
      tempatures.setFahrenheit(toFahrenheit(value)); 
      tempatures.setCentigrade(toCentigrade(value)); 
      tempatures.setKelvin(toKelvin(value)); 

     } 

     public abstract double toFahrenheit(double value); 

     public abstract double toCentigrade(double value); 

     public abstract double toKelvin(double value); 

    } 

    public class FahrenheitListener extends TempatureAction { 

     public FahrenheitListener(Tempatures tempatures) { 
      super(tempatures); 
      putValue(NAME, "Fahrenheit"); 
     } 

     public double toFahrenheit(double value) { 
      return value; 
     } 

     public double toCentigrade(double value) { 
      return (value - 32)/1.8; 
     } 

     public double toKelvin(double value) { 
      return toCentigrade(value) + 273.16; 
     } 

    } 

    public class CentigradeListener extends TempatureAction { 

     public CentigradeListener(Tempatures tempatures) { 
      super(tempatures); 
      putValue(NAME, "Centigrade"); 
     } 

     public double toFahrenheit(double value) { 
      return (value * 9)/5 + 32; 
     } 

     public double toCentigrade(double value) { 
      return value; 
     } 

     public double toKelvin(double value) { 
      return toCentigrade(value) + 273.16; 
     } 

    } 

    public class KelvinListener extends TempatureAction { 

     public KelvinListener(Tempatures tempatures) { 
      super(tempatures); 
      putValue(NAME, "Kelvin"); 
     } 

     public double toFahrenheit(double value) { 
      return 1.8 * (value - 273) + 32; 
     } 

     public double toCentigrade(double value) { 
      return value - 273.16; 
     } 

     public double toKelvin(double value) { 
      return value; 
     } 

    } 
} 
Смежные вопросы