Изучение, будьте любезны ... 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
}
}
The 'JTextField's имеет локальный контекст для' HandleEvent' конструктора, это означает, что они будут недоступны для любой другой части программы/класса. Попробуйте сделать их экземплярами полей уровня. Вы также затеняете переменные кнопки (повторное объявление их как локальных переменных) – MadProgrammer
Выполнение 'HandleEvent event3 = new HandleEvent();' внутри вас слушателя бессмысленно, поскольку экземпляр 'event3' не имеет ничего общего с экземпляром, который является на экране и сгенерировал исходное событие – MadProgrammer
MadProgrammer: Спасибо! Я даже не понял, что я это сделал. Исправлено это и удалено событие 3. Также удалены переменные кнопки, должны ли они быть экземплярами? – CodedMe