Adding Action listener for buttons created by method - button

Ok if i have the following code:
protected void makebutton(String name){
JButton button = new JButton(name);
mypanel.add(button);
}
then:
makebutton("Button1");
makebutton("Button2");
makebutton("Button3");
How can i add ActionListener to them. Which name do I use for ActionListener, tried many combination but no success.

What you could do is make the method return a Button. Thats way you can use the button variable else where in your program. What's happening in your case is that the button is encapsulated. so you can't access from anywhere else in your code. Something like this
private JButton makeButton(String name){
JButton button = new JButton(name);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
// code action to perform
}
});
return button;
}
You can use the method when you declare the button
JButton aButton = makeButton();
panel.add(aButton);
The more reasonable way to do it is just create the buttons without a method.
JButtton button = new JButton("Button");
panel.add(button);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
// code action to perform
}
});
I don't really see the need for a method.
Another option is to create a custom listener class
public class GUI {
JButton button1;
JButton button2;
public GUI(){
button1 = new JButton();
button2 = new JButton();
button1.addActionListner(new ButtonListener());
button2.addActionListner(new ButtonListener());
}
private class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e){
if (e.getSource() == button1){
// do something
} else if (e.getSource() == button2){
// something
}
}
}
}

protected void makebutton(String name){
final String n = name;
JButton button = new JButton(name);
mypanel.add(button);
button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
if(n=="Button1"){
button1ActionListener();
}else if(n=="Button2"){
button2ActionListener();
}
}
});
}
you have to create more methods for every button.
I think peeskillet's second code is the good one.

Related

How do i update a textfield in javafx in loop ?

I have a small javafx application using scene builder which on a button click should read a string from COM port at regular intervals and update in a text field.
But now it only shows the last string if I use a for loop, and nothing if i put the code in infinite loop (That's my temporary requirement).
Can anyone help me so that at each read from COM port the new string is updated in the text field.
Here is the code I used for both the cases :
Note : In both cases in controller class, I'm getting perfect output on console.
public class Main extends Application
{
#Override
public void start(Stage primaryStage)
{
try
{
Parent root = FXMLLoader.load(getClass().getResource("test.fxml"));
Scene scene = new Scene(root);
//scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setTitle("test");
primaryStage.setScene(scene);
primaryStage.show();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
launch(args);
}
}
Here is the Controller class :
// In this case it shows only the last string in the text field.
public class Controller implements Initializable
{
#FXML
private Button sayHelloButton;
#FXML
private TextField helloField;
#Override
public void initialize(URL arg0, ResourceBundle arg1)
{
}
#FXML
public void printHello(ActionEvent event)
{
if(event.getSource() == sayHelloButton)
{
SerialPort serialPort = new SerialPort("COM22");
for(int i=0;i<5;i++)
{
try
{
if(!serialPort.isOpened())
{
serialPort.openPort();
serialPort.setParams(9600, 8, 1, 0);
}
String str = serialPort.readString(10,3000);
System.out.println(str);
helloField.clear();
helloField.setText(str);
}
catch(Exception e)
{
helloField.setText(e.toString());
}
}
}
}
}
Here is the method with infinite loop :
//this shows nothing in the text field
#FXML
public void printHello(ActionEvent event)
{
if(event.getSource() == sayHelloButton)
{
SerialPort serialPort = new SerialPort("COM22");
while(true)
{
try
{
if(!serialPort.isOpened())
{
serialPort.openPort();
serialPort.setParams(9600, 8, 1, 0);
}
String str = serialPort.readString(10,3000);
System.out.println(str);
helloField.clear();
helloField.setText(str);
}
catch(Exception e)
{
helloField.setText(e.toString());
}
}
}
}
There are a couple things happening here. In your first example, you state that the console output is correct but the TextField only shows the last result.
This is expected if the loop executes quickly. The TextField is being updated, but it happens so quickly that you can't see it until the loop ends and the last result is still being displayed. Even if you have a delay built into the loop, this could still block the UI from being updated until the loop is completed.
With your infinite loop, the issue is that the loop is being run on the JavaFX Application Thread (JFXAT). This blocks any updates to the GUI until the loop is finished, which is never is.
You will need to move the infinite loop to a new background thread. From there, you can update the GUI using the Platform.runLater() method.
SerialPort serialPort = new SerialPort("COM22");
new Thread(() -> {
while(true)
{
try
{
if(!serialPort.isOpened())
{
serialPort.openPort();
serialPort.setParams(9600, 8, 1, 0);
}
String str = serialPort.readString(10,3000);
System.out.println(str);
// Update the UI on the JavaFX Application Thread
Platform.runLater(() -> {
helloField.clear();
helloField.setText(str);
});
}
catch(Exception e)
{
Platform.runLater(() -> helloField.setText(e.toString()));
}
}
}).start();
This allows your UI to continually update as the background thread sends it new information.

how to use again an actionEvent in Other textField in javafx

I have a log in form that i was creating and i want the TextField ActionEvent to be used also in the Button but I don't know what to do. In Swing I've seen it that it can recycle an ActionEvent and use it in other like TextField but i don't know how to do it in JavaFX.
Here is a code for my TextField with an ActionEvent
and I want to apply this also to my Button so I dont have to create another method with just the same function but different Component. Thanks
passField.setOnKeyPressed(new EventHandler<KeyEvent>()
{
#Override
public void handle(KeyEvent e)
{
if(e.getCode().equals(KeyCode.ENTER))
{
if(admin.equals(userField.getText()) && password.equals(passField.getText()))
{
textInfo.setText("WELCOME " + passField.getText());
textInfo.setTextFill(Color.BLACK);
}
else
{
userField.clear();
passField.clear();
textInfo.setText("Incorrect username or password");
textInfo.setTextFill(Color.RED);
}
}
}
});
You will have to find a shared Event that both the Button and the TextField support.
In your example you are attaching a handler for a KeyEvent watching for the ENTER key, which is equivalent to an ActionEvent. luckily the Button supports it too.
Create a shared EventHandler:
final EventHandler<ActionEvent> myHandler = e -> {
if(admin.equals(userField.getText()) && password.equals(passField.getText())) {
textInfo.setText("WELCOME " + passField.getText());
textInfo.setTextFill(Color.BLACK);
}
else {
userField.clear();
passField.clear();
textInfo.setText("Incorrect username or password");
textInfo.setTextFill(Color.RED);
}
}
Which you can now attach twice (or even more often):
button.setOnAction(myHandler);
passField.setOnAction(myHandler);
EDIT
Without lambda expression:
final EventHandler<ActionEvent> myHandler = new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e)
{
if(admin.equals(userField.getText()) && password.equals(passField.getText())) {
textInfo.setText("WELCOME " + passField.getText());
textInfo.setTextFill(Color.BLACK);
}
else {
userField.clear();
passField.clear();
textInfo.setText("Incorrect username or password");
textInfo.setTextFill(Color.RED);
}
}
});

