从此

Java 桌面开发 - Swing、AWT、JNA、FFM 客户端技术

综述

主要

JOptionPane.showMessageDialog(null, "对话框文字");

单项输入:JOptionPane.showInputDialog("请输入:", ip);
多项单选:(不支持编辑)
  String[] choices = {"多选1", "2", "3"};
  String rv = (String) JOptionPane.showInputDialog(null, "请选择:", "标题",
    JOptionPane.QUESTION_MESSAGE, null, choices, choices[0]);
多项单选:(支持编辑)
    String[] s = {"127.0.0.1", "::1", "240e::1"};
    var cb = new JComboBox(s); cb.setEditable(true);
    int rv = JOptionPane.showConfirmDialog(null, cb, "输入或选择", JOptionPane.OK_CANCEL_OPTION);
    if (rv == JOptionPane.OK_OPTION) { System.out.println(cb.getSelectedItem()); }
传入控件: new JPanel() 入参 Object message 处于上半部分区域,Object[] options 处于下部分。


JEditorPane:
  // 清空内容:
  jEditorPane.setText(""); // 会残留一些样式,想彻底清空可用下行:
  jEditorPane.setDocument(jEditorPane.getEditorKit().createDefaultDocument());

  // 滚动至底部:
  jEditorPane.setCaretPosition(jEditorPane.getDocument().getLength());



关闭所有extends WindowAdapter覆写了windowClosing方法的窗口:
        var we = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
        Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(we);
JDK FFM(Foreign Function & Memory API)取代JNA和JNI之系统调用C库实例(JDK22正式支持):
  说明 - OSHI 通过 JNA 查询 WMI/CIM,但似乎所有数组字段(SAFEARRAY)均返回 null,Powershell 里则能正常输出。

  // 或直接用 oshi-core-java25 库的 oshi.util.platform.windows.RegistryUtil或Advapi32UtilFFM.registryGetString(...)
  // SymbolLookup.libraryLookup("kernel32.dll", Arena.ofAuto());
  var nl = Linker.nativeLinker();
  var mh = nl.downcallHandle(nl.defaultLookup().find("_getpid").get(),
    FunctionDescriptor.of(JAVA_INT)); //or FunctionDescriptor.ofVoid(...)
  // mh.invokeExact(Arena.openConfined().allocateUtf8String("x"));
  var r = (int) mh.invokeExact(); System.out.println(r);

  纯Java获取Process ID (PID):ProcessHandle.current().pid();
  
  如果库文件规模过大,可采用jextract方式生成Java待调用的胶水代码:
    jextract 抽取C库头文件生成 Foreign Function & Memory API 绑定类

  库主要分为两类:静态库和动态库(共享库)。
   1. windows中静态库是以 .lib 为后缀的文件,动态库是以 .dll 为后缀的文件。
   2. linux中静态库是以 .a 为后缀的文件,动态库是以 .so为后缀的文件。
   3. mac中静态库是以.a为后缀的文件,动态库是以.dylib为后缀的文件。


其他

Windows任务栏缩略图的关闭按钮,点击后若有弹框阻止关闭会发红闪动,但不会toFront()至前台,所有程序均如此(HeidiSQL、NetBeans等):formWindowClosing(WindowEvent evt){ }