2013-01-17 30 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