vaadin 7 layout click doesn't work

I've created MainGameTab which extends TabSheet.
In constructor I create layouts and add them as tabs. I wanted to add right click event to the layout
mainLayout.addLayoutClickListener(new LayoutClickListener() {
private static final long serialVersionUID = 1871942396979048283L;
#Override
public void layoutClick(LayoutClickEvent event) {
if (event.getButton() == MouseButton.RIGHT) {
TextQuestUi.getCurrent().addWindow(new CharacterSheet(c));
}
}
});
this.addTab(mainLayout, "Game");
CharacterSheet is a class, that extends Window
public class CharacterSheet extends Window {
But when I click on tab - I've got basic right click items for browser instead of new window.
What's the problem?
My MainGameTab looks like this
public MainGameTab() {
final Player c = new Player();
c.setName("Hero");
c.setLevel(100);
Skill skill = new Skill();
skill.setName("Help from heaven");
skill.setEffect("Full recover health");
c.addSkill(skill);
Stat stat = new Stat();
stat.setName("Attack");
stat.setValue(50);
c.addStat(stat);
HorizontalLayout mainLayout = new HorizontalLayout();
mainLayout.addLayoutClickListener(new LayoutClickListener() {
private static final long serialVersionUID = 1871942396979048283L;
#Override
public void layoutClick(LayoutClickEvent event) {
if (event.getButton() == MouseButton.RIGHT) {
TextQuestUi.getCurrent().addWindow(new CharacterSheet(c));
}
}
});
this.addTab(mainLayout, "Game");
HorizontalLayout logLayout = new HorizontalLayout();
this.addTab(logLayout, "Log");
}
And I add it in UI
#Override
protected void init(VaadinRequest request) {
this.setContent(new MainGameTab());
}
I'll suggest you to use one of the existing Vaadin addons. See here
Or, I am assuming that you're probably looking for getButton() in ItemClickEvent - something like this:
t.addListener(new ItemClickListener() {
public void itemClick(ItemClickEvent event) {
if (event.getButton()==ItemClickEvent.BUTTON_RIGHT) {
// Right mouse button clicked, do greatThings!
}
}
});

Change label during button execution

I have a "Connect" button which calls internal logic for network connection
I have this button which starts network connection.
Button connectButton = new Button("Connect");
connectButton.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent e)
{
actiontarget.setText("Successful Connection Test!");
}
});
How I can change the button label during the action execution with label "Cancel"?
And also how I can cancel the action when the button label is "Cancel"? Maybe I need to call specific action when the button label is different?
You could extend your code snippet with the logic below. Haven't tried it but I think it should work, even I would suggest using Injection.
private final String CONNECT = "connect";
private final String DISCONNECT = "disconnect";
Button connectButton = new Button(CONNECT);
connectButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e)
{
if (connectButton.getText().equals(CONNECT)) {
do_something();
actiontarget.setText(DISCONNECT);
} else {
do_something_else();
actiontarget.setText(CONNECT);
}
}
});
Another Idea would be to use a ToggleButton:
In your FXML:
<ToggleButton fx:id="btnConnect" alignment="CENTER" maxHeight="1" maxWidth="1" onAction="#actionClickedConnectBtn" text="connect"/>
In your Code:
#FXML
public void actionClickedConnectBtn(ActionEvent event) {
if (btnConnectGpsd.isSelected()) {
do_something();
} else {
do_something_else();
}
}
You can use a Boolean flag to indicate which action to execute when the button is clicked; if the flag is true, then execute your cancel action and set the flag to false, setting your button's text to "Connect". If the flag is instead false, execute your connection action and set the flag to true, setting your button's text to "Cancel".

