我正在尝试创建一个GUI,用于在用户输入半径时计算圆的体积。到目前为止我所拥有的是:
import javax.swing.JFrame;
public class Volume
{
//Creates a JFrame that calculates the Volume of a circle given the radius
public static void main(String args[])
{
JFrame frame = new JFrame("Volume Calc");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
VolumePanel panel = new VolumePanel();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
我的Jframe和:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class VolumePanel extends JPanel
{
private JLabel radiusLabel, volumeLabel, resultLabel;
private JTextField inputField;
//Sets up the Panel
public VolumePanel()
{
JLabel radiusLabel = new JLabel("Please enter the radius: ");
JLabel volumeLabel = new JLabel("The volume of the circle is: ");
JLabel resultLabel = new JLabel("");
JTextField inputField = new JTextField(5);
inputField.addActionListener (new VolumeCalc());
add (radiusLabel);
add (inputField);
add (volumeLabel);
add (resultLabel);
setPreferredSize(new Dimension(250,75));
setBackground(Color.WHITE);
}
//Calculates the volume based on the input
private class VolumeCalc implements ActionListener
{
public void actionPerformed(ActionEvent stuff)
{
double radius, volume;
String input = inputField.getText();
radius = Double.parseDouble(input);
volume = (Math.pow(radius, 2) * Math.PI);
resultLabel.setText (Double.toString(volume));
}
}
}
我的小组。它编译得很好并且运行得非常好,但是当我按下回车键时它会混乱。
答案 0 :(得分:2)
您有两个inputField
声明,并声明了单独的变量。这一个:
private JTextField inputField;
是实例的成员字段,但它从未初始化,因此始终为null
。这一个:
JTextField inputField = new JTextField(5);
是构造函数中的局部变量。它在构造函数中只显示 。它在构造函数完成后就消失了。
如果您希望构造函数修改字段,请将第二行更改为
inputField = new JTextField(5);
使其成为赋值语句,而不是新变量的声明。
答案 1 :(得分:-1)
在你的actionPerformed中尝试:
String input = inputField.getText(); // guessing your input is the size of the circle
int result = Math.PI * Integer.valueOf(input);
resultLabel.setText(result);
圆圈中没有音量
编辑:使用您的代码布局时,在尝试使用inputField&时会出错。 volumePanel中的resultLabel