[英]How to get Current JPanel from Button Click
如果單擊按鈕,我將如何獲取它當前的JPanel?
我知道如何創建一個按鈕並添加一個actionlistener並進行事件處理。 我不知道如何選擇當前面板。
修改上述帖子中的代碼以避免使用最終變量
public void buildUI() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton button = new JButton("Button");
panel.add(button);
button.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("The current panel is " + ((JButton)e.getComponent()).getParent());
}
});
frame.add(panel);
frame.pack();
frame.setDefaultCloseBehavior(JFrame.CLOSE_ON_EXIT);
frame.setVisible(true);
}
public void buildUI() {
JFrame frame = new JFrame();
final JPanel panel = new JPanel();
JButton button = new JButton("Button");
panel.add(button);
button.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("The current panel is " + panel);
}
});
frame.add(panel);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
編輯:添加示例,其中偵聽器代碼與GUI代碼不在同一個類中。
//PanelPrintingListener.java
public class PanelPrintingListener implements ActionListener {
private JPanel panel;
public PanelPrintingListener(JPanel panel) {
this.panel = panel;
}
public void actionPerformed(ActionEvent e) {
System.out.println("The current panel is " + panel);
}
}
//OtherFoo.java
public void buildUI() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton button = new JButton("Button");
panel.add(button);
button.addActionListener( new PanelPrintingListener(panel) );
frame.add(panel);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
如果您正在尋找當前處於活動狀態的面板(意味着它是堆棧中的頂部面板),那么您可以使用getComponent()方法。
Component active = parentPanel.getComponent(0);
現在,“活動”對象將具有當前活動或顯示的面板。請注意,“parentPanel”是放置所需子面板的面板。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.