Reputation: 27
I'm trying to create a GUI that calculates the volume of a circle when the user inputs a radius. So far what I have is:
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);
}
}
for my Jframe and:
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));
}
}
}
for my Panel. It compiles fine and runs perfectly fine, but when I press the enter key it messes up.
Upvotes: 0
Views: 60
Reputation: 71
in you actionPerformed try:
String input = inputField.getText(); // guessing your input is the size of the circle
int result = Math.PI * Integer.valueOf(input);
resultLabel.setText(result);
there is no volume in a circle since its flat
EDIT: with your code layout you should have an error when trying to use inputField & resultLabel in volumePanel
Upvotes: -1
Reputation: 31689
You have two inputField
declarations, and they declare separate variables. This one:
private JTextField inputField;
is a member field of the instance, but it is never initialized, so it is always null
. This one:
JTextField inputField = new JTextField(5);
is a local variable inside the constructor. It is visible only inside the constructor. It goes away after the constructor is done.
If you want the constructor to modify the field, change the second line to
inputField = new JTextField(5);
which makes it an assignment statement, not a declaration of a new variable.
Upvotes: 2