GUI in Java.. generating a run time component - java

I have an User Interface where the user inputs a number (10 for example) in a textfeild
then if the user presses enter I want 10 text feilds to be generated in the same User Interface.
how can I do that?

Something like that:
// Assuming myOrigTextField is your original JTextField
int howMany = Integer.parseInt(myOrigTextField.getText());
JTextField[] jtfs = new JTextField[howMany];
for (int i = 0; i < jtfs.length; ++i) {
jtfs[i] = new JTextField();
myPanelToAddThem.add(jtfs[i]);
}

Create the text field objects,
add them to your container.
Use a loop to do this with an arbitrary number.
Post some code and your specific problems for more help.

Roughly assuming some thing about layout manager you're using I'd say this:
public List<JTextField> addComponents( int number ) {
List<JTextField> fields = new ArrayList<JTextField>( number );
for( int i = 0; i < number; i++ ) {
fields.add( new JTextField() );
panelToAddComponentsTo.add( fields.get( i ) );
}
return fields;
}

if the user presses enter I want ? text feilds to be generated in the same User Interface
You add an ActionListener to the text field. The ActionListener will be invoked when the Enter key is pressed.
In the ActionListener code you need to parse the number entered and then loop to create and add the text fields to your panel:
for (...)
{
panel.add( new JTextField(...) );
}
panel.revalidate(); // needed when dynamically adding/removing components
panel.repaint(); // sometimes needed

Related

How to create multiple field in swing and use the value in a for loop

I want to make a user interface where the user can select the caracteristic of each pizza he wants.
And I would like to be abl to use the value enter by said user.
So here's my code:
JPanel panelComm2 = new JPanel();
String[] crust = Crust.names();
String[] size = Size.names();
String[] drink = Drink.names();
Box verticalBox = Box.createVerticalBox();
for(int i=0;i<nbPizza;i++){
Box horizontalBox = Box.createHorizontalBox();
JLabel crustJLabel = new JLabel("Crust Pizza "+ (i+1)+": ");
horizontalBox.add(crustJLabel);
JComboBox comboCrust = new JComboBox(crust);
horizontalBox.add(comboCrust);
JLabel sizeJLabel = new JLabel("Size Pizza "+ (i+1)+": ");
horizontalBox.add(sizeJLabel);
JComboBox comboSize = new JComboBox(size);
horizontalBox.add(comboSize);
verticalBox.add(horizontalBox);
}
for (int j=0;j<nbDrink;j++){
Box horizontalBox = Box.createHorizontalBox();
JLabel drinkJLabel = new JLabel("Drink "+ (j+1) +": ");
horizontalBox.add(drinkJLabel);
JComboBox comboChooseDrink = new JComboBox(drink);
horizontalBox.add(comboChooseDrink);
verticalBox.add(horizontalBox);
}
panelComm2.add(verticalBox);
int p = JOptionPane.showOptionDialog(null, panelComm2, "Select option",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null, options2, options2[0]);
if (p == JOptionPane.YES_OPTION) {
// Here I want to store the value enter by the user in the comboBox
// Without a for, I would do this
//
// String crust1 = comboCrust().getSelectedItem().toString();
//
//But comboCrust don't exist anymore cause it exist only in the for
System.out.println("To do");
}
You can see I generate my interface within some for loop, the size of those loop, is depending of some variable (define before by the user)
A JComboBox is created for chosing either the 'Crust','Size' or 'Drink'. (All three are enumerations)
And the inteface is organized with the help of "Box" horizontal and vertical. Which I put in my main panel "panelComm2" also use to make a JoptionPane at the end.
Here's what it looks like:
Yet with the way I've built my interface, I can't get the information selected by the user.
I'm looking for a way to add variables for each field of the interface, so that I could use them when the user clicks on 'Ok'.
I give up on the idea of making variables for each field, and use array of JcomboBox define prior the 'for' loop.
JComboBox[] arrayComboCrust = new JComboBox[nbPizza];
JComboBox[] arrayComboSize = new JComboBox[nbPizza];
JComboBox[] arrayComboDrink = new JComboBox[nbDrink];
And then within the loop I define the value of the array:
arrayComboCrust[i]=comboCrust;
And I set up a new 'for' loop to in my JOptionPane to read the value I wanted
Thanks to MadProgrammer

How to give each JButton in a 10 x 10 grid button layout a unique ID/name

I am trying to give each JButton from a 10 x 10 button layout (so 100 buttons) each unique name or ID or number so I can call them later. I made an ArrayList because that's what some other person did.
public ArrayList<JButton> myList;
//Some other code
for(int row = 0; row < 10; row++)
{
for(int col = 0; col < 10; col++)
{
button = new JButton();
button.addActionListener( al );
myList.add(button);
for(JButton button : myList)
button.setText("");
panel_1.add(button);
}
}
The program compiles but it doesn't run. It's showing error at
myList.add(button);
It's a null pointer exception apparently.
but I don't know why. Is it not adding the buttons to the ArrayList? Also how do I give each button a unique name or string?
The program compiles but it doesn't run. It's showing error at
The ArrayList is null because you didn't create an ArrayList object.
The code should be:
private ArrayList<JButton> myList = new ArrayList<JButton>();
Also how do I give each button a unique name or string?
There is no need to give the button a unique name. Its unique name is the "index" used to access the JButton in the ArrayList.
You probably don't even need the ArrayList.
Normally you add an ActionListener to the button. Then you can just use the getSource() method of the ActionEvent to get the reference to the button.

How do I get input from buttons I created using a loop?

