I'm trying to create a custom component in NetBeans which contains 2 buttons on a panel.
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JPanel;
public class CustomComponent extends JPanel {
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
public CustomComponent() {
setLayout(new FlowLayout());
add(button1);
add(button2);
button1.setSize(100, 30);
button2.setSize(100, 30);
}
}
When I use this custom component on another project's JFrame (using GUI designer), those two buttons need to have two different ActionPerformed
events and those events must be shown in the Netbean's event list. is that possible to do?
(Currently, I only see the events owned by the JPanel.)
Thanks in advance
CodePudding user response:
As per the links above, you can add an action listener like below. This example is for a generic ActionEvent
, but you can modify the code to other types of events as well:
//The button to add an event to
JButton test = new JButton();
//The first option
test.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println("Action performed");
}
});
//The second option. This only works on Java 8 and newer
test.addActionListener((ActionEvent e) ->
{
System.out.println("Action performed");
});
//Or a simplified form for a single call
test.addActionListener(e -> System.out.println("Action performed"));
And a working example in your case:
public CustomComponent() {
setLayout(new FlowLayout());
add(button1);
add(button2);
button1.setSize(100, 30);
button2.setSize(100, 30);
//Add events
button1.addActionListener(e -> System.out.println("Button 1 action performed"));
button2.addActionListener(e -> System.out.println("Button 2 action performed"));
}
CodePudding user response:
instead of passing listeners through the constructor, I have created another setter, because the GUI does not support that.
public void setListners(ActionListener btn1ActionListner, ActionListener btn2ActionListner){
button1.addActionListener(btn1ActionListner);
button2.addActionListener(btn2ActionListner);
}
on the other project
public NewJFrame() {
initComponents();
ActionListener al1 = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Button 1");
}
};
ActionListener al2 = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Button 2");
}
};
customComponent1.setListners(al1, al2);
}