如何使用ActionListener从子对象修改父对象?

时间:2016-05-13 22:12:47

标签: java swing

所以我有一个扩展JFrame的窗口类,我添加了扩展JPanel的GUIPanel对象。当我的ActionListeners按钮位于GUIPanel类时,如何修改Window(例如,单击startbutton的delete面板)。或者我的GUI结构错了?

package view;
import javax.swing.*;
import java.awt.*;

public class Window extends JFrame{
    int a = 10;
    Window() {
        super("Simple Game");
        setLayout(new BorderLayout());
        setSize(600, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }
    public static void main(String[] args) {
        Window window = new Window();
        GUIPanel panel1 = new GUIPanel(new Dimension(600, 350), 0);
        GUIPanel panel2 = new GUIPanel(new Dimension(600, 100), 0);
        GUIPanel panel3 = new GUIPanel(new Dimension(600, 150), 0);
        panel2.addStartButton();
        window.add(panel1, BorderLayout.NORTH);
        window.add(panel2, BorderLayout.CENTER);
        window.add(panel3, BorderLayout.SOUTH);
    }
}


package view;
import javax.swing.*;
import java.awt.*;

class GUIPanel extends JPanel {
    GUIPanel(Dimension dimensions, int layoutIndex) {
        super();
        setPreferredSize(dimensions);
        if(layoutIndex == 0)
            setLayout(new FlowLayout());
        else if(layoutIndex == 1)
            setLayout(new BorderLayout());
    }
    void addStartButton() {
        JButton startButton = new JButton("START");
        startButton.setPreferredSize(new Dimension(300, 60));
        startButton.addActionListener(e -> {
            /* DO THINGS */
        });
        add(startButton);
    }
}

0 个答案:

没有答案