我正在尝试构建一个小程序,它有一个带有 2 个按钮的主 GUI。一个按钮关闭程序,另一个按钮我想打开一个新的 JPanel,其中包含文本字段等。
我希望能够制作按钮,使它们看起来像普通的应用程序按钮,我猜,漂亮且方形,大小相等等等,但我不知道如何做到这一点。
此外,我不确定如何通过单击按钮打开新的 JFrame。
图形用户界面代码:
package practice;
public class UserInterface extends JFrame {
private JButton openReportSelection = new JButton("Open new Window");
private JButton closeButton = new JButton("Close Program");
private JButton getCloseButton() {
return closeButton;
}
private JButton getOpenReportSelection() {
return openReportSelection;
}
public UserInterface() {
mainInterface();
}
private void mainInterface() {
setTitle("Program Information Application");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel centerPanel = new JPanel(new GridLayout(0, 3));
centerPanel.add(openReportSelection);
centerPanel.add(closeButton);
getCloseButton().addActionListener(new Listener());
add(centerPanel, BorderLayout.CENTER);
setSize(1000, 200);
setVisible(true);
}
private void addReportPanel() {
JPanel reportPanel = createNewPanel();
getContentPane().add(reportPanel, BorderLayout.CENTER);
}
private JPanel createNewPanel() {
JPanel localJPanel = new JPanel();
localJPanel.setLayout(new FlowLayout());
return localJPanel;
}
}
ActionListener类代码:
package practice;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Listener implements ActionListener {
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
}
编辑:我认为打开一个新的 JPanel 而不是 JFrame 是更好的选择。单击 Jbutton 来执行此操作的最佳方法是什么?
最佳答案
首先使用不同的布局管理器 FlowLayout
或GridBagLayout
可能效果更好
JPanel centerPanel = new JPanel(new FlowLayout());
centerPanel.add(openReportSelection);
centerPanel.add(closeButton);
这些布局将遵循您的按钮的首选尺寸
至于打开另一个窗口,嗯,您已经创建了一个窗口,因此过程几乎相同。话虽如此,您可能会考虑看看 The Use of Multiple JFrames: Good or Bad Practice?在你做出 promise 之前。
更好的方法可能是使用 JMenuBar
和JMenuItem
s 充当“打开”和“退出” Action 。看看How to Use Menus那么你可以使用 CardLayout
例如,在 View 之间切换
从纯粹的设计角度来看(我知道这只是练习,但熟能生巧),我不会从 JFrame
扩展任何内容。相反,将依赖于围绕 JPanel
之类的内容构建主 GUI相反。
这使您可以灵活地决定如何使用这些组件,因为您可以将它们添加到框架、小程序或其他组件中...
关于Java Swing 。从 JButton 打开一个新的 JPanel 并使按钮变得漂亮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24009159/