how to set same action / process to multiple buttons in java - java

I want to create the same actions on multiple buttons of my interface. Is it only feasible by creating seperate action listener methods and calling the method which does the actions or is there any other way? Is it possible by putting the buttons in a group and doing as:-
groupButton.setOnMousePressed(new EventHandler<MouseEvent>(){
public void handle(MouseEvent event){
//some other method called
}
}

(You should really use setOnAction(...) to handle button presses, rather than setOnMousePressed(), but I'll answer the question as posed.)
Just create the handler and assign it to a variable:
EventHandler<MouseEvent> handler = new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
// handle event...
}
};
groupButton.setOnMousePressed(handler);
someOtherButton.setOnMousePressed(handler);

Related

How to Perform Multiple Action on Single Click in Java Swing

I have a Question on performing other buttons action with single button click. Some example code for three buttons:
JButton a = new JButton("a");
a.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Action of a is Here
}
});
JButton b = new JButton("b");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Action of b is Here
}
});
Those should come together, like:
JButton c = new JButton("c");
c.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Action of c is Here
// Action of a
// Action of b
}
});
In the above example i have three buttons a,b,c with its own action; but as you can see, C also has to run the actions of A and B. What are good ways to address this?
The other answers are all correct, but there is one important aspect missing here: be careful about dong "too many things" on the AWT event dispatcher thread.
Meaning: when a button is clicked, an event gets created, and the UI framework uses that special thread to trigger the registered listeners. If one of the listeners now decides to do a intensive computation ... the UI event threads stays busy doing "that". And while doing "that thing"; this thread isn't available to dispatch any other UI event.
So, this is "not only" about creating methodA(), methodB(), methodC() and invoking them in your third action listener. It is also about understanding if combining multiple calls becomes subject to "I should better run those things in a separate thread; to not block the event dispatcher thread".
In that sense: the other answers tell you where to go from here; but be really careful about the "amount of activity" that your "joined actions" button is about to create!
1) Methods
Use methods for each action and call those in the ActionListener.actionPerformed
public void methodA(){}
public void methodB(){
methodA();
}
2) Action instance
You could create your own classes of ActionListener to perform the actions
First action :
class ActionA implements ActionListener{
public void actionPerformed(ActionEvent e) {
...
}
}
An improved action
class ActionB extends ActionA{
public void actionPerformed(ActionEvent e) {
super.actionPerformed(e); //Will call the first action
...
}
}
This is limited since you can't have multiple extends but is also a nice solution
3) Click
Last but I don't like it, use AbstractButton.doClick to dynamicly click on other buttons.
4) Add multiple action
Just notice that the methods is not a setActionListener but a addActionListener meaning that it will accept multiple ActionListener.
So define create two instances
ActionListener listenerA = new ActionLisener ..
ActionListener listenerB = new ActionLisener ..
buttonA.addActionListener(listenerA);
buttonB.addActionListener(listenerB);
buttonC.addActionListener(listenerA);
buttonC.addActionListener(listenerB);
With a small test, I notice that the actions are execute in the order B -> A (might not be a generality).
As said in comment, this should be us knowing the risk, this will . If an action failed because of an exception, should the next one be executed ? By default it won't because the process will not hide exceptions.
I would restrict this solution to GUI management like reseting fields, disabling, ... that could be use in different buttons.
Whatever you want to do on Button click a, you can put in a method and call it from wherever you want.
public void methodForA(){
// do here what you want
}
You can call this now in the methods you want it to call from. In your case from button click A and button click C
JButton a = new JButton("a");
a.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
methodForA();
}
});
// and also in your c-Button
JButton c = new JButton("c");
c.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Action of c is Here
methodForA();
}
});
Create 3 methods for each button indepently from the actionListeners action Perform method and call them from the actionPerfomed methods:
private void btnAClicked(){};
private void btnBClicked(){};
private void btnCClicked(){};
JButton c = new JButton("c");
c.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btnCClicked();
btnAClicked();
btnBClicked();
}
});

JavaFX button not responding on first click

public void handle(){
submit.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
LoginConnection login = new LoginConnection();
boolean pass = login.login(usernameField.getText(), passwordField.getText());
if(pass)
flip(SceneNames.Main);
else
invalLoginMessage.setOpacity(1.00);
}
});
register.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
flip(SceneNames.Register);
}
});
}
When i click on submit or register, it takes two click for it to do anything. How do i fix this?
What happens is that on first click it adds the handlers specified in the method and on second and consecutive clicks, it uses the handlers. To fix it just create separate methods to add through fxml or scene builder.

