2013-09-22 283 views
0

這是我的代碼,問題是當它運行時,JOptionPane出現問題。繼續循環,沒有循環

import java.awt.Color; 
import java.awt.Graphics; 

import javax.swing.JFrame; 
import javax.swing.JOptionPane; 


public class MoveTyper extends JFrame 
{ 
int Location[] = {40, 40}; 
public static void main (String args[]) 
{ 
    new MoveTyper(); 
} 

public MoveTyper() 
{ 
    super("typetomove"); 
    setSize(800, 450); 
    setVisible(true); 
    setDefaultCloseOperation(EXIT_ON_CLOSE); 

} 

public void paint(Graphics g) 
{ 
    System.out.println("poop"); 
    g.setColor(Color.BLUE); 


     g.fillRect(Location[0], Location[1], 20, 20); 

     String Axis = JOptionPane.showInputDialog("Move by X or by Y? If you would like to quit, type cancel"); 

      int Movement = Integer.parseInt(JOptionPane.showInputDialog("How Many would you like to move up from")); 
      if(Axis.equalsIgnoreCase("X")) 
      { 
       Location[0] = Location[0] + Movement; 
      } 
      else if(Axis.equalsIgnoreCase("cancel")) 
      { 

      } 
      else 
      { 
       Location[1] = Location[1] + Movement; 


    } 

    JOptionPane.showMessageDialog(null, "You have quit. GOOD JOB. YOU SMELL"); 


} 

} 當運行時,JOptionPane的繼續彈出(一個在另一個之上),就好像在一個循環中,你們可以幫我找出這個問題?我似乎無法找到問題。

+6

的'漆( )方法在組件需要重新繪製時運行,例如當它被移動或重新調整大小時。當你第一次彈出一個JOptionPane時,它會彈出在你的組件上,這意味着當你選擇它時,組件需要重新繪製。所以'paint()'方法再次運行,顯示另一個JOptionPane,並且一直持續下去。 – Kon

+2

@Kon你應該發佈它作爲答案。 – Pshemo

+0

嗯......好吧,我不完全明白,但是我需要做些什麼來解決這個問題? – user2789610

回答

0

showInputDialog()showMessageDialog()的代碼不應該在paint()方法中。將其移出到一個新的方法:

public void showDialog() { 
    String Axis = JOptionPane.showInputDialog("Move by X or by Y? If you would like to quit, type cancel"); 

    int Movement = Integer.parseInt(JOptionPane.showInputDialog("How Many would you like to move up from")); 
    if(Axis.equalsIgnoreCase("X")) 
    { 
     Location[0] = Location[0] + Movement; 
    } 
    else if(Axis.equalsIgnoreCase("cancel")) 
    { 

    } 
    else 
    { 
     Location[1] = Location[1] + Movement; 


    } 
    JOptionPane.showMessageDialog(null, "You have quit. GOOD JOB. YOU SMELL"); 
} 

,並在你的情況下,調用此方法從構造

public MoveTyper() 
{ 
    super("typetomove"); 
    setSize(800, 450); 
    setVisible(true); 
    setDefaultCloseOperation(EXIT_ON_CLOSE); 
    showDialog(); 
} 

所以paint()方法看起來像這樣

public void paint(Graphics g) 
{ 
    System.out.println("poop"); 
    g.setColor(Color.BLUE); 
    g.fillRect(Location[0], Location[1], 20, 20); 
}