【发布时间】:2021-11-25 22:41:28
【问题描述】:
我创建了一个 Swing 应用程序,它在 2 台装有 JDK8 的笔记本电脑上看起来不错,但在第三台笔记本电脑上,所有菜单控件都几乎没有下降。我正在附上图片。
我创建了 maven 结构,其中存在以下 java 文件和 pom。只有这两个文件。使用 maven 或 main 方法运行。
Java 代码
package com.sv.test;
import javax.swing.*;
import java.awt.*;
public class Test extends JFrame {
public Test() {
JMenuBar mb = new JMenuBar();
JMenu m = new JMenu("*");
mb.add(m);
JToolBar tb = new JToolBar();
tb.setFloatable(false);
tb.setRollover(false);
tb.add(new JTextField(15));
tb.add(new JTextField(15));
tb.add(mb);
JButton exit = new JButton("Exit");
exit.addActionListener(e -> System.exit(0));
tb.add(exit);
tb.setBackground(Color.orange);
getContentPane().add(tb);
pack();
setLocationRelativeTo(null);
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Test();
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sv</groupId>
<artifactId>Test</artifactId>
<version>1.0</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
编译命令
mvn install
运行命令
mvn exec:java -D"exec.mainClass"="com.sv.test.Test"
【问题讨论】:
-
如何重现问题?它依赖于分辨率吗?依赖 LAF?操作系统?
-
笔记本电脑有 JDK1.8.0_251,但我无法在其他笔记本电脑上重现。
-
JMenuBar 添加到 JFrame,而不是 JToolBar。将 setDefaultCloseOperation 方法调用移到 pack 方法调用之上。
-
没有吉尔伯特,检查代码 - tb.add (mb)。另外,我尝试通过移动 pack 方法,但结果保持不变。
-
当@GilbertLeBlanc 写“JMenuBar 被添加到JFrame”时,他的意思是菜单栏应该被添加到框架中。使用
JFrame.setJMenuBar(JMenuBar)来做到这一点。
标签: java swing alignment jmenu