Result set in multiple jLabel using array - java

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**

Related

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.

Setting the horizontal alignment of JTextField in a loop

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
public class Excercise24_19 extends JFrame
{
private static int[][] grid = new int[10][10]; //creates a grid
public static void main(String[] args)
{
Excercise24_19 frame = new Excercise24_19(); //creates the frame
frame.setTitle("Excercise 24_19"); //title of window
frame.setLocationRelativeTo(null); //sets location to middle of screen
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true); //displays the window
}
public Excercise24_19()
{
createMatrix(); //creates matrix of numbers inside "grid"
setLayout(new GridLayout(10, 10)); //sets a 10 x 10 layout
String temp; //creates a temp variable to hold number's as string
for(int i = 0; i < grid.length-1; i++)
{
for(int j = 0; j < grid[i].length-1; j++)
{
temp = "" + grid[i][j] + "";
matrix.add(new JTextField(temp, 2));
}
}
}
public static void createMatrix()
{
Random myRand = new Random();
for(int i = 0; i < grid.length-1; i++)
{
for(int j = 0; j < grid.length-1; j++)
{
grid[i][j] = myRand.nextInt(2);
}
}
}
}
PROBLEM: I must create a 10x10 grid with random numbers and use JTextField so that I can change the numbers on the spot. The program must then find the biggest block (Algorithm of O(n^2) complexity) of 1's in the matrix and highlight them red.
Not implemented yet are the listeners or buttons for the other part of this program, and code that finds the largest block of 1's.
My problem is how to i center the text on the JTextFields? Its bothering me because I am not creating variable names for the textfields but I don't see how I am suppossed to center the text inside using ".setHorizontalAlignment(JTextField.CENTER);"
Also will I be able to create listeners for the textfields in case i do change the numbers.
If it helps this is what the end program is suppsed to look like:
This is what my program looks like now:
Thank you in advance for your help!
You have to give the text field a variable name if you want to change its settings. Change this line:
matrix.add(new JTextField(temp, 2));
to these lines:
JTextField text = new JTextField(temp, 2));
text.setHorizontalAlignment(JTextField.CENTER);
matrix.add(text);

How to add jlabels to a jlabel array manually in netbeans?

I created a JLabel array:
private JLabel label[]=new JLabel[10];
How do I add the jlabels to this array in netbeans?
Try this:-
JLabel[] labels = new JLabel[10];
for(int i=0; i<labels.length; i++){
labels[i] = new JLabel("Label Name " + i);
}
I've never used netbeans so I'm not sure if this is what you mean exactly (like some IDE shortcut or something), but you can add JLabels to an array in java by assigning the location in the array to a new JLabel.
JLabel[] label = new JLabel[10];
assigning them manually...
label[0] = new JLabel("text");
or all at once...
for(int i = 0; i < label.length; i++) {
label[i] = new JLabel("text");
}
You don't add elements to array, it is not dynamic, you can just update the entries.
Initially your array has null entries.
JLabel label1 = new JLabel("Okocha");
label[0] = label1;

java nested for() loop throws ArrayIndexOutOfBoundsException

I'm working through a JPanel exercise in a Java book. I'm tasked with creating a 5x4 grid using GridLayout.
When I loop through the container to add panels and buttons, the first add() throws the OOB exception. What am I doing wrong?
package mineField;
import java.awt.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class MineField extends JFrame {
private final int WIDTH = 250;
private final int HEIGHT = 120;
private final int MAX_ROWS = 5;
private final int MAX_COLUMNS = 4;
public MineField() {
super("Minefield");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container mineFieldGrid = getContentPane();
mineFieldGrid.setLayout(new GridLayout(MAX_ROWS, MAX_COLUMNS));
// loop through arrays, add panels, then add buttons to panels.
for (int i = 0; i < MAX_ROWS; i++) {
JPanel[] rows = new JPanel[i];
mineFieldGrid.add(rows[i], rows[i].getName());
rows[i].setBackground(Color.blue);
for (int j = 0; j < MAX_COLUMNS; j++) {
JButton[] buttons = new JButton[i];
rows[i].add(buttons[j], buttons[j].getName());
}
}
mineFieldGrid.setSize(WIDTH, HEIGHT);
mineFieldGrid.setVisible(true);
}
public int setRandomBomb(Container con)
{
int bombID;
bombID = (int) (Math.random() * con.getComponentCount());
return bombID;
}
/**
* #param args
*/
public static void main(String[] args) {
//int randomBomb;
//JButton bombLocation;
MineField minePanel = new MineField();
//minePanel[randomBomb] = minePanel.setRandomBomb(minePanel);
}
}
I'm sure I'm over-engineering a simple nested for loop. Since I'm new to Java, please be kind. I'm sure I'll return the favor some day.
JPanel[] rows = new JPanel[i];
i is 0 in the first iteration, which isn't what you want. Make that:
JPanel[] rows = new JPanel[MAX_ROWS];
Also, I think you want to take that completely outside the for loop, since you seem to be using its elements, which would be uninitialised...
This is also wrong:
JButton[] buttons = new JButton[i];
i can be 0 when j is 2 for example, in which case there's no such thing as a buttons[j]. Make them all MAX_* and I think you want to take them out of the loop, since I don't see the point in recreating them at every iteration. Also, you need to instantiate the individual array elements as well.
This part doesn't really make sense:
for (int j = 0; j < MAX_COLUMNS; j++) {
JButton[] buttons = new JButton[i];
rows[i].add(buttons[j], buttons[j].getName());
}
You're creating an array of i JButtons, and trying to add the jth to rows, which makes little sense and won't work if j >= i. You probably meant to do:
JButton[] buttons = new JButton[MAX_COLUMNS];
for (int j = 0; j < MAX_COLUMNS; j++) {
rows[i].add(buttons[j], buttons[j].getName());
}
But the array still doesn't contain any buttons, all you did is initialize it. There's really no reason for the array at all; this actually works:
for (int j = 0; j < MAX_COLUMNS; j++) {
JButton button = new JButton("foo");
rows[i].add(button, button.getName());
}
JPanel[] rows = new JPanel[i];
When i is 0, you create an array with 0 elements. You then try to access that array, but it has no elements in it.
The problem is that your button array is of size i, but j can be larger than i. For instance, the first time through, you are making an empty array here:
JButton[] buttons = new JButton[i];
because i is equal to 0. You then attempt to access it at index 0, which doesn't exist (since the array has no size) and you get your exception. Should you instead be doing something like:
JButton[] buttons = new JButton[MAX_COLUMNS];
That way you will have a button for each array location. Also, you will probably need to initialize the individual buttons - i.e. something like this:
for (int k = 0; k < MAX_COLUMNS; k++) {
buttons[k] = new JButton();
}
(disclaimer: code not tested, but pulled out of you-know-where for example purposes only. There could be typos or unseen bugs.)
Good luck.
It looks like you're creating way too many arrays. You're creating your arrays INSIDE the loops, so instead of creating 5 rows, you're creating 5 rows 5 times, or 25 rows.
The other problem is that you aren't actually creating any objects, only the array to hold the objects. For each object in your array, you need another "button[j] = new JButton()" line.

Categories

Resources