Hello forum vaironl here, I'm having a little bit of trouble with a school assignment which is storing up to 10 names and printing them out in the command box or just printing out the names if the user presses -1.
For some reason my loop doesn't wait for the user to type in all of the names and it just advances directly to the for loop.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Assign2 extends JPanel
{
static JLabel helloMsg;
static String empty;
static String[] name = new String[10];
static String temp, done;
static int i;
static JTextField box;
static JButton Enter;
public Assign2(){
setLayout(new FlowLayout());
helloMsg = new JLabel("Typer your name , then press Enter. Enter -1 if done");
helloMsg.setHorizontalAlignment(SwingConstants.CENTER);
add(helloMsg);
box = new JTextField(25);
box.setText("Name here");
box.setHorizontalAlignment(SwingConstants.CENTER);
add(box);
Enter = new JButton("Enter");
Enter.addActionListener(new Listener());
Enter.setLocation(10,50);
Enter.setHorizontalAlignment(SwingConstants.CENTER);
add(Enter);
}
private class Listener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
empty =new String("");
i = 0;
temp = new String();
done = new String("-1");
while(i<10)
{
temp = box.getText();
if(temp.equals(empty)==false){
name[i]= temp;
helloMsg.setText("Hello "+ name[i]);
i++;
System.out.print(i+",");// Will print how many names have been entered.
}
break;
}
for (int o =0;o<10;o++){
System.out.println(name[o]);
}
}
}
public static void main(String[] args)
{
JFrame frame = new JFrame("Assignment1");
frame.setSize(350, 150);
frame.setLocation(200, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new Assign2());
frame.setVisible(true);
}
}