通过类创建按钮
问题描述:
我是新来的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);
}
}
答
其实,你的代码创建两个按钮,但JFrame
窗口高于对方,所以你可以看到只有一个。移动窗口,你可以看到两个按钮。
要将按钮添加到同一个框架,您需要从createButton()
方法中删除JFrame
的创建,并将其作为参数添加到函数中。在您的main()
-方法中创建框架。
正如其他人已经评论,类的名称有点“非标准”。如果您打算在那里创建其他小部件,则更好的名称是ButtonFactory
或UIFactory
。无论如何,考虑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);
}
}
看起来像一个类的奇怪名称,不仅创建一个按钮,而且还创建一个框架。为什么不只是创建一个按钮? – ChiefTwoPencils
一般而言,如果您为班级选择的名称是一个动词短语,那么您的设计必须有缺陷(或您的名字,或者您对所做事情的理解)。方法应该是“动词”。类应该是“对象”。无论如何,你的按钮都是在它自己的框架中创建的。当你关闭那个框架时,你没有看到它后面的另一个按钮的框架? – RealSkeptic
是的,我明白了。谢谢 – Rajesh