简体   繁体   中英

Can someone identify what's wrong with my code?

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.

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.

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

Source

EDIT: with your code layout you should have an error when trying to use inputField & resultLabel in volumePanel

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM