call component Listener manually - java

I add a listener to JCheckBox component and I want call listener manually.how do it?
myCheckBox.selected(false)
then I want to called myCheckBox listener. Do you have better idea?

I know I'm a bit late, but this should do the trick:
ItemListener listener = new ItemListener() {
public void itemStateChanged(ItemEvent e) {
//whatever your itemStateChanged() looks like.
}
};
JCheckBox checkBox = new JCheckBox();
checkBox.addItemListener(listener);
Then, whenever you need to call it manually:
listener.itemStateChanged(
new ItemEvent(checkBox, ItemEvent.ITEM_STATE_CHANGED, checkBox, 0));
If you created your listener anonymously, you can still access it like:
checkBox.getItemListeners()[0].itemStateChanged(
new ItemEvent(checkBox, ItemEvent.ITEM_STATE_CHANGED, checkBox, 0));

I really don't know what checkBox component you use. You don't tell us which framework do you use or provide other helpful context infos.
But in general: Your listener is impl. an interface. This interface defines the callbackmethod that your component (checkBox) calls.
If you have a instance of your listener obj. you can call this method directly.

Instead of trying to call the Listener, why not just use a separate method?
ItemListener listener = new ItemListener() {
public void itemStateChanged(ItemEvent e) {
method();
}
};
public void method() {
//code you want to run
}
Then just call method() when you want to run the code separate from the Listener.

Related

Javafx adding ActionListener to button

button.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent e) {
label.setText("Accepted");
}
});
In the code above we are defining what will happen when we press the button. This is all good but I wanna create new ActionListener and then add it to my button.
Normally in JButton I can just add ActionListener like this:
button.addActionListener(someControllerClass.createButtonListener());
In code above createButtonListener() returns ActionListener.
My question is: What is the equivalent of JButton addActionListener ?
If you want to e.g. reuse an EventHandler, define it like described in JavaFX Documentation as:
EventHandler<ActionEvent> buttonHandler = new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
label.setText("Accepted");
event.consume();
}
};
You can now add your defined buttonHandler to the onAction of your button via:
button.setOnAction(buttonHandler);
And citing from the documentation providing the remove option for completeness:
To remove an event handler that was registered by a convenience method, pass null to the convenience method, for example, node1.setOnMouseDragged(null).
Resulting for you in:
button.setOnAction(null)
The documentation furthermore provides some examples how to add handler for specific events - it's a good read.
Just the same approach, but easier with lamda expressions:
button.setOnAction(event -> buttonSaveClicked());
I think this is how I should do. Creating the handler:
public EventHandler<Event> createSolButtonHandler()
{
btnSolHandler = new EventHandler<Event>() {
#Override
public void handle(Event event) {
System.out.println("Pressed!");
biddingHelperFrame.getBtnSag().setVisible(false);
}
};
return btnSolHandler;
}
Adding Handler to button:
btnSol.addEventHandler(MouseEvent.MOUSE_CLICKED, biddingHelperFrameController.createSolButtonHandler());

Is it possible to define a new listener inside a listener?

I have an swt application on eclipse.I want to create a statement like "If x-button is not clicked, do some stuff".
btnPrint.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
//DO STUFF
}
});
I know that I can modify this btnPrint.addSelectionListener(new SelectionAdapter() { part as btnPrint.addSelectionListener(SWT.Close, new SelectionAdapter() {.But, since there are some different processes inside the widgetSelected method, I cannot change it like that.
To be clear, I want to be able to create like if (x-button is not clicked, do some stuff) inside the widgetSelected method without modifying addSelectionListener structure.
Is it possible to add a new listener inside a listener with a different structure?
Or how can I solve this problem?
EDIT:
The updated code is as follows:
btnPrint = new ToolItem(customToolbar, SWT.NONE);
btnPrint.setImage(ResourceManager.getPluginImage(
"com.meta.efatura.view", "icons/actions/print.jpg"));
btnPrint.setText(Messages.get().getValue("Print"));
btnPrint.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
//DO STUFF
}
});

Can I call ActionPerformed method from an Event Handler class for JButton?

I have a JButton titled "select"
In the class that creates that JButton and other classes, I want to use an if condition with ActionPerformed method.
Something like(pseudo-code)
if(_selectListener.actionPerformed(ActionEvent)) { //i.e., if select Button is clicked,
//do something
}
Is this possible?
I want to call this method because I have to handle a situation in which a player should be able to choose something by clicking "select" button, or another "scroll" button, and I want to control it using something similar to a bunch of if statements like the one above.
If it is possible, what is the syntax for it? What is the argument ActionEvent?
Thank you!
The easiest and cleanest way is to add a dedicated, specific action listener to each button. That way, when the actionPerformed() method is called, you're sure that the associated button has been clicked, and don't need to test which button has been clicked:
selectButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// handle click on select button
}
});
scrollButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// handle click on scroll button
}
});
Another way is to use a common ActionListener, and use the getSource() method of ActionEvent to know which component triggered the event. Compare the result with each potential button to determine which is the one that has been clicked:
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == selectButton) {
// handle click on select button
}
else if (e.getSource() == scrollButton) {
// handle click on scroll button
}
}
What is the argument ActionEvent?
The answer is in the documentation. Read it.
no you cant call, if needs boolean expression/value, but this method returns void.

