How to dynamically create SWT buttons and their actions? - java

I have one OK button(push button) created.
Based on user input i want to dynamically create 1 to 10 SWT buttons(check box).
How to create it?
If OK button is clicked, how to display which are all check box button has been selected?
Please find below snippet I am trying with:
Set<String> Groups = getData(Contents);
for(String group : contentGroups) {
contentButton = new Button(fComposite, SWT.CHECK);
// is this right way to create dynamic buttons?
contentButton.setText(group);
}
okButton = new Button(lowComposite, SWT.PUSH);
okButton.addSelectionListener(new SelectionListener(){
#Override
public void widgetSelected(SelectionEvent e){
//Here how to get the selection status of contentButtons?
}
}

This will print out the selection state of the buttons:
Set<String> Groups = getData(Contents);
final List<Button> buttons = new ArrayList<Button>();
for(String group : contentGroups)
{
Button newButton = new Button(fComposite, SWT.CHECK);
newButton.setText(group);
// save the button
buttons.add(newButton);
}
Button okButton = new Button(lowComposite, SWT.PUSH);
okButton.addListener(SWT.Selection, new Listener()
{
#Override
public void handleEvent(Event e)
{
// iterate over saved buttons
for(Button button : buttons)
{
System.out.println(button.getText() + ": " + button.getSelection());
}
}
}

Related

How to add two buttons in a TableColumn of TableView JavaFX

I want to add two button in action TableColumn, i already read this How to add button in JavaFX table view and this Add a button to a cells in a TableView (JAVAFX) but both of them use one button in setGraphic, so when i try to use :
actionFld.setCellFactory(param -> new TableCell<Patient, Patient>() {
private final JFXButton editButton = new JFXButton("edit");
private final JFXButton deleteButton = new JFXButton("delete");
#Override
protected void updateItem(Patient patient, boolean empty) {
super.updateItem(patient, empty);
if (patient == null) {
setGraphic(null);
return;
}
deleteButton.setOnAction(event -> {
Patient getPatient = getTableView().getItems().get(getIndex());
System.out.println(getPatient.getNom() + " " + getPatient.getPrenom());
});
editButton.setOnAction(event -> {
Patient getPatient = getTableView().getItems().get(getIndex());
System.out.println(getPatient.getNom() + " " + getPatient.getPrenom());
});
setGraphic(deleteButton);//<<<---------------add button 1
setGraphic(editButton);//<<------------------add button 2
}
});
it show me just one button :
How can i solve this problem?
You can use HBox to add your component one beside the other for example :
HBox pane = new HBox(deleteButton, editButton);
setGraphic(pane);
result:
If you have another way, i will be happy for it!

How to make something use the previous value of an integer even after the integer changes

I am new to programming, using JavaFX at the moment for a personal organization tool. I have showed here an arraylist of buttons(called books) and stages(called bookStages), a VBox called addBook, and an Int called bookButtonCount set to 0.
addBook.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent t) {
addBooks.getChildren().add(books.get(bookButtonCount));
books.get(bookButtonCount).setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent t) {
bookStages.get(bookButtonCount).show();
System.out.println(bookButtonCount);
}
});
bookButtonCount++;
}
});
The first button adds a button from the "books" arraylist to the VBox. The button from the vbox is supposed to open a stage from the stage arraylist. You should be able to fire the button multiple times, each time adding a new button to the vbox and setting that button to open its own stage. Though it seems that using bookButtonCount as a reference will not work because each time you press a button from the books arraylist in the vbox, it checks for the current value of bookButtonCount.(Which changes as more buttons are added) and opens the wrong stage.
Is there any way to have the action for the button be saved with the value of bookButtonCount at the time it is set only?
If not, how should I set this up?
Here is some more bits of code that may be useful:
ArrayList<Stage> bookStages = new ArrayList();
ArrayList<Button> books = new ArrayList();
for (int i=0;i<10;i++){
books.add(new Button("Book " + (i+1)));
bookStages.add(new Stage());
bookStages.get(i).setTitle("Book " + (i+1));
}
Just register the handler when you create the button and stage:
ArrayList<Stage> bookStages = new ArrayList();
ArrayList<Button> books = new ArrayList();
for (int i=0;i<10;i++){
Button button = new Button("Book " + (i+1));
books.add(button);
Stage stage = new Stage();
bookStages.add(stage);
stage.setTitle("Book " + (i+1));
button.setOnAction(e -> stage.show());
}
and
addBook.setOnAction(e -> {
addBooks.getChildren().add(books.get(bookButtonCount));
bookButtonCount++ ;
});

