I've been looking all over the net for a code that is something like this:
JTextField[] jt = new JTextField{jTextField1,jTextField2,..};
I had a copy of this code once and I kept it in a hard disk because I know I might use it in the future, but the disk died!
can anyone help me find this code? It gives me error so please do correct this for me. thanks!
by the way, this is an array for an existing jTextField and it runs inside a button when pressed.
EDIT: since this was flagged as possible duplicate, heres my explanation.
The classic initialization has already been tested and what ive seen yet so far in declaring jTextField array is this:
JTextField[] jt = new jTextField[10];
specifying the value then adding it.
jTextField[n] = new JTextField(jTextField1);
if i use that method, I would have to type it all over again.
jTextField[n] = new JTextField(jTextField2);
jTextField[n] = new JTextField(jTextField3);.. and so on and so forth.
now what I am looking for is what i've said on the sample code. I have used this once but I was clumsy enough not to back it up.
This is wrong syntax and will throw a compilation error:
JTextField[] jt = new JTextField{jTextField1,jTextField2};
You need to do:
JTextField[] jt = new JTextField[] {jTextField1,jTextField2}; // or you can do {jTextField1,jTextField2};
I tried this and it works fine:
JTextField j1 = new JTextField();
JTextField j2 = new JTextField();
JTextField[] j = new JTextField[] {j1, j2};
//JTextField[] j = {j1, j2}; // This syntax also works
System.out.println(j);
I think it's not possible to do what you want. Try to code some cycle to create and add JTextFields to you array.
int x = 2;
JTextField[] textFields = new JTextField[x];
for(int i = 0;i < x; i++) {
JTextField textField = new JTextField(blabla);
textField.setSomething();
textFields [i] = textField;
}
Silly netbeans..
I closed my project down and re-opened it just to try it out. well guess what. the code works properly now.
public void arrayoftextboxes(){
JTextField[] jt = {jTextField1, jTextField2};
}
Related
To start with -- I'm not sure, that I have properly formulated the question (I'm new in Java and in making programs with GUI).
It is the following thing, I'm trying to do. I have a window with several similar parameters (numbers are just for distinction between lines and it ist just very simplified example, of what should my GUI be):
Initial Window
Then, by clicking on the "+"-button I would like to add an new line, like here:
Line 35 is added
It should be also possible to delete lines, like here: Line 30 was deleted, by pressing "-"-Button.
As I wrote at the beginning, it is possible, that there was such a question, but I couldn't find anything (probably, because I do not now the keywords or I was looking with a wrong ones).
How such window can be done? The only idea I have is to draw a new window after every +/-.
Addition: Code (not working in the part of changing the number of rows).
import javax.swing.*;
import java.awt.event.*;
public class Test extends JFrame {
public Test() {
setSize(200, 600);
JButton plusButton[] = new JButton[100];
JButton minusButton[] = new JButton[100];
JTextField fields[] = new JTextField[100];
JPanel panel1 = new JPanel();
for (int i=0; i<plusButton.length; i++) {
plusButton[i]=new JButton("+");
minusButton[i]=new JButton("-");
fields[i] = new JTextField("Text "+ i);
}
for (int i=1; i<4; i++) {
panel1.add(plusButton[i*10]);
plusButton[i*10].setActionCommand("add after " +String.valueOf(i));
panel1.add(minusButton[i*10]);
minusButton[i*10].setActionCommand("remove " +String.valueOf(i));
panel1.add(fields[i*10]);
}
panel1.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
this.getContentPane().add(panel1);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
for (int i=0; i<100; i++) {
String stand1 = "add after "+String.valueOf(i);
String stand2 = "remove "+String.valueOf(i);
if (stand1.equals(e.getActionCommand())) {
//add "row" of elements
panel1.add(plusButton[i]);
plusButton[i+1].setActionCommand("add");
panel1.add(minusButton[i+1]);
minusButton[i+1].setActionCommand("remove");
panel1.add(fields[i+1]);
} else if (stand2.equals(e.getActionCommand())) {
//delete "row" of elements
}
}
}
public static void main(String[] args) {
Test a = new Test();
}
}
The Problem, that is obvious -- when I want to add 2 rows (i think it is proper definition) of buttons after button 20, there will be an doubling of numbers. As a solution I see here a creation of a new panel for each new row. But it is sounds wrong for me.
P.S. Unfortunately I do not have time to end this topic or to post a working example. I actually found some kind of solution, beginning from the Question here, on Stack Overflow:
Adding JButton to JTable as cell.
So, in case somebody will be looking for such topic, it should sounds like "jButton in jTable".
There are multiple GUI frameworks for Java. First decide which one you wanna use.
As for your particular query
Add functionality to the + and - such that it will create an instance of a field object (that line with parameters as you call them) or destroy that particular instance of the object.
+ is clicked -> Create new object on consecutive line and increase the pointer-count(?) of the following fields.
- is clicked -> Call destructor for the particular object and decrease the pointer-count of the following fields.
I am looking for away to change the text color of all my JLabels with a function so I don´t have to use the setForegroundColor for each and every one of them.
I currently have a bunch of JLabels in a panel called Main. I did a bit of research and came across the instanceof and getComponents method. So I've come this far:
main = new JPanel();
main.setBackground(Color.red);
tf_search = createTF();
l_name1 = new JLabel("Name: "+ DB.findUser(1001).returnName());
l_nick = new JLabel("Nick: " + DB.findUser(1001).returnNick());
l_style = new JLabel("Style: ");
l_styleshow = new JLabel(DB.findUser(1001).returnStyle());
l_music = new JLabel("Favourite songs: ");
l_musicshow1 = new JLabel(DB.findUser(1001).returnMusic1());
l_musicshow2 = new JLabel(DB.findUser(1001).returnMusic2());
l_musicshow3 = new JLabel(DB.findUser(1001).returnMusic3());
l_blank = new JLabel("");
l_blank2 = new JLabel("");
l_inst = new JLabel("Instrument: ");
l_instshow = new JLabel(DB.findUser(1001).returnInst());
l_band = new JLabel("Band: ");
l_bandshow = new JLabel(DB.findUser(1001).returnBand());
b_search = new JButton("Sök");
b_musicchn = new JButton("Edit Profile");
b_return = new JButton("Return to profile");
main.setLayout(new GridLayout(9,2));
main.add(l_name1);
main.add(l_nick);
main.add(l_style);
main.add(l_styleshow);
main.add(l_music);
main.add(l_musicshow1);
main.add(l_blank);
main.add(l_musicshow2);
main.add(l_blank2);
main.add(l_musicshow3);
main.add(l_band);
main.add(l_bandshow);
main.add(l_inst);
main.add(l_instshow);
main.add(b_search);
b_search.addActionListener(new searchHandler());
main.add(b_musicchn);
b_musicchn.addActionListener(new editHandler());
main.add(tf_search);
main.add(b_return);
b_return.addActionListener(new returnHandler());
And all the Panels and stuff are declared, or what to call it. ex "private JLabel l_nick, etc"
So I thought this might select all JLabels and turn the text to white, but my code doesn't work hehe. Is this a legit way of doing things and can you correct it, or does someone know another way. Thanks in advance!
Note: I am a student and this is for my final project in my first programming year, so I just want the code variety. If it is not possible with a massive, advanced block of code don't bother typing it out, even though your help is appreciated!
don't do this:
main.getComponents(l_label instanceof JLabel).setForegroundColor(Color.White);
instead define a List<JLabel> mylabels = ...
populate the list:
myLabels.add(l_label);
myLabels.add(l_label2);
myLabels.add(l_label3);
and do a for enhanced
for(JLabel x:myLabels){
x.setForegroundColor(Color.White);
}
You may retrieve all child components, check if they are JLabel, and set the color accordingly .
for (Component component : panel.getComponents()) {
if (component instanceof JLabel) {
component.setForeground(Color.WHITE);
}
}
I don't know of a method getComponents that takes a filter argument. But you could use streams to filter. Something like this:
Stream.of(main.getComponents()).filter(component -> component instanceOf JLabel).forEach(label -> ((JLabel)label).setForegroundColor(Color.White));
In my applet program I have the TextField declared in my public class header as:
TextField numbers [][] = new TextField[5][5];
I also have a button that is supposed to clear all the textboxes when clicked.
Right now I basically have this:
JButton b = new JButton("Clear");
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
numbers.setText("");
}
});
But I'm getting an error: "Cannot invoke setText(null) on the array type TextField[][]"
How can I fix this?
Key lesson here: read the error message critically as it is telling you exactly what is wrong.
"Cannot invoke setText(null) on the array type TextField[][]"
You're treating the numbers variable as if it's a single TextField and it's not, and so you can't call setText(...) on it -- rather it's a 2D array of objects. A solution is to think of how you interact with any similar 2-d array, how do you call methods on each item held within the array: use nested for loops to iterate through the array.
for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < numbers[i].length; j++) {
numbers[i][j].setText("");
}
}
Also, change TextField to JTextField so that you're using all Swing components:
// change type from TextField to JTextField
JTextField numbers [][] = new JTextField[5][5];
I am having problems with the gridbag layout, I am trying to get the images to be on one line horizontally, however when I add images to the left of the original one, it will go down vertically instead of going horizontally to the left.
I have tried to specify the gridY to be the same, however this did not work, also I have tried the GridBayConstarints.Horizontal however that was irrelevant.
So far I have
import java.awt.GridBagConstraints;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
public class main {
public static void main(String[] args)
{
GUI g = new GUI();
int turnCounter = 1;
for(int i = 0; i<6; i++)
{
String image = "src/resources/bone"+0+i+".png";
GridBagConstraints c = new GridBagConstraints();
//ADDS IMAGE TO THE LEFT
if(turnCounter%2 == 0)
{
c.gridy = c.gridy;
c.gridx = c.gridx-1;
ImageIcon icon1 = new ImageIcon(image);
JLabel label1 = new JLabel((ImageIcon) icon1);
g.add(label1,c);
g.revalidate();
turnCounter++;
}
//ADD IMAGES TO THE RIGHT
else if(turnCounter%2 == 1)
{
c.gridy = c.gridy;
c.gridx = c.gridx+1;
ImageIcon icon1 = new ImageIcon(image);
JLabel label1 = new JLabel((ImageIcon) icon1);
g.add(label1,c);
g.revalidate();
turnCounter++;
}
}
}
}
What the image looks like at the moment.
The [2|0] and [3|0] should be to the left of [0|0] in that order so it will look like this
[4|0][2|0][0|0][1|0][3|0][5|0] all in one line.
The code you used for putting things to the right is correct, but as the default value of gridx is 0, what you are doing when you try to add a component to the left is giving a value to gridx of -1, an incorrect value for gridx, seems like the problem is there.
The solution I can give right now, is making an array with a lenght of how many images you want to display, in this case it would be a:
int yourLenght = 5; //Sounds dirty lol
JLabel[] yourArray;
yourArray = new JLabel[myLenght]
After this, only select the place of the array where you want to place it, I would recommend it in the middle.
Why does this work?
Now your images can only be on the 5th or 1st column (gridx = 0), but not on -1, altough we haven't finished yet, if you leave it like this, and you add or quit one to "yourLenght" your images could only be placed on the 2nd column or the 4th one, cause you can only add or quit one to 3. To avoid these what we are going to do is declare another int.
int magicInt = 1;
And then after each component is added we will add 1 to the "magicInt" value.
//You already added the object rather on the left or on the right
magicInt++;
And that way each time you add an object you can advance one place to the left or to the right more.
Notes:
1-Anchors won't work if you don't give a value to weighty. You can read more about these variables here.
2-I discourage using
c.gridy = c.gridy;
If you are only going to use that loop for adding things on one row, better use:
c.gridy = 0;
That way your code is easier to read.
3- Solution listed above only works if objects are added consitently with the following pattern : left, right, left, right... or right, left, right, left...
(It was a quick solution, but you will find your solution just think...)
Hope, this helped you, if you have any doubts don't mind commenting that way I can help :)
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;
}
// ...