2014-12-12 2 views
-1

오늘 자바를 배우기 시작했고 여기에 붙어 있습니다. 버튼을 사용하여 패널을 새로 고치는 방법을 모르겠습니다. 여기 내 코드는 다음과 같습니다.다른 값으로 JPanel을 새로 고침

import java.awt.GridLayout; 
import java.util.Random; 
import javax.swing.*; 

public class App { 

public static int STR = 0, aPower = 0, sPower = 0, INT = 0, STA = 0, DEF = 0; 

private static void GenerateStatus(){ 
    Random randomGenerator = new Random(); 
    STR = randomGenerator.nextInt(50); 
    aPower = randomGenerator.nextInt(50); 
    sPower = randomGenerator.nextInt(50); 
    INT = randomGenerator.nextInt(50); 
    STA = randomGenerator.nextInt(50); 
    DEF = randomGenerator.nextInt(50); 
} 

private static void FirstTimeInGame() { 
    String[] items = {"Warrior", "Mage", "Druid", "Scout"}; 
    JComboBox combo = new JComboBox(items); 
    JTextField Name = new JTextField(); 
    JPanel panel = new JPanel(new GridLayout(0, 1)); 

    GenerateStatus(); 

    panel.add(new JLabel("Name", SwingConstants.CENTER)); 
    panel.add(Name); 
    panel.add(new JLabel("Class", SwingConstants.CENTER)); 
    panel.add(combo); 
    panel.add(new JLabel("Stats", SwingConstants.CENTER)); 
    panel.add(new JLabel("Strength   " + STR)); 
    panel.add(new JLabel("Attack Power " + aPower)); 
    panel.add(new JLabel("Spell Power  " + sPower)); 
    panel.add(new JLabel("Intellect   " + INT)); 
    panel.add(new JLabel("Stamina   " + STA)); 
    panel.add(new JLabel("Armor    " + DEF)); 

    String[] buttons = {"Create!", "Randomize!", "Cancel"}; 

    int result = JOptionPane.showOptionDialog(null, 
      panel, 
      "Welcome", 
      JOptionPane.YES_NO_CANCEL_OPTION, 
      JOptionPane.PLAIN_MESSAGE, 
      null, 
      buttons, 
      buttons[2] 
      ); 

    if (result == JOptionPane.OK_OPTION) { 
     System.out.println(combo.getSelectedItem() 
       + " " + Name.getText()); 
    } 
    else if (result == JOptionPane.NO_OPTION){ 
     GenerateStatus(); 
     panel.validate(); 
     panel.repaint(); 

    } 
    else{ 
     System.out.println("CANCEL"); 
    } 

} 

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

함수 GenerateStatus()는 난수를 생성합니다. '무작위 화'버튼을 누르면 창이 닫힙니다.
enter image description here

누구나 나를 도와 줄 수 있습니까? 부디?

+0

표시된 코드가 문제와 관련이없는 것으로 보입니다 ... – John3136

+0

'임의로 지정'버튼을 눌러야 만합니다. '통계'값을 새로 고칩니다. 어떻게해야합니까? – Cosmin

+0

우리는 어떻게 알 수 있습니까? "통계"에 대해 할 일이있는 코드는 표시하지 않았습니다. – John3136

답변

1

JLabel을 패널에 추가하는 대신 클래스 수준 멤버에 저장해야합니다. 버튼을 클릭하면 기존 레이블의 텍스트를 변경해야합니다. 이 근처

:

public static int STR = 0, aPower = 0, sPower = 0, INT = 0, STA = 0, DEF = 0; 

private JLabel strLabel; 

추가는 다음 panel.add(new JLabel("Strength " + STR));

strLabel = new JLabel("Strength   " + STR); 
panel.add(strLabel); 

지금은 다른 곳에서 strLabel의 텍스트를 변경할 수 있습니다됩니다.

+0

코드의 일부를 쓸 수 있습니까? 나는이 일을하는 법을 모르지만 자바에서 처음으로 :) – Cosmin

+0

하지만, "Randomize"를 누르면! 창문이 닫히고, 어떻게 계속 머물게 만드나요? – Cosmin

+0

내가 말할 수있는 충분한 코드가 없다고 생각합니다 ... 지문이 당신에게 뭐라고 말합니까? 코드의 어떤 부분이 실행됩니까? – John3136