How to click on a javafx slider

I have a question.
I am creating an audiplayer, almost everything is finished, but I have a small problem.
I can use the slider, but I can only slide it, clicking doesn't work.
How can i fix this, i have seen some solutions for JavaFX but not for a javaFX application which uses FXML (I am using FXML).
Thank you very much!
Slider has a method setOnMouseReleased(EventHandler<? super MouseEvent> value), which means you can easily add a MouseEvent handler for clicking the slider:
mySlider.setOnMouseReleased((MouseEvent event) -> {
// do whatever has to be done
});
Something like this:
timeSlider.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
timeSlider.setValueChanging(true);
double value = (event.getX()/timeSlider.getWidth())*timeSlider.getMax();
timeSlider.setValue(value);
timeSlider.setValueChanging(false);
}
});
This would also cause your value property listener to fire if you have any registered. You can register one like this:
timeSlider.valueProperty().addListener(new InvalidationListener() {
public void invalidated(Observable ov) {
if (timeSlider.isValueChanging()) {
//do something here
}
}
}

How to save selected view highlighted in rcp application?

I have an Eclipse RCP application. In a perspective there are four views and I want to highlight respective views whenever I click on them. Is it possible to do it?
i have tried following code:
private void addFocusBackgroundOnSelectingView() {
viewer.getControl().addListener(SWT.MouseEnter, new Listener() {
#Override
public void handleEvent(Event event) {
viewer.getControl().setBackground(
PlatformUI.getWorkbench().getDisplay()
.getSystemColor(SWT.COLOR_GRAY));
}
});
viewer.getControl().addListener(SWT.MouseExit, new Listener() {
#Override
public void handleEvent(Event event) {
viewer.getControl().setBackground(
PlatformUI.getWorkbench().getDisplay()
.getSystemColor(SWT.COLOR_WHITE));
}
});
}
I want to save the selection even i mouse hover out if that view is already had selected.
The Eclipse PartService keeps track of which part (Editors, Views etc...) is currently active. You can add a listener to the service via the PlatfomUI class:
IPartListener partListener = ...;
IPartService partService = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getPartService();
partService.addPartListener(listener);
The IPartListener interface has partActivated and partDeactivated methods where you can do your highlighting.

SWT/JFace: How to handle Keyevents for each ViewPart or Form?

I'm building an Eclipse application and I'm trying to make a shortcut for launching an action when pressing F5, and make that the default action when that Tab/ViewPart has the focus.
I have read that this is not possible, or very complex. Is there any simple/straight way of doing it?
I tried with:
Display.getCurrent().addFilter(...)
this.addKeyListener(new KeyAdapter() {...})
...
Making this in the constructor is my best:
this.getShell().addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if(e.keyCode == SWT.F5) {
//doAnything()
}
}
});
And this doesn't work when loaded, but if I switch from this to another View/Tab starts to work. But it works too when others have focus (which I don't want).
Is there anyway of making this work at the start, and only when the focus is in the View?
You should define work in a handler & then should use key bindings as given in this example. You can find a good example here. Hope it solves your need.
You should look at RetargetableActions. I think that's Eclipse way of doing it:
You need to look at extensions org.eclipse.ui.bindings and org.eclipse.ui.contexts.
Define a command and its handler
Define a binding for the command
define context (cxtId)
associate context with command so that command is available only when context is active
Activate context when you open the view or form.
If you get the listener of the events of the component it will listen on the events. And if the event occur for this component it will be notified.
To add listener of the key event on the ViewPart we should create the control which could be able listen on the event.
public class SampleView extends ViewPart {
/**
* The ID of the view as specified by the extension.
*/
public static final String ID = "views.SampleView";
private Composite mycomposite;
public void createPartControl(Composite parent) {
mycomposite = new Composite(parent, SWT.FILL);
//then add listener
mycomposite.addKeyListener(keyListener);
}
private KeyListener keyListener = new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(KeyEvent e) {
showMessage("key pressed: "+ e.keyCode);
}
};
//the rest of focusing and handle event
private void showMessage(String message) {
MessageDialog.openInformation(
mycomposite.getShell(),
"Sample View",
message);
}
/**
* Passing the focus request to the viewer's control.
*/
public void setFocus() {
mycomposite.setFocus();
}
}
//the end

Categories