Search code examples
javawhile-loopjframejoptionpane

Output entire loop in JFrame


I want to get the whole output from my while-loop, when the "1-10" button is pressed, and not have to click on the "OK" button for every number to show.

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();}
}

Solution

  • I think what you want to do is to build up a String (or StringBuilder preferrably) inside your while loop, and then output it once after the loop completes. So something like:

    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);
    

    That should get you closer at least.

    Note that if you want the message dialog to be modal, pass "this" as the first argument (instead of null) to showMessageDialog.