Java Swing.从JButton打开一个新的JPanel并使按钮漂亮

 陌北从南_221 发布于 2023-01-12 02:04

我正在尝试构建一个带有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);
    }    



}

编辑:我认为打开一个新的JPanel将是一种方式,而不是一个JFrame.从Jbutton点击这样做的最佳方法是什么?

1 个回答
  • 首先使用不同的布局管理器,FlowLayout或者GridBagLayout可能更好

    JPanel centerPanel = new JPanel(new FlowLayout());
    centerPanel.add(openReportSelection);     
    centerPanel.add(closeButton);    
    

    这些布局将遵循按钮的首选大小

    至于打开另一个窗口,嗯,你已经创建了一个窗口,所以这个过程几乎是一样的.话虽如此,你可以考虑看看多个JFrame的使用:好的还是坏的做法?在你做到远远之前.

    更好的方法可能是使用a JMenuBarJMenuItems作为"开放"和"退出"操作.例如,看看如何使用菜单然后你可以使用a CardLayout在视图之间切换

    从纯粹的设计角度来看(我知道这是唯一的练习,但完美的练习是完美的),我不会扩展任何东西JFrame,而是依赖于构建主要的GUI来JPanel代替.

    这使您可以灵活地决定如何使用这些组件,因为您可以将它们添加到框架,小程序或其他组件中......

    2023-01-12 02:19 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有