我正在尝试构建一个带有2个按钮的主GUI的小程序 . 一个按钮关闭程序,另一个按钮我打开一个新的JPanel,它将有文本字段等 .
我希望能够制作按钮,使它们看起来像普通的应用程序按钮,我想,漂亮和正方形,相同的大小等等,我不知道如何做到这一点 .
另外,我不确定如何通过按钮单击打开新的JFrame .
GUI代码:
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);
}
}
EDIT: I think opening a new JPanel would be the way to go rather than a JFrame. What would be the best way to do this from a Jbutton click?
4 回答
首先使用不同的布局管理器,
FlowLayout
或GridBagLayout
可能会更好这些布局将遵循按钮的首选大小
至于打开另一个窗口,嗯,你已经创建了一个窗口,所以这个过程几乎是一样的 . 话虽如此,你可能会考虑先看看The Use of Multiple JFrames: Good or Bad Practice?,然后才能做到最远 .
更好的方法可能是使用
JMenuBar
和JMenuItem
来充当"open"和"exit"动作 . 例如,看看How to Use Menus然后你可以使用CardLayout在视图之间切换从纯粹的设计角度来看(我知道's only practice, but perfect practice makes perfect), I wouldn' t从
JFrame
扩展任何东西,而是依赖于像JPanel
这样的东西构建你的主GUI .这使您可以灵活地决定如何使用这些组件,因为您可以将它们添加到框架,小程序或其他组件中......
如果您希望按钮具有原生外观(L&F),请将以下内容添加到您的程序中:
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
而不是打开另一个
JFrame
,而是想要使用JDialog
,通常使用模态集 .在Java中,您只能扩展一个类,因此您应该仔细考虑是否适合扩展另一个类 . 你可以问自己,“我实际上是在扩展JFrame的功能吗?”如果答案为否,那么您实际上想要使用实例变量 .
以下是上述建议的示例程序:
我不确定你的问题是什么,你想做什么 . 是否要打开新的JFrame,或者是否要将JPanel添加到现有框架中 .
要使用按钮打开新的JFrame,请在按钮的actionPerformed方法中创建JFrame的实例 . 在你的情况下,它看起来类似于:
你可能正在寻找创建和打开一个新的JFrame . 为此,首先需要从JFrame类实例化一个对象 . 举个例子,让我们实例化一个具有特定边界的新JFrame .
然后你需要创建像JButtons,Jlabels等组件,然后你应该将它们添加到你的新testFrame对象 .
例如,让我们创建一个Jlabel并添加它testFrame:
现在让我们假设您有一个名为“jbutton”的Jbutton,通过单击它,将创建一个新的JFrame对象,并将Jlabel组件添加到它: