Java Swing - Dynamically create JTextField - java

I want to create several JTextFields that I can then get the user data from once they hit a submit button. I am using the code below to dynamically create labels for the text fields and was planning on creating the text fields in a similar way, but I realized that if I do that the fields won't have variable names and I won't be able to extract the data. Is there a way to dynamically assign variable names or otherwise retrieve the data from the text fields if I create them in a way similar to what's shown below?
int autoX = 0;
int autoY = 0;
for (int i = 0; i< units.numOfUnits(); i++ ){
c.gridx = (autoX % 5);
c.gridy = autoY;
if((autoX % 5) == 4){
autoY++;
}
mainPanel.add(new JLabel(units.getUnit(i)),c);
autoX++;
}

You need to keep a reference to the text fields you create. Like this:
List<JTextField> textFields = new ArrayList<JTextField>();
int autoX = 0;
int autoY = 0;
for (int i = 0; i< units.numOfUnits(); i++ ){
c.gridx = (autoX % 5);
c.gridy = autoY;
if((autoX % 5) == 4){
autoY++;
}
mainPanel.add(new JLabel(units.getUnit(i)),c);
JTextField textField = new JTextField();
mainPanel.add(textField);
textFields.add(textField);
autoX++;
}
Then you can refer to a specific text field with:
textFields.get(0).getText();

Related

Result set in multiple jLabel using array

How can I create a multiple jLabel using the result set from database column?
I spent almost 2 days trying to solve but unfortunately i still didn't get it correct. please help me.
Here's my codes:
String[] arr = null;
try{
String sql = "SELECT * FROM Position";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()){
String s1 = rs.getString("PositionName");
arr = s1.split("\n");
int v = 50;
for (int i = 0; i < arr.length; i++){
JLabel[] labels = new JLabel[i];
labels[i] = new JLabel();
labels[i].setBounds(50,v,80,20);
labels[i].setText(arr[i]);
jPanel3.add(labels[i]);
v+=40;
System.out.println(arr[i]);
}
jPanel3.repaint();
}
I want a result something like this, (in a jLabel)
President
Vice-President
Secretary
if i make int i = 0 the output is "java.lang.ArrayIndexOutOfBoundsException:0"
if i make it int i = 1, there's no error but not created jLabel at all.
When i == 0, then
JLabel[] labels = new JLabel[i];
creates an array which can't hold anything since it's size is 0. So then
labels[i] = new JLabel();
attempts to set the element at index 0 which causes the exception.
The code is attempting to do too much which can make it difficult to find bugs. Try separating the code into single responsibility methods such as:
List<String> getAvailablePositions() {
// get the positions from the database
}
and
void addPositionLabels(List<String> availablePositions) {
// add the positions to the JPanel
}
initialize JLabel array outside the for-loop
JLabel[] labels = new JLabel[arr.length];
for (int i = 0; i < arr.length; i++){
labels[i] = new JLabel();
labels[i].setBounds(50,v,80,20);
labels[i].setText(arr[i]);
jPanel3.add(labels[i]);
v+=40;
}
**here is the sample code **
JFrame frame = new JFrame();
frame.setSize(300,300);
JPanel panel = new JPanel();
panel.setLayout(null);
int v = 50;
JLabel[] labels = new JLabel[3];
for (int i = 0; i < 3; i++){
labels[i] = new JLabel();
labels[i].setBounds(50,v,80,20);
labels[i].setText("hi");
panel.add(labels[i]);
v+=40;
}
frame.add(panel);
frame.setVisible(true);
**you will get the following result
hi
hi
hi**

How do I access one button from a 2D array of buttons? Java JSwing

I am trying to create a grid of buttons.
This is my code to create the grid (which works), but if I want to access a single button later on how would I go about doing that?
for(int i = 1; i<= row; i++){
for( int p=1; p<= col; p++){
boardPanel.add(new JButton());
}
}
Many Thanks
A Clements;
From your question title I'm assuming that you want to be able to access these buttons from a 2d array, but in your code the button is not in an array. If you did something like the following:
JButton[][] buttons = new JButton[row][col];
for(int i = 1; i<= row; i++){
for( int p=1; p<= col; p++){
buttons[i][p] = new JButton();
boardPanel.add(buttons[i][p]);
}
}
Then you are maintaining a 2d array that contains references to the buttons in your JPanel. So now you can access the buttons from the array like this:
buttons[i][j];