AspectJ capture button clicked

I want to know whether how to capture the button clicked with AspectJ and get its parameter (eg. button name). I think for having more generalized capturing with AspectJ, it shoudl be used MouseListener so it can capture other UI elements in general!
Example:
In a GUI example I have defined 2 buttons that take some actions
public JButton btn1 = new JButton("Test1");
public JButton btn2 = new JButton("Test2");
btn1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//take some actions
}
}
btn2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//take some actions
}
}
How to capture these buttons with AspectJ, and get their parameters (eg. name)?
It is possible. I have provided two examples. The first that prints out for every JButton that has an ActionListener. The other example only prints out if a specific buttons is clicked.
Prints the text for every JButton clicked with an ActionListener:
#Pointcut("execution(* *.actionPerformed(*)) && args(actionEvent)")
public void buttonPointcut(ActionEvent actionEvent) {}
#Before("buttonPointcut(actionEvent)")
public void beforeButtonPointcut(ActionEvent actionEvent) {
if (actionEvent.getSource() instanceof JButton) {
JButton clickedButton = (JButton) actionEvent.getSource();
System.out.println("Button name: " + clickedButton.getText());
}
}
Prints the text for a specific JButton:
public static JButton j1;
#Pointcut("execution(* *.actionPerformed(*)) && args(actionEvent) && if()")
public static boolean button1Pointcut(ActionEvent actionEvent) {
return (actionEvent.getSource() == j1);
}
#Before("button1Pointcut(actionEvent)")
public void beforeButton1Pointcut(ActionEvent actionEvent) {
// logic before the actionPerformed() method is executed for the j1 button..
}
UPDATED:
You can do this in many different ways. For example add your buttons to the aspect directly. But I prefere to use a enum object between (ButtonManager in this case), so the code does not know about the aspect. And since the ButtonManager is an enum object, it is easy for the aspect to retrieve values from it.
I just tested it with a Swing button class from Oracle and it works. In the Swing class:
b1 = new JButton("Disable middle button", leftButtonIcon);
ButtonManager.addJButton(b1);
AspectJ is extremely powerful when it comes to manipulating classes, but it can not weave advises into specific objects since objects is not created at the time of weaving. So you can only work with objects at runtime and that is why I have added the addJButton(..) method above. That enables the aspect to check the advised button against a list of registered buttons.
The ButtonManager class:
public enum ButtonManager {
;
private static Collection<JButton> buttonList = new LinkedList<JButton>();
public static void addJButton(JButton jButton) {
buttonList.add(jButton);
}
public static Collection<JButton> getButtonList() {
return buttonList;
}
}
Modified pointcut and advice to only print the name of the buttons registered in the ButtonManager:
#Pointcut("execution(* *.actionPerformed(*)) && args(actionEvent) && if()")
public static boolean buttonListPointcut(ActionEvent actionEvent) {
Collection<JButton> buttonList = ButtonManager.getButtonList();
JButton registeredButton = null;
for (JButton jButton : buttonList) {
if (actionEvent.getSource() == jButton) {
registeredButton = jButton;
}
}
return registeredButton != null;
}
#Before("buttonListPointcut(actionEvent)")
public void beforeButtonListPointcut(ActionEvent actionEvent) {
JButton clickedButton = (JButton) actionEvent.getSource();
System.out.println("Registered button name: " + clickedButton.getText());
}
UPDATED 2
Okay, I believe I understand what you want. You want to listen to mouse events. That is possible. The downside is that you have to register all your GUI components that you want to listen for clicks with a mouse listener. It is not enough to register the JPanel of the JFrame with a MouseListener. So if you only have registered an ActionListener for your buttons, you also have to add a mouse listener.
I have created a quick solution that works for me. It only shows that it works. I have not tried to make the solution generic with many different GUI objects. But that should be quite easy to refactor in when you have got the basics to work.
In the Swing class:
private class MouseListener extends MouseInputAdapter {
public void mouseClicked(MouseEvent e) {}
}
In the init method of the Swing class:
MouseListener myListener = new MouseListener();
btn1.addMouseListener(myListener);
btn2.addMouseListener(myListener);
In the Aspect class:
#Pointcut("execution(* *.mouseClicked(*)) && args(mouseEvent)")
public void mouseEventPointcut(MouseEvent mouseEvent) {}
#Before("mouseEventPointcut(mouseEvent)")
public void beforeMouseEventPointcut(MouseEvent mouseEvent) {
if (mouseEvent.getSource() instanceof JButton) {
JButton clickedButton = (JButton) mouseEvent.getSource();
System.out.println("aspectJ --> mouseClicked: " + clickedButton.getText());
}
}
This results in the following output in the console:
aspectJ --> mouseClicked: Test1
I hope it helps!

Resources