【发布时间】:2022-01-08 04:00:10
【问题描述】:
所以我是 Java Swing GUI 的新手,我正在创建一个学生管理系统。这个想法是,当程序启动时,屏幕上的每个模块都有一个按钮,单击每个按钮会将您带到另一个窗口,其中包含有关模块的信息。我想要一个能够添加和删除模块的功能,所以我的想法是在运行时您可以添加一个代表新模块的新按钮,或者在您想要删除该模块时删除一个按钮。
我尝试了很多不同的方法,但我遇到的最多的问题是我可以很好地创建按钮,但我无法将它添加到框架中。
public class GUI {
// -=GLOBAL VARIABLES=-
public int moduleCount = 0; //Setting the module count to 0, this will increase/decrease as modules are made/deleted. This variable allows the program to determine where to position each button
// -=CREATING MODULE METHOD=-
public void addButton(String name, String text){
//Calculates positioning of each button based on quantity of buttons
moduleCount += 1;
int x = 150 / moduleCount;
int y = 100 / moduleCount;
JButton newButton = new JButton();
newButton.setText(text);
newButton.setBounds(x, y, 100, 40);
newButton.setName(name);
}
public GUI () {
// -=CREATING THE FRAME=-
JFrame frame = new JFrame("Student Management System"); //Creating a new frame
frame.setSize(750, 500);//400 width and 500 height
frame.setLayout(null);//using no layout managers
frame.setVisible(true);//making the frame visible
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
如果这是可能的(即使我走错了方向),任何帮助都将不胜感激:)
编辑:我知道我实际上并没有将按钮添加到框架中,我已经尝试过了。每次我使用
frame.add(newButton);
或先投射 GUI,它只是不将其添加到框架中
【问题讨论】:
-
不要使用空布局。 Swing 旨在与布局管理器一起使用。您的代码的问题是您从不将按钮添加到框架中。您实际上在哪里构建应用程序逻辑?阅读 How to Use Buttons 上的 Swing 教程。它将展示如何创建一个简单的界面。您需要修改代码以添加按钮。
-
我不知道@camickr 是否会同意我的观点,但我认为您需要查看卡片布局(docs.oracle.com/javase/tutorial/uiswing/layout/card.html)并使用此布局管理器切换到(卡片)代表当前模块的正确视图的面板。我认为这个解决方案比基于相同条件从视图中添加和/或删除组件要好。所以基本上,按照它们应该看起来的方式为模块创建面板,然后让布局管理器根据当前模块“洗牌”你的卡片面板。
-
@hfontanez,是的,我同意。您需要一个面板来包含按钮。然后,当您单击按钮时,您使用 CardLayout 交换面板。
-
我建议不要“添加按钮”,而是使用
JList,而是在列表模型中添加新功能作为条目。