Trying to display from arraylist on a JPanel - java

im new to java swing, and Ive got a little problem.
So I've got a class Flight.java. In there I have a method displaySeat2D().
First I had this done with the scanner. Now Im using swing. So basically I made text fields to take in a number of seats and a number of rows. Now Im trying to display this in JPanel. Guess Id have to use JLabel and display it there. Not realy sure. So instead of 0 and 1, id like to have seats and rows displayed like squares for example. Or if its possible id try to keep it simple and display it like in Eclipse console with 0.
This is the code.
// FLIGHT class:
public void displaySeat2D(){
for (int i = 0; i < arraySeatPassenger.length; i++) {//line
System.out.println("");
for (int j = 0; j < arraySeatPassenger[i].length; j++) {// seat
if (arraySeatPassenger[i][j] == null) {
System.out.print("0");//
} else {
System.out.print("1");
}
}
}
System.out.println("");
}
// UI (display part):
lblDisplay.setForeground(new Color(0, 128, 0));
btnDisplayv.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
// Piece of UI
http://i44.tinypic.com/ajnlo3.jpg
That's basically it. I could use help when I click this button some field would appear with for example 4(seats)x4(rows). Thanks for the help.

Have a look at using a JTable. Each seat can be represented by individual cells with the table managing the alignment of the characters in the ArrayList. For more see How to Use Tables

Related

press buttons one by one

Hello I am new to java language,and I have created a JFrame in NetBeans IDE 8.2 .
The JFrame contains 8 buttons created diretly from swing palette.The case is that I am trying to open another JFrame form after clicking for example 5 buttons.
I know that for appearing another JFrame form it is used setVisible(true) method, in the last btnActionPerformed;
What I am asking is that how to make possible clicking 5 buttons and then appear the other Jframe form??If somebody knows what I am asking please help me to find the solution?
You could have a counter variable that each time you clic on a button it increases by 1 its value and when that value is 5, you call setVisible on your second JFrame.
However I suggest you to read The use of multiple JFrames, Good / Bad practice?. The general consensus says it's a bad practice.
As you provided not code, I can only show you that it's possible with the below image and the ActionListener code, however you must implement this solution on your own:
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
if (e.getSource().equals(buttons[i][j])) {
clics++;
sequenceLabel.setText("Number of Clics: " + clics);
if (clics == 5) {
clics = 0;
frame2.pack();
frame2.setLocationRelativeTo(frame1);
frame2.setVisible(true);
}
}
}
}
}
};

Dynamic Arraylist of checkboxes in Java Swing

I'm writing a GUI Java program for student registration which will retrieve available classes from database, give the user an option to choose classes and then store this in DB.
What I'm trying to do and have so far achieved partial success, is this - I created a combo box with the available majors (got that from DB), retrieved the available classes for that major and displayed check boxes for these classes.
There are two issues with this code.
After selecting the major from combo box, the check boxes aren't displayed. They appear one by one only when I hover my cursor.
Once I change my major in the combo box, the check boxes are not updated, even though the console in eclipse says check boxes for newly selected major has been created.
ArrayList<JCheckBox> checkBoxes=new ArrayList<JCheckBox>();
//combox action listener below
public void actionPerformed(ActionEvent e)
{
//get all available classes for the selected major
avail_class = new String[count_class];
//get all available class ids
avail_classid = new String[count_class];
JCheckBox checkbox;
int xdim = 75;
for (int i = 0; i < count_class; i++)
{
checkbox = new JCheckBox(avail_classid[i] + "-" + avail_class[i]);
checkbox.setBackground(new Color(0, 255, 255));
checkbox.setBounds(183, xdim, 289, 23);
contentPane.add(checkbox);
checkBoxes.add(checkbox);
checkbox.setEnabled(true);
xdim = xdim + 50;
}
}
EDIT
For my second problem, I called repaint() and it worked. For the first one, I did the following:
if(flag < 0)
//flag will be raised whenever there is a change in the selected major. For ex, from web dev to data analytics
for(int i = 0; i < checkBoxes.size(); i++)
{
checkBoxes.get(i).setVisible(false);
System.out.println("old Checkboxes invisible!" + i);
}
you need to call repaint and revalidate function to the container that holds your check boxes to redraw it with the new check boxes .

How can I create actions for a variable number of buttons?

I'm creating a user interface for a game that I have to do as a class project, and needless to say I'm not experienced with Swing.
I did learn about actionevents and whatnot for simple button pushes, but in those cases I knew how many buttons would be on screen. Here, I need to create a board with an arbitrary number of tiles, which will be represented as buttons in Swing. I need to push a button and "move" my character from one tile to another, so I need to call a method on one tile object to remove the player from that tile, and then add it to another tile.
So my question is, given that the number of buttons is generated at runtime (and stored in a 2d array) how can I make an actionlistener that is able to distinguish between each unique button?
Set all your buttons to the same handler:
ActionListener a = new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() == buttons[0][0]) {
}
// etc
// common handling
}
};
for (int i = 0; i < height; ++i)
for (int j = 0; j < width; ++j)
buttons[i][j].addActionListener(a);

Issues with JtextArea. JAVA

I have a GUI setup with with buttons on them and a JTextArea.
I also have an array of Strings with say size of 3.
What I want to do is use an action listener in a way that when the button called "next" is pressed, the JTextArea will then show the next cell in the array. The only problem is it displays the array at the same time. I need it to display the next cell when the button is hit
Can anyone help me with the code? Please and thank you.
final ActionListener m2 = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
arr = new String[3];
arr[0]= "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
arr[1]= "sssssssssssssssssssssss";
arr[2]= "xxxxxxxxxxxxxxxxxxxxx";
for (int i = 0; i<arr.length; i++){
text.append(arr[i]);
}
}
};
next.addActionListener(m2);
So the basic concept is. You need a index value to maintain the current index of the array that is being displayed.
From there, each time the user clicks next, you would increment the index and display the next value in the String
public void actionPerformed(ActionEvent e) {
currentIndex++;
// You need to decide what to do when we reach the end of the array...
String value = myStrings[currentIndex];
textArea.setText(value);
}
To create the button, use the JButton class. To respond to events, use the JButton#addActionListener() method. If you are having trouble, post what you have tried. Good luck!

Collecting data from a large number of Swing text fields

I am currently writing a sudoku solver in Java. What I need now is some kind of Swing GUI to input the known numbers. I created a JFrame, but manually adding 81 text fields from the toolbox seems like a bad solution. I am also able to add with code like this:
this.setLayout(new GridLayout(9, 9));
for (int i = 0; i < 81; i++)
{
this.add(new JTextField("Field"));
}
However, I do not know how to address these text fields afterwards to collect the user input into a two-dimensional array. How can I do that?
A different solution would be to use a JTable. You could allow for the TableModel to maintain the full data solution, as well as a copy of the user's attempts. The CellRenderers and CellEditors could handle the user experience. See this tutorial.
Struggled a bit with this for my own sudoku solver, but ended up going for painting on a JPanel, and adding a mouse listener to that.. Than determine the current field using mouse position with his function:
addMouseListener(new MouseAdapter() {
private int t(int z) {
return Math.min(z / factor, 8);
};
#Override
public void mouseMoved(MouseEvent e) {
setToolTipPossibilities(t(e.getX()), t(e.getY()));
}
#Override
public void mousePressed(MouseEvent e) {
clickColumn = t(e.getX());
clickRow = t(e.getY());
}
});
First you need to declare array of JTextFields.
So just like your array to store user input you do:
private JTextField[] textFields;
After that you can use some math to map your one-dimensional array to your two dimensions.
something like this should work:
floor(index / 9), index % 9
for x,y
Yes that will work to display the array. To read from the array you just need to call the getText method for each element.
JTable is your friend. Use a DefaultTableModel with editable String values.
String[] columnNames = new String[9];
for(int i=0; i<9; i++){columnNames[i]="";}
String[][] data = new String[9][9];
JTable tab = new JTable(columnNames,data);
When they fill it in, check that each string is an appropriate number and prompt for error.
1st way:
You could put the text fields into an array that mirrors the array that your cell values are in.
The problem with this method tho is that when you need to bind a mouseListener or ActionListener to the TextField you will have a hard time figuring out which cell number it corrisponds to.
2nd way:
You could extend the JTextField into a custom class with new instance variables that store cell number in it.
Using this method you can also implement MouseListener or ActionListener on the extended class too and get whatever information about the field you need, without searching through your array. And combining with the first to put them into an array organizes them for quick access.
Just want to post a little update.
I added an array of textfields as a field on my form:
private JTextField[] fields;
Initialized it:
fields = new JTextField[81];
And finally I am adding the fields to my form like this:
private void addComponents()
{
this.setLayout(new GridLayout(9, 9));
for (int i = 0; i < fields.length; i++)
{
fields[i] = new JTextField("" + i);
this.add(fields[i]);
}
}
The result as of now can be seen here:
Image of my textfields

Categories