我正在嘗試在 NetBeans 中創建一個自定義組件,它在面板上包含 2 個按鈕。
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);
}
}
當我在另一個專案的 JFrame(使用 GUI 設計器)上使用這個自定義組件時,這兩個按鈕需要有兩個不同的ActionPerformed事件,并且這些事件必須顯示在 Netbean 的事件串列中。那有可能嗎?
(目前,我只看到 JPanel 擁有的事件。)

提前致謝
uj5u.com熱心網友回復:
根據上面的鏈接,您可以添加如下所示的動作偵聽器。此示例適用于通用ActionEvent,但您也可以將代碼修改為其他型別的事件:
//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"));
以及您的案例中的一個作業示例:
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"));
}
uj5u.com熱心網友回復:
我沒有通過建構式傳遞偵聽器,而是創建了另一個 setter,因為 GUI 不支持它。
public void setListners(ActionListener btn1ActionListner, ActionListener btn2ActionListner){
button1.addActionListener(btn1ActionListner);
button2.addActionListener(btn2ActionListner);
}
在另一個專案上
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);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/363966.html
上一篇:打字稿嵌套泛型
