2009-12-14 2 views
0

문제점 : 업데이트 할 JTextFields 또는 rollResultTotal 값을 가져올 수 없습니다. JTextFields의 데이터가 유효하더라도 NumberFormatException이 여전히 발생합니다.Java : 롤러 프로그램 - 디버그 변수가 유효한 정보와 상관없이 JTextField 및 NumberFormatException에서 업데이트되지 않음

질문 : 변수가 유지되지 않는 이유는 무엇입니까? 이것은 클래스 자체의 선언 때문입니까? JLabel 패널을 업데이트하여 업데이트 된 결과를 표시 할 수 있습니까? (시도, 서사시 실패)

어떤 입력과 예제도 미리 감사드립니다.

/* 
    ITP-120:  Final Project 
    Programmer: S. Schnoor 
    Date:  November 7th, 2009 
    Filename: SchnoorProject.java 
    Purpose:  To generate "dice rolls" - a tally of random values as defined by the user, 
       including a final calculation modifier. 
*/ 

import java.awt.*; 
import java.awt.event.*; 
import java.util.*; 
import javax.swing.*; 
import java.lang.*; 
import java.math.*; 

public class SchnoorProject extends JFrame implements ActionListener, EventListener 
{ 
    // Declare Class Variables 
    int sidesToRoll, diceToRoll, diceLeft, modifier, rollResult, rollResultTotal; 
    String getSides, getDice, getModifier; 
    JTextField inputSides  = new JTextField(); 
    JTextField inputDice  = new JTextField(); 
    JTextField inputModifier = new JTextField(); 
    Random roll; 

    // Panels and Buttons 
    JPanel rollPanel; 
    JButton newRollButton, helpButton, exitButton; 

    // Create Colors 
    Color darkPurple  = new Color (80, 0, 80); 
    Color darkGold   = new Color (255, 215, 0); 
    Color darkCoal   = new Color (24, 24, 24); 
    Color crimson   = new Color (127, 12, 12); 
    Color ltSilver   = new Color (140, 140, 180); 

    public static void main(String args[]) 
    { 
     JFrame frame = new SchnoorProject(); 

     WindowListener l = new WindowAdapter() 
      { 
       public void windowClosing(WindowEvent e) 
       { 
        System.exit(0); 
       } 
      }; 

    frame.addWindowListener(l); 
    frame.pack(); 
    frame.setVisible(true); 

    } 

    public SchnoorProject() 
    { 
     // Construction of Components 
     rollPanel       = new JPanel(); 
     getContentPane().add(rollPanel); 


     JLabel  sidesLabel    = new JLabel ("Enter the number of sides on each die below. (1 to 99)"); 
        sidesLabel.setForeground(darkGold); 
        sidesLabel.setHorizontalAlignment(sidesLabel.CENTER); 

     JTextField inputSides    = new JTextField("6"); 
        inputSides.setBackground(darkCoal); 
        inputSides.setForeground(darkGold); 
        inputSides.setHorizontalAlignment(inputSides.CENTER); 

     JLabel  diceLabel    = new JLabel ("Enter the number of dice to roll below. (1 to 99)"); 
        diceLabel.setForeground(darkGold); 
        diceLabel.setHorizontalAlignment(diceLabel.CENTER); 

     JTextField inputDice    = new JTextField("3"); 
        inputDice.setBackground(darkCoal); 
        inputDice.setForeground(darkGold); 
        inputDice.setHorizontalAlignment(inputDice.CENTER); 

     JLabel  modifierLabel   = new JLabel ("Enter the final modifier below. (-99 to 99)"); 
        modifierLabel.setForeground(darkGold); 
        modifierLabel.setHorizontalAlignment(modifierLabel.CENTER); 

     JTextField inputModifier   = new JTextField("2"); 
        inputModifier.setBackground(darkCoal); 
        inputModifier.setForeground(darkGold); 
        inputModifier.setHorizontalAlignment(inputModifier.CENTER); 

     JButton  newRollButton   = new JButton("ROLL"); 
        newRollButton.setBackground(darkCoal); 
        newRollButton.setForeground(darkGold); 
        newRollButton.addActionListener(this); 

     JButton  helpButton    = new JButton("Help/About"); 
        helpButton.setBackground(darkCoal); 
        helpButton.setForeground(ltSilver); 
        helpButton.addActionListener(this); 

     JButton  exitButton    = new JButton("Exit"); 
        exitButton.setBackground(darkCoal); 
        exitButton.setForeground(crimson); 
        exitButton.addActionListener(this); 

     //Conversions 
        getSides    = inputSides.getText(); 
        getDice     = inputDice.getText(); 
        getModifier    = inputModifier.getText(); 
        sidesToRoll    = Integer.parseInt(getSides); 
        diceToRoll    = Integer.parseInt(getDice); 
        modifier    = Integer.parseInt(getModifier); 
        diceLeft    = diceToRoll; 
        //rollResultTotal  = rollResultTotal; 

     // Paneling 
     rollPanel.setLayout(new GridLayout (3,3)); 
     rollPanel.setBackground(darkPurple); 
     rollPanel.setForeground(darkGold); 
     rollPanel.add(sidesLabel); 
     rollPanel.add(diceLabel); 
     rollPanel.add(modifierLabel); 
     rollPanel.add(inputSides); 
     rollPanel.add(inputDice); 
     rollPanel.add(inputModifier); 
     rollPanel.add(newRollButton); 
     rollPanel.add(helpButton); 
     rollPanel.add(exitButton); 
    } 