How to add multiple labels using for loop In an applet?

I want to add 70 labels and 70 checkboxes in an applet I takes lot of code when we write normally . how to add these labels using for loop
You could use a for loop to add Labels to an array. Something like
List<Label> li = new List<Label>();
for(int i = 0; i < 70; i++)
{
li.add(new Label("label " + i));
}
If you don't want to use an array just you could just add the labels directly to your layout.
FlowLayout fl = new FlowLayout(FlowLayout.CENTER, 10, 10);
for(int i = 0; i < 70; i++)
{
fl.add(new Label("label " + i));
}

Difference between initialization of array with two dimensions

In my JPanel I am using tablelayout.jar Oracle library (have a look here) and so, generally, I have to do the following:
private double[][] size = {
{30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30},
{30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30}
};
JPanel p = new JPanel();
p.setLayout(new TableLayout(size));
where "30" is the dimension respectively for cos and rows. In this case we wanted square cells. So I can do, for example,:
p.add(new JButton(), "1,4" /*"col,row"*/);
We thought that declaring that "size" matrix like that was not good to do and so we changed the initialization like the following:
size = new double[Constants.GUI_ROWS][Constants.GUI_COLS];
for (int i=0; i<Constants.GUI_COLS-1; i++)
for (int j=0; j<Constants.GUI_ROWS-1; j++)
size[i][j] = 30;
where
Constants.GUI_COLS = 19 ({30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30})
and
Constants.GUI_ROWS = 17 ({30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30})
but this does not work. When we try to add something to the JPanel then nothing is shown. It works only if we write the first initialization by hand. Why this?
To achieve the same as you did by hand you can use
double size[][];
size = new double[2][];
size[0]=new double[19];
size[1]=new double[17];
for (int i=0; i<19; i++)
size[0][i] = 30;
for (int i=0; i<17; i++)
size[1][i] = 30;
You got the loop conditions off by one. Should be :
for (int i=0; i<Constants.GUI_COLS; i++)
for (int j=0; j<Constants.GUI_ROWS; j++)
size[i][j] = 30;
Note that if this call
p.setLayout(new TableLayout(size));
comes before this call :
size = new double[Constants.GUI_ROWS][Constants.GUI_COLS];
The old array referred by size will be used by the TableLayout.

How can I return a variable from within a "for" loop inside a mouseEntered method?

I've made a stadiumPanel class that contains a two-dimensional array of JButtons, each with their own MouseListener. Each button corresponds to a "Seat" object, which contains a set of data (inside a separate data class), and when I hover over the button with the mouse, I want to grab the data that corresponds to that button and display it in my parent class (a JWindow).
To do this, I'm trying to use two nested "for" loops inside the MouseEntered() method, which then uses MouseEvent.getSource() to search for the hovered-over JButton (and consequently the index corresponding to the correct Seat). A Seat object at the given index is then returned using my "stad.getSeat" method. Then, from the for loop, I want to store that seat in my "seatHovered" variable so I can access the data corresponding to that Seat from another class. However, I can't manage to change the hoveredSeat variable from within the "for" loop.
How can I do this?
public class StadiumPanel extends JPanel implements MouseListener
{
Seat hoveredSeat;
Stadium stad;
JButton[][] buttons = new JButton[Stadium.ROWS+1][Stadium.COLUMNS+1];
public StadiumPanel(Stadium s){
stad = s;
for (int row = 0; row < Stadium.ROWS; row++){
for (int col = 0; col < Stadium.COLUMNS; col++){
buttons[row][col] = new JButton();
add(buttons[row][col]);
buttons[row][col].addMouseListener(this);
}
}
}
public void mouseEntered(MouseEvent e)
{
for (int row = 0; row < Stadium.ROWS; row++){
for (int col = 0; col < Stadium.COLUMNS; col++){
if (e.getSource() == buttons[row][col] && buttons[row][col] != null){
hoveredSeat = stad.getSeat(row,col);
}
}
}
}
}
My apologies if this question is ridiculously confusing. Any input is much appreciated.

Categories

Resources