I'm trying to make a simple calculator in Java using Swing, and I've created my buttons the following way:
//Our number keypad
public static JPanel numbers(){
//our panel to return
JPanel panel = new JPanel();
//Create and add 3x4 grid layout to panel
GridLayout gl = new GridLayout(3, 4);
panel.setLayout(gl);
//For creating and adding buttons to panel
for(int i = 0; i < 10; i++){
//Create a new button where the name is the value of i
String name = "" + i + "";
JButton button = new JButton(name);
//add action listener
button.addActionListener(handler);
//Add button to panel
panel.add(button);
}
return panel;
}
My question is how do I reference each specific button in my event handler? I can't think of a way to do this without having to manually create each button rather than using a loop.
Thanks.
In your listener, call event.getSource(), and that will return the button which has been pressed. Get the text of the button, and you have its number.
Or create a different instance of your handler for every button, and pass the value of the button (i) to the constructor of the handler. This last solution is cleaner, IMO, because it doesn't depend on the text of the button. If you replaced the text by an image, for example, the first technique wouldn't work anymore.
You can distinguish created buttons by adding the following inside handler:
String buttonText = ((JButton) e.getSource()).getText();
if (<text1>.equals(buttonText)){
//do the stuff
} else if (<text2>.equals(buttonText)){
//do the stuff
} else {
//do the stuff
}
Method #1: go through the child components of the parent JPanel (quite tedious, has to be rebuilt every time you modify the contents of that JPanel). Make sure they're JButtons by using an if . . instanceof clause.
Method #2: as you create them in that loop, add them to a List (or even better, a Map). I prefer a Map personally as it lets me customise the key for that specific JComponent
i.e.
HashMap<String, JComponent> buttonList = new HashMap<String, JComponent>();
for(. .) {
buttonList.put("nameForEachButton", button);
}
I recommend generating the button name based off of the loop counter. Either use your existing name value, or just set it to "button" + i;
Declare your buttons using an array.
JButton[] button = new JButton[9]; //outside the for loop
for (int i = 0; i < 10; i++) {
//put your code
button[i] = new JButton(name);
//your code
}

Assigning text field name to variable amount of text fields

My program starts by prompting the user to enter the number of masses they would like to orbit
public class textEvent1 implements ActionListener { //action listener for "how many masses?"
public void actionPerformed (ActionEvent e) {
n = (int)(Double.parseDouble(massNumField.getText()));
submit1.setVisible(false); //removes text event 1 text from screen
massNumLabel.setVisible(false);
massNumField.setVisible(false);
Then with that information I create that number of labels and text fields like so
for(int i=1; i<=n; i++) { //adds text event 2 text to the screen
massLabel = new JLabel("How much mass does Mass " +i+ " have? ");
massField = new JTextField(5);
xCorLabel = new JLabel("What is mass "+i+"'s starting x-coordinate?");
xCorField = new JTextField(5);
yCorLabel = new JLabel("what is mass "+i+"'s starting y-coordinate?");
yCorField = new JTextField(5);
xVelLabel = new JLabel("What is mass "+i+"'s starting x velocity?");
xVelField = new JTextField(5);
yVelLabel = new JLabel("What is mass "+i+"'s starting y velocity?");
yVelField = new JTextField(5);
add(massLabel);
add(massField);
add(xCorLabel);
add(xCorField);
add(yCorLabel);
add(yCorField);
add(xVelLabel);
add(xVelField);
add(yVelLabel);
add(yVelField);
}
Now my problem is reading from these text fields with with another actionlistner (a submit button) and assigning the value entered into an array. Since I dont know how many masses there will be I dont know how many text fields there will be and each text field essentially has the same name, how do I assign say the value entered for mass2's mass when its text field has the same name as all the other text fields?
Use List<JTextField> for each piece of data you need.
So add to your class the instance variables:
List<JTextField> masses, xCors, yCors, xVels, yVels;
Initialize them (ArrayLists probably work fine here), then in that actionPerformed method where you create the JTextFields, add them one by one to the Lists:
for (int i = 1; i <= n; i++) {
massLabel = new JLabel("How much mass does mass " +i+ " have? ");
massField = new JTextField(5);
masses.add(massField);
/* .. initialize all other fields similarly, adding them to the Lists */
When you want to read values from / assign values to the text fields, you can access them from the Lists using masses.get(i).

how to create TextFields dynamically in j2me?

we are developing Mobile application in j2me.In my application, we are using TextField and some other controls in Form.Here, my problem is i want to dynamically create TextField based on User's Credentials.For Example, If Manager is entered,then i want to create certain TextField(based on Manager Selection) for getting input from the Manager.Otherwise,i just want to create TextField that are less than the Manager TextField.
How to Create TextFields Dynamically...
For example like this...
int userSelection=10;
for(int i=0;i<userSelection;i++)
TextField text=new TextField("Some Name",null);
here, our problem is,
I want to create TextField With Different Name...
Please guide me to get out of this issue...
Create the TextField array and refer from array index.
TextField[] textFields = new TextField[10];
for (int i = 0; i < textFields.length; i++) {
textFields[0] = new TextField(label, text, maxSize, constraint);
}
after you use correct parameters to construct TextField, code might look like
import javax.microedition.lcdui.TextField;
import java.util.Vector;
// ...
Vector newTextFields(int userSelection) {
// neither List nor generics in midp sorry
final int MAX_SIZE = 42;
final Vector list = new Vector();
for(int i=0; i < userSelection; i++) {
list.addElement(new TextField("Name #" + i, null,
MAX_SIZE, TextField.ANY);
}
return list;
}
// ...

Categories

Resources