Вопрос инициализации Java - PullRequest
       26

Вопрос инициализации Java

0 голосов
/ 20 августа 2011
JPanel p2 = new JPanel(new GridLayout(6,1));
ButtonGroup tubtype = new ButtonGroup();
JRadioButton roundrButton = new JRadioButton("Round", true);
tubtype.add(roundrButton);
JRadioButton ovalrButton = new JRadioButton("Oval", false);
tubtype.add(ovalrButton);
calcButton = new JButton("Calculate Volume");
exitButton = new JButton("Exit");
hlength = new JTextField(5);
hwidth = new JTextField(5);
hdepth = new JTextField(5);
hvolume = new JTextField(5);
lengthLabel = new JLabel("Enter the tub's length (ft):");
widthLabel = new JLabel("Enter the tub's width (ft):");
depthLabel = new JLabel("Enter the tub's depth (ft):");
volumeLabel = new JLabel("The tub's volume (ft^3):");
p2.add(roundrButton);
p2.add(ovalrButton);
p2.add(lengthLabel);
p2.add(hlength);
p2.add(widthLabel);
p2.add(hwidth);
p2.add(depthLabel);
p2.add(hdepth);
p2.add(volumeLabel);
p2.add(hvolume);
p2.add(calcButton);
p2.add(exitButton);
tab.addTab( "Hot Tubs", null, p2, " Panel #1" );

calcButtonHandler2 ihandler =new calcButtonHandler2();
calcButton.addActionListener(ihandler);
exitButtonHandler ghandler =new exitButtonHandler();
exitButton.addActionListener(ghandler);
FocusHandler hhandler =new FocusHandler();
hlength.addFocusListener(hhandler);
hwidth.addFocusListener(hhandler);
hdepth.addFocusListener(hhandler);
hvolume.addFocusListener(hhandler);

// add JTabbedPane to container
getContentPane().add( tab );
setSize( 550, 500 );
setVisible( true );
} 
public class calcButtonHandler implements ActionListener {

public void actionPerformed(ActionEvent e) {
DecimalFormat num =new DecimalFormat(",###.##");
double sLength, sWidth, sdepth, Total;

sLength = Double.valueOf(plength.getText());

sWidth =Double.valueOf(pwidth.getText());

sdepth =Double.valueOf(pdepth.getText());

if(e.getSource() == pcalcButton) {
Total = sLength * sWidth * sdepth;
pvolume.setText(num.format(Total));
try{
String value=pvolume.getText();
File file = new File("output.txt");
FileWriter fstream = new FileWriter(file,true);
BufferedWriter out = new BufferedWriter(fstream);
out.write("Length= "+sLength+", Width= "+sWidth+", Depth= "+sdepth+" so the volume of Swimming  Pool is "+value);
out.newLine();
out.close();
}
catch(Exception ex){}
}
}
}

public class calcButtonHandler2 implements ActionListener {

public void actionPerformed(ActionEvent g) {
DecimalFormat num =new DecimalFormat(",###.##");
double cLength, cWidth, cdepth, Total;

cLength = Double.valueOf(hlength.getText());

cWidth = Double.valueOf(hwidth.getText());

cdepth = Double.valueOf(hdepth.getText());

try
{
AbstractButton roundrButton;
if(roundrButton.isSelected())
{

Total = Math.PI * Math.pow(cLength / 2.0, 2) * cdepth;
}
else 
{
Total = Math.PI * Math.pow(cLength * cWidth, 2) * cdepth;
}
hvolume.setText(""+num.format(Total));
}

catch(Exception ex){}
}
}
}



class exitButtonHandler implements ActionListener {
    public void actionPerformed(ActionEvent g){
        System.exit(0);
    }
}
class FocusHandler implements FocusListener {
    public void focusGained(FocusEvent e) {
    }
    public void focusLost(FocusEvent e) {
    }


public static void main( String args[] )
{
    Final tabs = new Final();
    tabs.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}

Я получаю сообщение об ошибке, в котором говорится, что мой roundrButton, возможно, не был инициализирован. Пожалуйста, помогите.

Ответы [ 3 ]

0 голосов
/ 20 августа 2011

Проблема в следующих строках:

try
{
    AbstractButton roundrButton;
    if(roundrButton.isSelected())
    {

Вы объявляете переменную с именем roundrButton, а затем пытаетесь вызвать .isSelected() для нее.Однако вы никогда ничего не назначаете на roundButton, так что это будет null.

Возможно, вы захотите сослаться на roundrButton, который вы объявили ранее.Рассматривали ли вы сделать это поле вашего класса?

0 голосов
/ 20 августа 2011

Я полагаю, ваша проблема в методе actionPerformed класса calcButtonHandler2:

    try { 
AbstractButton roundrButton;
if(roundrButton.isSelected())

roundrButton действительно не инициализирован, и это приведет к исключению NullPointerException во время выполнения.

0 голосов
/ 20 августа 2011

Ошибка происходит здесь:

try {
    AbstractButton roundrButton;
    if (roundrButton.isSelected()) {

Вы объявили переменную с именем roundrButton, но не присвоили ей какой-либо объект.

Затем вы вызвали метод, ну ктознает?Нет объекта для вызова метода, потому что переменная roundrButton никогда не получала значение.

...