    // Implement ActionListener for multiple JButtons 
    public void actionPerformed(ActionEvent e) 
    { 
     String arg = e.getActionCommand(); 
     if ("Help/About".equals(arg)) 
      { 
       JOptionPane.showMessageDialog(null,"This application generates random values, based on the parameters input by the user.\nPlease choose number of dice, sides on each die, and a +/- roll modifier.\nIf no roll modifier is needed, enter 0 (numeric zero) in the modifier field.\n(The starting numbers tell the program to roll 3 six-sided dice and add 2 or '3d6+2'.)","Help/About",JOptionPane.INFORMATION_MESSAGE); 
      } 

     if ("Exit".equals(arg)) 
      { 
       System.exit(0); 
      } 

     if ("ROLL".equals(arg)) 

       { 
        try 
        { 
         while (diceLeft>0) 
         { 
          getSides     = inputSides.getText(); 
          sidesToRoll     = Integer.parseInt(getSides); 
          if(sidesToRoll<1 || sidesToRoll>99)  throw new NumberFormatException(); 
          else 

          getDice      = inputDice.getText(); 
          diceToRoll     = Integer.parseInt(getDice); 
          if(diceToRoll<1 || diceToRoll>99)  throw new NumberFormatException(); 
          else 

          getModifier     = inputModifier.getText(); 
          modifier     = Integer.parseInt(getModifier); 
          if(modifier<-99 || modifier>99)   throw new NumberFormatException(); 
          else 

         rollResult     = roll.nextInt(sidesToRoll)+1; 
         rollResultTotal    = rollResultTotal + rollResult; 
         diceLeft--; 
         } 

        } 


        catch(NumberFormatException ex) 
        { 
         JOptionPane.showMessageDialog(null,"You must enter an integer within the given range of each field.","ROLL",JOptionPane.INFORMATION_MESSAGE); 
         diceLeft = 0; 
        } 


        { //Display the Roll Formula and Result 
        JOptionPane.showMessageDialog(null,"You entered a roll of " + (diceToRoll) + "d" + (sidesToRoll) + "+(" + (modifier) + ").\nYou rolled " + (rollResultTotal) + "!"); 
        } 
     ;} 
    ;} 
} 
+0

나는 시청자들에게 좋은보고 위의 코드를 포맷하는 방법을 모르겠어요. 사과드립니다. –

+0

코드를 선택하고 ctrl + k를 누르십시오 (이미 해당 작업을 수행했습니다) – Bozho

+0

