通过课程创建按钮

时间:2016-08-24 06:39:55

标签: java swing class jbutton

我是Java新手并尝试通过我的类创建一个按钮,它有一个带参数的方法。但是当我创建我的类的两个实例时,它只显示一个按钮,即最新的按钮。你能告诉我我在这里做了什么错误吗?

我的班级文件

public class CreateButton {
    int posx;
    int posy;
    int buttonWidth;
    int buttonHeight;
    public void newButton(int x, int y, int w, int h) {
        posx = x;
        posy = y;
        buttonWidth = w;
        buttonHeight = h;
        JFrame f = new JFrame();
        JButton b = new JButton("Test");
        b.setBounds(posx, posy, buttonWidth, buttonHeight);

        f.add(b);
        f.setSize(400, 400);
        f.setLayout(null);
        f.setVisible(true);

        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

我的档案

class Project {
    public static void main(String[] args) {
        CreateButton myButton1 = new CreateButton();
        CreateButton myButton2 = new CreateButton();
        myButton1.newButton(50, 200, 100, 50);
        myButton2.newButton(100, 250, 100, 50);
    }
}

1 个答案:

答案 0 :(得分:0)

实际上,您的代码会创建两个按钮,但JFrame窗口彼此相对,因此您只能看到一个。移动窗口,您可以看到两个按钮。

要将按钮添加到同一帧,您需要从JFrame方法中删除createButton()的创建,并将其作为参数添加到该函数中。在main()方法中创建框架。

正如其他人已经评论过的那样,这个类的名称有些“非标准”。如果您打算在那里创建其他小部件,则更好的名称是ButtonFactoryUIFactory。无论如何,请考虑createButton()方法返回初始化按钮,而不是将其添加到JFrame。这样您就可以获得灵活性,并且可以更轻松地在单元测试中测试创建的按钮参数。如果按钮自动添加到框架中,则实现起来要复杂得多。

import javax.swing.*;

public class CreateButton {


    public static class UIFactory {

        public JButton newButton(int posx, int posy, int buttonWidth, int buttonHeight) {
            JButton b = new JButton("Test");
            b.setBounds(posx, posy, buttonWidth, buttonHeight);

            return b;
        }

        public JFrame newFrame(int width, int height) {
            JFrame f = new JFrame();
            f.setSize(width, height);
            f.setLayout(null);

            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            return f;
        }

        public JFrame mainWindow() {
            JFrame f = newFrame(400, 400);
            f.add(newButton(50, 200, 100, 50));
            f.add(newButton(100, 250, 100, 50));
            return f;
        }
    }

    public static void main(String[] args) {
        UIFactory ui = new UIFactory();
        JFrame main  = ui.mainWindow();
        main.setVisible(true);

        JFrame win2 = ui.newFrame(150, 150);
        win2.setLocation(400, 400);
        JButton b2;
        win2.add(b2 = ui.newButton(50, 50, 100, 50));
        b2.addActionListener( e -> win2.setVisible(false) );
        win2.setVisible(true);
    }
}