set button on action within method java

How could I set the action of a button within the same method I am creating the buttons?
My desired method would be something like this:
private void buttonsCreation() {
//----------------creation of interactive buttons with text-----------------
Button buttonForLoad = new Button("Load footage file");
Button buttonForSave = new Button("Save footage file");
Button buttonForSaveAs = new Button("Save as footage file");
ButtonbuttonForRun = new Button("Run footage animation");
Button buttonForTerminate = new Button("Stop footage animation");
Button buttonForEditMenu = new Button("Edit current footage");
//---------------setting the interaction of the buttons---------------------
buttonForLoad.setOnAction(loadFootage());
buttonForSave.setOnAction(saveFootage());
buttonForSaveAs.setOnAction(saveAs());
buttonForRun.setOnAction(runAnimation());
buttonForTerminate.setOnAction(terminateAnimatino());
buttonForEditMenu.setOnAction(editMenu());
}
I would like the attributes of setOnAction to call those methods, but I receive this error. setOnAction in ButonBase can not be applied to void.
I am aware I can create a void handle with an ActionEvent as a parameter and make it work, but my desired function will be in one function, and if it is possible with as least lines of code as possible.
Thanks very much
To call void function in action handler, lambda expression is usefull. Like this:
buttonForLoad.setOnAction(e -> loadFootage());
buttonForSave.setOnAction(e -> saveFootage());
...
Maybe did you mean the action listener for example:
private void buttonsCreation() {
//------------creation of interactive buttons with text---------------
Button buttonForLoad = new Button("Load footage file");
buttonForLoad.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// to do something
}
});
...
}

Get the number of checkboxes in Swing

I've a swing with some 50 check boxes, and a sample code for 3 is below.
JCheckBox checkboxOne = new JCheckBox("One");
JCheckBox checkboxTwo = new JCheckBox("Two");
JCheckBox checkboxThree = new JCheckBox("Three");
// add these check boxes to the container...
// add an action listener
ActionListener actionListener = new ActionHandler();
checkboxOne.addActionListener(actionListener);
checkboxTwo.addActionListener(actionListener);
checkboxThree.addActionListener(actionListener);
 
// code of the action listener class
 