학술 윤리에 우려하는 사람들을 위해, 나는 이미 주말에이 수업을 마쳤습니다. 이제는 개인적인 지식에 관한 것입니다. –

답변

1

이 멤버 변수를 초기화,하지만 당신은 UI에이 필드를 추가하지 :

여기
JTextField inputSides = new JTextField(" "); 

여전히 정수가 아닌 문자열 " "을 포함하고이 텍스트 필드에서 읽습니다.

getSides = inputSides.getText(); 
sidesToRoll = Integer.parseInt(getSides); 

생성자에서 UI를 구축

, 당신은 새로운 객체를 가리키는 이름이 같은 다른 지역 변수를 선언 :

JTextField inputSides = new JTextField("6"); 

이이 UI에 표시되는 개체입니다. 지역 변수 inputSides은 동일한 이름의 멤버 변수를 숨 깁니다.

arg == "ROLL" 

이 유일한 작품 같은, 인턴 개체 인스턴스를 가리키는 arg 때문에 : 여담으로


,이 문자열을 비교하는 올바른 방법이 아니다. 이 값을 비교하는 올바른 방법은 다음과 같습니다

"ROLL".equals(arg) 

편집 :

당신이 누락 트릭은 당신이 사람 참조 변수가 가리키는된다 만들고있는 개체에 대한 생각입니다.

는 코드의 단순화 된 버전 고려해

public class ObjectReferences { 
    private final JLabel label = new JLabel("I am FOO"); // label 1 

    public ObjectReferences() { 
    JLabel label = new JLabel("I am BAR"); // label 2 

    JButton button = new JButton("Click me"); 
    button.addActionListener(new ActionListener() { 
     @Override public void actionPerformed(ActionEvent e) { 
     onclick(); 
     } 
    }); 

    // will display "I am BAR" 
    JFrame frame = new JFrame(); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setSize(600, 400); 
    frame.setLayout(new FlowLayout()); 
    frame.add(label); // label 2 
    frame.add(button); 
    frame.setVisible(true); 
    } 

    public void onclick() { 
    // will display "I am FOO" 
    JOptionPane.showMessageDialog(null, label.getText()); // label 1 
    } 

    public static void main(String[] args) { 
    new ObjectReferences(); 
    } 
} 

두 레이블 오브젝트가 작성됩니다 만, 하나의 프레임에 추가됩니다. 레이블 1은 member 변수에 의해 참조되며 onclick() 메소드에 표시됩니다. 생성자 내에서 레이블 2label이라는 멤버 변수를 숨기는 label이라는 로컬 변수에 의해 참조됩니다.

귀하의 의도는이 대신 같은 것을 작성하는 것입니다 :

public class ObjectReferences { 
    private final JLabel label = new JLabel("I am FOO"); 

    public ObjectReferences() { 
    JButton button = new JButton("Click me"); 
    button.addActionListener(new ActionListener() { 
     @Override public void actionPerformed(ActionEvent e) { 
     onclick(); 
     } 
    }); 

    JFrame frame = new JFrame(); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setSize(600, 400); 
    frame.setLayout(new FlowLayout()); 
    frame.add(label); 
    frame.add(button); 
    frame.setVisible(true); 
    } 

    public void onclick() { 
    JOptionPane.showMessageDialog(null, label.getText()); 
    } 

    public static void main(String[] args) { 
    new ObjectReferences(); 
    } 
} 
+0

신속한 응답에 감사드립니다. 나는 arg == "ROLL"을 "ROLL".equals (arg)로 전환 할 수 있었고 Exit와 Help/About 버튼도 바꿀 수있었습니다. 불필요한 코드를 제거함과 동시에 변경 사항을 반영하기 위해 위의 코드를 정리했습니다. 그래도 그것을 알아 내지 못했습니다. –

+0

나는 내 대답을 편집 했으므로 그 문제가 더 명확하게 밝혀졌다. 또한 'roll' 멤버를 초기화하지 않았으므로 사용하려고하면 NullPointerException이 발생합니다 ._ – McDowell

+0

이것이 의미가 있습니다. 나는 계속 지킬거야. :) –

관련 문제