如何从单独的类添加按钮到框架?

时间:2014-04-11 19:48:09

标签: java class jbutton

    import javax.swing.JButton;
    import javax.swing.JPanel;


    public class EventButton extends MainLayout{
        //create the string for the button's text 
        private String button_text; 
        private JButton event_button; 
        private JPanel event_panel;



        public EventButton(){
            //initialize the button text
            button_text = "Set Event";
            event_button = new JButton();
            event_panel = new JPanel();
            event_button.setText(button_text);
            event_panel.add(event_button);
            add(event_panel);



        }
}


import javax.swing.JFrame;

public class MainLayout extends JFrame{
    public MainLayout(){
        EventButton eb = new EventButton();
    }
}


import javax.swing.*;
public class Tester {
    public static void main(String[] args){
        MainLayout frame = new MainLayout();
        frame.setSize(300, 300);
        frame.setVisible(true);
    }

}

这是三个单独的类。现在我希望能够将按钮添加到MainLayout框架,但似乎无法弄明白。当我运行这段代码时,我得到一个错误,我尝试了不同的东西,比如在main函数中创建按钮的实例,代码编译但只弹出一个框架。

1 个答案:

答案 0 :(得分:0)

听起来好像没有EventButton扩展MainLayout(这不会起作用,因为它无论如何都会是一个单独的实例),你想要做的是:

// Change the EventButton() constructor:
public EventButton(Container addTo) {
   ...
   addTo.add(event_panel);
}

// Change your MainLayout() constructor:
public MainLayout(){
   EventButton eb = new EventButton(getContentPane());
}