北屋教程网

专注编程知识分享,从入门到精通的编程学习平台

Java编写Swing的桌面应用小程序(一)

兴趣爱好,加上一些工作需要,学习一下Java的Swing桌面应用程序的开发。

学习过程笔记一下。

1、构建一个入门的桌面小程序并运行

参考豆包给的源码:

package com.zx.swing.tool;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or
// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter.
public class SwingToolMain {

    private JFrame frame;
    private JTextField textField;
    private JTextArea textArea;

    public SwingToolMain() {
        initialize();
    }

    private void initialize() {
        // 创建主窗口
        frame = new JFrame("Java桌面应用示例");
        frame.setSize(600, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new BorderLayout(0, 0));

        // 创建顶部面板
        JPanel topPanel = new JPanel();
        frame.getContentPane().add(topPanel, BorderLayout.NORTH);

        // 添加标签
        JLabel label = new JLabel("输入文本:");
        topPanel.add(label);

        // 添加文本框
        textField = new JTextField();
        topPanel.add(textField);
        textField.setColumns(30);

        // 添加按钮
        JButton button = new JButton("添加到列表");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String text = textField.getText();
                if (!text.isEmpty()) {
                    textArea.append(text + "\n");
                    textField.setText("");
                }
            }
        });
        topPanel.add(button);

        // 创建中间文本区域
        textArea = new JTextArea();
        textArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(textArea);
        frame.getContentPane().add(scrollPane, BorderLayout.CENTER);

        // 创建底部状态栏
        JLabel statusLabel = new JLabel("就绪");
        frame.getContentPane().add(statusLabel, BorderLayout.SOUTH);
    }

    // java com.zx.swing.tool.SwingToolMain
    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            try {
                SwingToolMain window = new SwingToolMain();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
}

我是idea上生成的,过程如下:




设置Maven



C:\MyProgramFiles\maven\apache-maven-3.9.10
C:\MyProgramFiles\maven\apache-maven-3.9.10\conf\settings.xml
C:\MyProgramFiles\maven\maven_jar


把Main改成SwingToolMain,参考上面的代码黏贴


设置启动:







访问target目录:

C:\Projects\zx\zx-swing-tool\code\zx-swing-tool\target




在target目录下用java运行

有点问题,后续在研究

java com.zx.swing.tool.SwingToolMain
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言