class ActionHandler implements ActionListener {
    #Override
    public void actionPerformed(ActionEvent event) {
        JCheckBox checkbox = (JCheckBox) event.getSource();
        if (checkbox == checkboxOne) {
            System.out.println("Checkbox #1 is clicked");
        } else if (checkbox == checkboxTwo) {
            System.out.println("Checkbox #2 is clicked");
        } else if (checkbox == checkboxThree) {
            System.out.println("Checkbox #3 is clicked");
        }
    }
}
Here i want to loop through the 50 checkboxes like creating an ArrayList of the available checkboxes and loop them to check which is checked. I'm unable to understand on how to create a ArrayList of checkboxes.
I referred to Array of checkboxes in java, but i'm unable to understand how do i use it?
Please let me know how can do this.
Create an ArrayList of JCheckBox and add them in order.
Then, you can use the indexOf() function to retrieve the number, like so:
public class TestFrame extends JFrame {
public TestFrame() {
setLayout(new GridLayout());
setSize(500, 500);
JCheckBox checkboxOne = new JCheckBox("One");
JCheckBox checkboxTwo = new JCheckBox("Two");
JCheckBox checkboxThree = new JCheckBox("Three");
final ArrayList<JCheckBox> checkBoxes = new ArrayList<>();
add(checkboxOne);
add(checkboxTwo);
add(checkboxThree);
checkBoxes.add(checkboxOne);
checkBoxes.add(checkboxTwo);
checkBoxes.add(checkboxThree);
ActionListener actionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
JCheckBox checkbox = (JCheckBox) event.getSource();
int index = checkBoxes.indexOf(checkbox) + 1;
System.out.println("Checkbox #" + index + " is clicked");
}
};
checkboxOne.addActionListener(actionListener);
checkboxTwo.addActionListener(actionListener);
checkboxThree.addActionListener(actionListener);
}
public static void main(String[] args) {
TestFrame frame = new TestFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Please note that this is adaptation of your code. This example was made as close as possible to your code so that the only modifications present are supposed to reflect the point I'm trying to get across.
Edit
Since you modified your question and a new one was made, here goes the second part of the answer:
and in my action listener, I was trying to get the checked boxes values, but it is throwing null as name and though I've checked, the output shows as not selected.
Modify your code to use getText() instead of getName(), such as:
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println(checkBoxes.size());
for (int i = 0; i < checkBoxes.size(); i++) {
if (checkBoxes.get(i).isSelected()) {
System.out.println(" Checkbox " + i + " and " + checkBoxes.get(i).getText() + " is selected");
} else {
System.out.println(
" Checkbox " + i + " and " + checkBoxes.get(i).getText() + " is noooooot selected");
}
}
}
});
In order to define an ArrayList with CheckBoxes please refer to following example:
List<JCheckBox> chkBoxes = new ArrayList<JCheckBox>();
Add your JCheckBox elements to the ArrayList using standard approach, for example:
JCheckBox chkBox1 = new JCheckBox();
chkBoxes.add(chkBox1);
Interatve over the list and carry out check if selected using JCheckBox method #.isSelected() as follows:
for(JCheckBox chkBox : chkBoxes){
chkBox.isSelected(); // do something with this!
}
If you need to get all checkboxes from actual existing Frame / Panel, you can use getComponents() method and one by one deside if it's checkbox (not sure if getComponents is supported by all containers)
eg.:
Component[] comps = jScrollPane.getComponents();
ArrayList<JCheckBox> chckBoxes= new ArrayList<JCheckBox>();
for(Component comp : comps) {
if(comp instanceof JCheckBox) {
chckBoxes.add((JCheckBox) comp);
}
}
(Founded # Get all swing components in a container )

Showing a right click menu for a SWT TableItem?

Is it possible to show a right click menu on table items with SWT? The menu would be different for every item, e.g for some rows, some of the menu items would be enabled, for others, they would be disabled. So, each row would need its own menu, and when setting up the menu i'd need a way to identify which row I was working with.
Any ideas?
Listening for SWT.MouseDown, as suggested by #user4793956, is completely useless. The context menu is always brought up, no need to call setVisible(true). Quite contrary, you need to cancel the SWT.MenuDetect event, if you do not want the menu to pop up.
This works for me:
// Create context menu
Menu menuTable = new Menu(table);
table.setMenu(menuTable);
// Create menu item
MenuItem miTest = new MenuItem(menuTable, SWT.NONE);
miTest.setText("Test Item");
// Do not show menu, when no item is selected
table.addListener(SWT.MenuDetect, new Listener() {
#Override
public void handleEvent(Event event) {
if (table.getSelectionCount() <= 0) {
event.doit = false;
}
}
});
Without using a DynamicTable:
Menu contextMenu = new Menu(table);
table.setMenu(contextMenu);
MenuItem mItem1 = new MenuItem(contextMenu, SWT.None);
mItem1.setText("Menu Item Test.");
table.addListener(SWT.MouseDown, new Listener(){
#Override
public void handleEvent(Event event) {
TableItem[] selection = table.getSelection();
if(selection.length!=0 && (event.button == 3)){
contextMenu.setVisible(true);
}
}
});
table = new DynamicTable(shell, SWT.BORDER | SWT.FULL_SELECTION);
table.addMenuDetectListener(new MenuDetectListener()
{
#Override
public void menuDetected(MenuDetectEvent e)
{
int index = table.getSelectionIndex();
if (index == -1)
return; //no row selected
TableItem item = table.getItem(index);
item.getData(); //use this to identify which row was clicked.
//The popup can now be displayed as usual using table.toDisplay(e.x, e.y)
}
});
More details: http://www.eclipsezone.com/eclipse/forums/t49734.html

Categories