How to know which JCheckBox sent ItemEvent

I have a number of checkboxes in my Swing Project. For each checkbox select/deselect a particular query is to be executed. I know one way of getting the source of checkbox is
public void itemStateChanged(ItemEvent e) {
if(e.getSource=="checkbox object")
{
some code goes here;
}
}
If i have small number of checkboxes than this solution is best but if i have many checkboxes then i have to write lengthy code. Is there a way to find the object of checkbox that causes the event in a single command?
You can get selected checkbox by like this
JCheckBox checkBox1 = new JCheckBox("Check1");
JCheckBox checkBox2 = new JCheckBox("Check2");
checkBox1.setName("Check1");
checkBox2.setName("Check2");
ItemListener listener = new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
JCheckBox check = (JCheckBox)e.getSource();
String name = check.getName();
System.out.println(name);
}
};
checkBox1.addItemListener(listener);
checkBox2.addItemListener(listener);
If you handle checks in some verry uniform way, it may help to put JChekBoxes into HashMap, mapping them into some structure (maybe data source or some processing object) that helps to process the event easier. Amount of code can be further reduced by having a method that creates, adds and registers a checkbox. The general idea would be along the lines
HashMap<JCheckBox, String> urls = new HashMap<JCheckBox, String>();
// Here I use String but can be any complex data structure.
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String url = urls.get(e.getSource());
// Work with the selected URL now
}
};
void buildCheckBoxes() {
register("http://wikipedia.org");
register("http://stackoverflow.com");
// and 101 others, or load the list from the file.
}
void register(String url) {
JCheckBox box = new JCheckBox("Use "+url);
urls.put(box, url);
box.addActionListener(listener);
// One listener for all, defined above
myPanel.add(box);
// Some panel probably with GridLayout
}
From the other side, if your actions are very different, it may also be better to have a separate listener (probably inner or anonymous class) for each different action:
JCheckBox boxA = new JCheckBox("A");
JCheckBox boxB = new JCheckBox("B");
boxA.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Only code for boxA
}
});
boxB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Only code for boxB
}
});
As soon as there is more code in the listener, you should move it into a method on you main class.
If you want to know which component (either CheckBox or any other Component) has generated an event in java, you can assign name to that component using "setName(name)" method.
// For CheckBox
JCheckBox checkBox1 = new JCheckBox();
checkBox1.setName("CheckBox1");
// Any other Component
JButton button1 = new JButton();
button1.setName("Button1");
Now in listener class you can obtain source object who has generated current event.
// CheckBox Listener
public void itemStateChanged(ItemEvent e)
{
JCheckBox source = (JCheckBox)e.getSource();
if(source.getName().equals("CheckBox1"))
{
//some code goes here;
}
}

Setting a key-binding to perform the same action as in my action listener

I have a JButton that's attached to an ActionListener, but I also wanted to add a shortcut key to the button to be more user-friendly. Say, the user can click the button and the program performs some function "f" or the user can also press "Enter" on the keyboard to perform the same function f. So here's what the gist of my code looks like
private JButton button;
public static void main(String[] args){
Action buttonListener = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
//Perform function f
}
};
button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("ENTER"),
"test");
button.getActionMap().put("test",
buttonListener);
button.addActionListener(new OtherListener());
}
private class OtherListener implements ActionListener{
public void actionPerformed(ActionEvent e){
//Perform function f
}
}
Seems a bit tedious having to add an Action and an ActionListener to do the same thing. Maybe I'm not seeing it, but is there a way to cut the code down so I can eliminate the Action and just use the actionListener? I was thinking switching the buttonListener parameter in the getActionMap().put() method to but the method only takes Action types.
Action extends ActionListener, so you should be able to define a single Action and use it wherever you need an ActionListener.
e.g.
public static void main(String[] args){
Action buttonListener = new Action() {
public void actionPerformed(ActionEvent e) {
//Perform function f
}
};
button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
.put(KeyStroke.getKeyStroke("ENTER"), "test");
button.getActionMap().put("test", buttonListener);
button.addActionListener(buttonListener);
}
JRootPane has a method setDefaultButton(...) that will do what you want. You will need to get the root pane from the top-level container, then you can call this method passing a reference to your JButton, and it will perform its action when enter is pressed on the GUI. And this makes sense when you think about it as "enter" is a special key, one whose behavior should be the responsibility of the GUI, not a single button.

Categories

Resources