试图在 JAVA 中向已制作的程序添加按钮。它将温度从华氏温度转换为摄氏度。我的按钮不会出现。我错过了一些东西。这个想法是您将能够同时按下回车键或按钮来获得结果。该程序的主要部分是:
import javax.swing.JFrame;
public class Fahrenheit
{
public static void main (String[] args)
{
JFrame frame = new JFrame ("Fahrenheit");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
FahrenheitPanel panel = new FahrenheitPanel();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
然后在一个单独的文件中:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FahrenheitPanel extends JPanel
{
private JLabel inputLabel, outputLabel, resultLabel;
private JButton push;
private JTextField fahrenheit;
//-----------------------------------------------------------------
// Constructor: Sets up the main GUI components.
//-----------------------------------------------------------------
public FahrenheitPanel()
{
inputLabel = new JLabel ("Enter Fahrenheit temperature:");
outputLabel = new JLabel ("Temperature in Celsius: ");
resultLabel = new JLabel ("---");
fahrenheit = new JTextField (5);
fahrenheit.addActionListener (new TempListener());
add (inputLabel);
add (fahrenheit);
add (outputLabel);
add (resultLabel);
//Here's some button code
push = new JButton ("Push!!!");
push.addActionListener (new ButtonListener());
add (push);
setPreferredSize (new Dimension(300, 75));
setBackground (Color.red);
}
private class ButtonListener implements ActionListener
{
private class TempListener implements ActionListener
{
//--------------------------------------------------------------
// Performs the conversion when the enter key is pressed in
// the text field.
//--------------------------------------------------------------
public void actionPerformed (ActionEvent event)
{
int fahrenheitTemp, celsiusTemp;
String text = fahrenheit.getText();
fahrenheitTemp = Integer.parseInt (text);
celsiusTemp = (fahrenheitTemp-32) * 5/9;
resultLabel.setText (Integer.toString (celsiusTemp));
}
}
}
}