通过 class 创建按钮

Creating button through class

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

我的class文件

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);
    }
}

实际上,您的代码创建了两个按钮,但是 JFrame windows 彼此在上方,因此您只能看到一个。移动 window,您会看到两个按钮。

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

正如其他人已经评论的那样,class 的名称有点 "nonstandard"。如果您还打算在那里创建其他小部件,则更好的名称是 ButtonFactoryUIFactory。无论如何,请考虑 createButton() 方法 returns 初始化按钮,而不是为您将其添加到 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);
    }
}