Java/Swing GUI 最佳实践(从代码角度)

发布于 2024-10-27 21:21:45 字数 1459 浏览 2 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

苍景流年 2024-11-03 21:21:45

由于关于什么是“最佳实践”似乎存在一些争论,我将向您提供我发现的最适合我的内容以及我的推理:

1.
每个窗口都应该扩展 JFrame 或 JDialog(取决于窗口的类型)。这使得控制窗口的属性变得很容易,而无需每次都指定特定的对象。不过,这更属于一般情况,因为众所周知,我会同时采用这两种方法。

2.
main() 方法应该位于单独的类中。这增加了能够在其他地方使用窗口类的可能性,因为它们不依赖于特定的实现。从技术上讲,这没有什么区别,但应用程序启动代码不属于窗口。

3.
侦听器应该位于匿名内部类中。您的顶级类不应实现任何侦听器。这可以防止黑客从除侦听器所附加的对象之外的任何地方调用侦听器方法。

这是一个带有单个框架的简单应用程序来演示这些实践:

public class Main {
    public static void main(String[] args) {
        final String text = args[0];
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                final MyWindow wnd = new MyWindow(text);
                wnd.setVisible(true);
            }
        });
    }
}

public class MyWindow extends JFrame {
    public MyWindow(String text) {
        super("My Window");

        setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                MyWindow.this.setVisible(false);
                MyWindow.this.dispose();
            }
        });

        final JButton btn = new JButton(text);
        btn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(MyWindow.this, "Button Pressed", "Hey", JOptionPane.INFORMATION_MESSAGE);
            }
        });

        setLayout(new FlowLayout());
        add(btn);
        pack();
    }
}

Since there seems to be some argument about what constitutes "best practices", I'll give you what I have found works best for me, and my reasoning:

1.
Each window should extend either JFrame or JDialog (depending on the type of window). This makes it easy to control the properties of the window without specifying a specific object every time. This is more of the general case, though, as I have been known to do it both ways.

2.
The main() method should be in a separate class. This increases the likelihood of being able to use your window classes elsewhere, as they are not tied to specific implementations. Technically it doesn't make a difference, but application startup code just doesn't belong in a window.

3.
Listeners should be in anonymous inner classes. Your top-level class should not implement any listeners. This prevents hacks like calling the listener methods from anywhere except the object to which they are attached.

Here is a simple application with a single frame to demonstrate these practices:

public class Main {
    public static void main(String[] args) {
        final String text = args[0];
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                final MyWindow wnd = new MyWindow(text);
                wnd.setVisible(true);
            }
        });
    }
}

public class MyWindow extends JFrame {
    public MyWindow(String text) {
        super("My Window");

        setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                MyWindow.this.setVisible(false);
                MyWindow.this.dispose();
            }
        });

        final JButton btn = new JButton(text);
        btn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(MyWindow.this, "Button Pressed", "Hey", JOptionPane.INFORMATION_MESSAGE);
            }
        });

        setLayout(new FlowLayout());
        add(btn);
        pack();
    }
}
最后的乘客 2024-11-03 21:21:45

我同意乔纳森的所有观点

  1. 每个窗口都应该扩展 JFrame 或 JDialog...

  2. main() 方法应该位于单独的类中...

  3. 侦听器应该位于匿名内部类中...

我还想添加以下内容:

  1. 明智地使用 GridBagLayout (GBL)。 GBL 是一个功能强大的布局管理器,虽然很难学习,但功能相当强大。

  2. 考虑对所有 UI 进行手动编码。我个人不喜欢可视化编辑器生成的代码。但是,话虽如此,我已经好几年(2000 年左右)没有使用过可视化编辑器了。在这一点上他们可能会更好。

  3. 明智地使用 JPanel。查看您的 ui 并确定哪些组件应在屏幕尺寸更改时表现相同,然后将这些组件组合到 JPanel 上。考虑在 JPanel 内部使用 JPanel 以获得正确的大小调整行为。

我通常会采用与 Jonathan 稍有不同的方法来让我的组件处理事件,但我相信他的方法比我的更干净一些。

另外,认真研究 MVC 和分层架构的使用。确实最好不要将 UI 和业务逻辑混合在一起。

I agree with all of Jonathan's points.

  1. Each window should extend either JFrame or JDialog...

  2. The main() method should be in a separate class...

  3. Listeners should be in anonymous inner classes...

I would also like to add the following:

  1. Use GridBagLayout (GBL) judiciously. GBL is a powerful Layout Manager, difficult to learn, but quite powerful.

  2. Consider hand coding all your UI. I'm personally not a fan of the code that is produced by visual editors. But, with that said I have not used a visual editor in several years (2000ish). They might be better at this point.

  3. Use JPanels judiciously. Look at your ui and determine which components should behave the same as the screen size changes and then group those components together on a JPanel. Consider using JPanels inside of JPanels to get your correct resizing behavior.

I normally take a slightly different approach on having my components handle events then Jonathan does, but I believe his approach is a bit cleaner then mine.

Also, really study the use of MVC and Layered Architecture. It is truly best not to be mixing UI and Business Logic together.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文