Spl*_*unk 2 java user-interface swing netbeans jpanel
我正在尝试构建一个带有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;
}
}
Run Code Online (Sandbox Code Playgroud)
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);
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:我认为打开一个新的JPanel将是一种方式,而不是一个JFrame.从Jbutton点击这样做的最佳方法是什么?
Mad*_*mer 10
首先使用不同的布局管理器,FlowLayout
或者GridBagLayout
可能更好
JPanel centerPanel = new JPanel(new FlowLayout());
centerPanel.add(openReportSelection);
centerPanel.add(closeButton);
Run Code Online (Sandbox Code Playgroud)
这些布局将遵循按钮的首选大小
至于打开另一个窗口,嗯,你已经创建了一个窗口,所以这个过程几乎是一样的.话虽如此,你可以考虑看看多个JFrame的使用:好的还是坏的做法?在你做到远远之前.
更好的方法可能是使用a JMenuBar
和JMenuItem
s作为"开放"和"退出"操作.例如,看看如何使用菜单然后你可以使用a CardLayout
在视图之间切换
从纯粹的设计角度来看(我知道这是唯一的练习,但完美的练习是完美的),我不会扩展任何东西JFrame
,而是依赖于构建主要的GUI来JPanel
代替.
这使您可以灵活地决定如何使用这些组件,因为您可以将它们添加到框架,小程序或其他组件中......
归档时间: |
|
查看次数: |
35927 次 |
最近记录: |