Dynamic Arraylist of checkboxes in Java Swing - java

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 .

Related

Rapidclipse - multiple windows in one screen using a filter to select

Is there a possibilty to create a certain number of windows in one screen. Each window has the same layout but different content. I would like to include a filter so that I can choose which window I would like to see. Right now I have a table with four entries. For each entry one window is generated, but that looks quite messy.
final int i = this.table.size();
for (int h = 1; h <= i; h++) {
final Window win = new Window("Window" + h, new SecondView());
this.getParent().getUI().addWindow(win);
}
Edit:
The Starting point is as described. I have a table with content from a database. In this table i can select multiple rows. For each row a pre-defined window should open. In this window i have textFields, that should contain the values of the matching attributes from the selected row. In order to get a better structure i want to choose which window should be visbile.
final int i = this.table.size();
List<Window> windowList= new LinkedList<>();
for (int h = 1; h <= i; h++) {
Window win = new Window("Window" + h, new SecondView());
windowList.add(win);
}
Then later on, you can itterate the list and do addWindow(...) or removeWindow(...)with the correct window instance
Here is what you need to do:
1) fetch the selected items from the table. Not the amount of selected items, but the actual items - instances of Person if your table is of type Person.
2) iterate over these selected items.
2.a) For each item, create a new Window and pass that item into the constructor of your SecondView, so each SecondView can show values of that item or bind inputs to this bean.
2.b) Add that window to the UI
Since I am not very accustomed to the Table class I use a newer Grid instead in my example. I'm sure the table has some API to get the selected rows - use that instead.
Button openDetailWindowsButton = new Button("Open Details", click -> {
Set<Person> selectedItems = grid.getSelectedItems();
for (Person selectedItem : selectedItems) {
Window win = new Window(selectedItem.getName(), new SecondView(selectedItem));
this.getParent().getUI().addWindow(win);
}
});
Thank you for your help, but meanwhile i found another solution.
private void button_buttonClick(final Button.ClickEvent event) {
final int i = this.table.getSelectedItems().size() - 1;
for(int h = 0; h <= i; h++) {
final int personId = this.table.getSelectedItems().get(h).getBean().getId();
final Window win = new Window("Person", new SecondView(personId));
this.getUI().addWindow(win);
}
That's the button click event.
And here is the constructor for my SecondView
public SecondView(final int personId) {
super();
this.initUI();
final Person myPerson = new PersonDAO().find(personId);
this.fieldGroup.setItemDataSource(myPerson);
}
The one last problem that i have, is that for every selected person/row each window shows seperately. My intent was to only show one window where i can select between the different selected persons/rows.

Java determining if which JRadioButton was selected

I know that it is possible in an event driven program in Java to find out what object caused an event (e.g. JRadioButton was selected, therefore a certain action will take place). My question is, if you have 2 JRadioButtons in a buttongroup, both with action listeners added to them, and you keep selecting from one to the other, is it possible to find out what JRadioButton was previously selected? In other words, if I selected another JRadioButton, is it possible to write code that determines which JRadioButton was previously selected before selecting the current JRadioButton?
public class Drinks extends JPanel implements ActionListener{
double drinksPrice = 2.10;
double noDrinks = 0;
static String selectedDrink;
JRadioButton btnPepsi = new JRadioButton("Pepsi"); //add a button to choose different drinks
JRadioButton btnMtDew = new JRadioButton("Mt Dew");
JRadioButton btnDietPepsi= new JRadioButton("Diet Pepsi");
JRadioButton btnCoffee = new JRadioButton("Coffee");
JRadioButton btnTea = new JRadioButton("Tea");
JRadioButton btnNone = new JRadioButton("None");
JLabel lblDrinksHeading = new JLabel("Choose a drink (each drink is $2.10):");
ButtonGroup drinksButtonGroup = new ButtonGroup();
private static final long serialVersionUID = 1L;
public Drinks(){
setLayout(new FlowLayout()); //Using GridLayout
btnPepsi.setActionCommand(btnPepsi.getText()); //set the ActionCommand to getText so I can retrieve the name for the receipt
btnMtDew.setActionCommand(btnMtDew.getText());
btnDietPepsi.setActionCommand(btnDietPepsi.getText());
btnCoffee.setActionCommand(btnCoffee.getText());
btnTea.setActionCommand(btnTea.getText());
btnNone.setActionCommand(btnNone.getText());
drinksButtonGroup.add(btnPepsi);
drinksButtonGroup.add(btnMtDew);
drinksButtonGroup.add(btnDietPepsi);
drinksButtonGroup.add(btnCoffee);
drinksButtonGroup.add(btnTea);
drinksButtonGroup.add(btnNone);
btnNone.setSelected(true); //set default to "none"
btnPepsi.addActionListener(this);
btnMtDew.addActionListener(this);
btnDietPepsi.addActionListener(this);
btnCoffee.addActionListener(this);
btnTea.addActionListener(this);
btnNone.addActionListener(this);
add(lblDrinksHeading);
add(btnPepsi);
add(btnDietPepsi);
add(btnMtDew);
add(btnCoffee);
add(btnTea);
add(btnNone);
repaint();
revalidate();
selectedDrink = drinksButtonGroup.getSelection().getActionCommand();
//add the drink price to totalPrice, it is adding it every time though, even if its none
/*if(drinksButtonGroup.getSelection() == btnNone){
MenuFrame.totalPrice += 0;
}
else{
MenuFrame.totalPrice += drinksPrice;
}
*/
// buttonGroup1.getSelection().getActionCommand()
//String selectedDrink = drinksButtonGroup.getSelection().toString();
//class
}
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(source == btnNone) {
MenuFrame.totalPrice += 0;
TaxAndGratuityFrame.subtotalTextField.setText("$" + MenuFrame.totalPrice);
TaxAndGratuityFrame.subtotalVariable = MenuFrame.totalPrice;
TaxAndGratuityFrame.taxVariable = TaxAndGratuityFrame.subtotalVariable * TaxAndGratuityFrame.TAX_RATE;
TaxAndGratuityFrame.taxTextField.setText("$" + TaxAndGratuityFrame.taxVariable);
Receipt.receiptTotal.setText("Total: $" + (MenuFrame.totalPrice));
Receipt.receiptsubtotal.setText("Subtotal: " + (TaxAndGratuityFrame.subtotalVariable));
}
else {
MenuFrame.totalPrice += drinksPrice;
TaxAndGratuityFrame.subtotalTextField.setText("$" + MenuFrame.totalPrice);
TaxAndGratuityFrame.subtotalVariable = MenuFrame.totalPrice;
TaxAndGratuityFrame.taxVariable = TaxAndGratuityFrame.subtotalVariable * TaxAndGratuityFrame.TAX_RATE;
TaxAndGratuityFrame.taxTextField.setText("$" + TaxAndGratuityFrame.taxVariable);
Receipt.receiptTotal.setText("Total: $" + (MenuFrame.totalPrice));
Receipt.receiptsubtotal.setText("Subtotal: " + (TaxAndGratuityFrame.subtotalVariable));
}
}
Edit: I'll be more specific. I am creating an "imaginary" restaurant program. In it, I list several drinks that have the same price (e.g. Pepsi: $2.10, Mountain Due: $2.10, etc). These listed drinks are JRadioButtons. Once a customer clicks one of these buttons to "order a drink", $2.10 will be added to a "total" variable. However, a problem occurs when a user wants to change there drink, because if they click a different JRadioButton, $2.10 will still be added to the "total" variable. I want to make it so that they can change there drink without adding $2.10 to the order every time.
I think the problem is at this line:
MenuFrame.totalPrice += drinksPrice;
Because "+=" increments a value by another value instead of simply adding two values.
So every time the user clicks on one of the radio buttons, it will continuously add 2.10 to your total value, whereas if you were you just say:
MenuFrame.totalPrice = MenuFrame.totalPrice + drinksPrice;
It will set your total price equal to the current total price plus the price of drinks, instead of adding 2.10 to the total value every time a button is pressed.
Perhaps I am misunderstanding the question, but I am thinking along the lines of creating a public variable, and then inside the action listeners updating the variable with the radio button that was just selected. When the selected event fires, you can look at the variable to see which radio button had last been selected, do what you want to about it, and then update it with the new radio button.

Creating a GUI with for loop using Java Swing

I have a GUI, from this GUI I choose an input file with the dimensions of a Booking system(new GUI) If the plane has 100 seats the GUI will be for example 10x10, if the plane has 200 seats it will be 10x20, all the seats are going to be buttons, and should store passenger information on them if they are booked.Also a booked seat shall not be booked again.
The question is the dimensions of the GUI will change according to the seat numbers and orientation, which means in one version there can be lots of buttons on another less, also more seats means the GUI will be longer or wider maybe 10 cm x 10 cm or 10 cm x 20 cm, or 15 cm x 25 cm...
I am thinking to do this with a for loop but I dont want to put buttons out of the GUI.I dont know how can I add a button next to the other button arbitrarily. I always used Eclipse Window Builder for building GUIs but I guess I need to write this one on my own... can someone help me?Some hints?Thanks for your time!
Try something like this:
// The size of the window.
Rectangle bounds = this.getBounds();
// How many rows of buttons.
int numOfRows = 100;
// How many buttons per row.
int numOfColumns = 50;
int buttonWidth = bounds.width / numOfRows;
int buttonHeight = bounds.height / numOfColumns;
int x = 0;
int y = 0;
for(int i = 0; i < numOfColumns; i++){
for(int j = 0; j < numOfRows; j++){
// Make a button
button.setBounds(x, y, buttonWidth, buttonHeight);
y += buttonHeight;
}
x += buttonWidth;
}
This will make all the buttons fit inside of your window.
Here's a link on rectangles, they come in pretty handy when doing things like this.
http://help.eclipse.org/helios/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fapi%2Forg%2Feclipse%2Fswt%2Fgraphics%2FRectangle.html
Also, you can still use windowbuilder, infact I recommend you do. It really helps you to visualize the dimensions you want. AND you can also create stuff (buttons, lists, dropdowns... etc) manually with code and, assuming you put the variables where WindowBuilder would, it will still display them in the 'design' tab.
Hope this helps!
EDIT: I was kinda vague on how to make buttons using a loop
To make buttons with a loop you will need a buffer (to store a temporary button long enough to add to a list) and... a list :D.
This is how it should look:
Outside loop:
// The list to store your buttons in.
ArrayList<Button> buttons = new ArrayList<Button>();
// The empty button to use as a buffer.
Button button;
Inside loop (where the '//Make a button' comment is):
button = new Button(this, SWT.NONE);
buttons.add(button);
Now you have a list of all the buttons, and can easily access them and make changes such as change the buttons text like so;
buttons.get(indexOfButton).setText("SomeText");
EDIT:
Seeing as you're new to swt (and I couldn't get awt/JFrame to work) here's the full code.
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class ButtonTest extends Shell {
/**
* Launch the application.
* #param args
*/
// Code starts here in main.
public static void main(String args[]) {
try {
Display display = Display.getDefault();
// Creates a window (shell) called "shell"
ButtonTest shell = new ButtonTest(display);
// These two lines start the shell.
shell.open();
shell.layout();
// Now we can start adding stuff to our shell.
// The size of the window.
Rectangle bounds = shell.getBounds();
// How many rows of buttons.
int numOfRows = 5;
// How many buttons per row.
int numOfColumns = 3;
int buttonWidth = bounds.width / numOfRows;
int buttonHeight = bounds.height / numOfColumns;
Button button;
int x = 0;
int y = 0;
for(int i = 0; i < numOfColumns; i++){
for(int j = 0; j < numOfRows; j++){
button = new Button(shell, SWT.NONE);
button.setBounds(x, y, buttonWidth, buttonHeight);
x += buttonWidth;
}
x = 0;
y += buttonHeight;
}
// This loop keeps the shell from killing itself the moment it's opened
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the shell.
* #param display
*/
public ButtonTest(Display display) {
super(display, SWT.SHELL_TRIM);
createContents();
}
/**
* Create contents of the shell.
*/
protected void createContents() {
setText("SWT Application");
setSize(800, 800);
}
#Override
protected void checkSubclass() {
// Disable the check that prevents subclassing of SWT components
}
Also, I made a little typo in my nested loop (and forgot to reset the x value to 0 after each row). It's fixed in this edit.
Also you will need to import swt for this to work.
Go here: http://www.eclipse.org/swt/ and download the latest version for your operating system, then go in eclipse, right click your project > Build Path > configure Build Path > Libraries tab > Add external JAR's > find the swt file you downloaded and click.
Sorry for such a long answer, hope it helps :D
Start with a GridLayout. Each time you need to change the seat layout, reapply the GridLayout.
Ie, if you need 100 seats, use something like, new GridLayout(20, 10)...
Personally, I'd use a GridBagLayout, but it might be to complex for the task at hand
Its a little more difficult to add/rmove new content. I would, personally, rebuild the UI and reapply the model to it.
As for the size, you may not have much control over it, as it will appear differently on different screens. Instead, you should provide means by which you can prevent the UI from over sizing the screen.
This is achievable by placing the seating pane within a JScrollPane. This will allow the seating pane to expand and shrink in size without it potentially over sizing on the screen
Take a look at
Creating a UI with Swing
Using Layout Managers
A Visual Guide to Layout Managers

Trying to display from arraylist on a JPanel

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

JCombobox and JTextfield

I'm trying to work to display a number of jtextfield according to one of the given values in a combobox.
So, I will have a drop down menu with let's say 1 to 4. If the user selects number 3, 3 textfields will be displayed. I've created the jcombobox with a selection of numbers. But I'm not sure how to implement this. If I'm not mistaken I need to use
ItemEvent.SELECTED
I think I need to create a reference to the JTextField object that will be available to the JComboBox's itemListener object.
Any help would be greatly appreciated.
I've added this to my class :
// aOption is the combobox I declared
aOptionComboBox.setModel(new DefaultComboBoxModel(new String[]{"1","2","3"}));
public void itemStateChanged(ItemEvent event) {
String num = (String)aOptionComboBox.getSelectedItem();
int num1 = Integer.parseInt(num);
JTextField[] textfields = new JTextField[num1];
for (int i = 0; i < num1; i++)
{
textfields[i] = new JTextField("Field");
getContentPane().add(textfields[i]);
textfields[i].setBounds(200, 90, 100, 25);
}
}
am I on a right track?
use the getSelectedItem() on the combobox. This will either yield a string or an integer (depending on how you implemented it). Next use a for-loop to determine the amount of JTextField's and store them in an array.
int amount = myJComboBox.getSelectedItem();
JTextField[] textfields = new JTextField[amount];
for (int i = 0; i < amount; i++) {
textfields[i] = new JTextField("awesome");
this.add(textfields[i]);
}
this way you can easily store the textfields and add them to your panel.
Some added information.
The textfield-array must be accesible outside the eventListener, so you must implement it in your class. that way the whole class can use it.

Categories