2013-01-17 35 views
1

當按下「1-10」按鈕時,我想從我的while循環中獲取整個輸出,而不必單擊每個數字顯示的「確定」按鈕。在JFrame中輸出整個循環

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 

public class Testgui1 extends JFrame implements ActionListener 
{ 
    int i = 1; 
    JLabel myLabel = new JLabel(); 
    JPanel mypanel = new JPanel(); 
    JButton mybutton = new JButton("1-10"); 
    Testgui1() 
    { 
     super("Meny"); 
     setSize(200,200);//Storlek på frame 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     Container con = this.getContentPane(); 
     con.add(mypanel); 
     mybutton.addActionListener(this); 
     mypanel.add(myLabel); mypanel.add(mybutton); 
     setVisible(true); 
    } 
    public void actionPerformed(ActionEvent event) 
    { 
    // Object source = event.getSource(); 
    //if (source == mybutton) 
    { 
      while (i < 11){ 
         System.out.print(+i); 
     { 
      JOptionPane.showMessageDialog(null,i,"1-10", 
        JOptionPane.PLAIN_MESSAGE); 
        setVisible(true); 
        ++i; 
     } 
    } 
     } 
      } 
    public static void main(String[] args) {new Testgui1();} 
} 

回答

2

我想你想要做的是在你的while循環中建立一個String(或StringBuilder),然後在循環完成後輸出它。所以像這樣:

StringBuilder s = new StringBuilder(); 
while(i < 11) { 
    s.append(" ").append(i); 
    i++; 
} 
System.out.println(s); 
JOptionPane.showMessageDialog(null, s, "1-10", 
      JOptionPane.PLAIN_MESSAGE); 

這應該讓你至少更近。

請注意,如果您希望消息對話框爲模態,請將「this」作爲第一個參數(而不是null)傳遞給showMessageDialog。

+1

謝謝你我的好先生! – Krappington