1

我创建了一个 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"
4

1 回答 1

1

JToolbar 的默认布局是 BoxLayout。如果 JMenu 作为 JToolbar 中的一项,这会由于 BoxLayout 而消失。
您需要手动设置布局和管理边距,这将解决您的问题。我在您的代码中添加了以下行,它可以工作,但在按钮之间放置了一些边距。

tb.setLayout (new FlowLayout());

您可以在此处阅读有关 JToolbar的更多信息

于 2021-10-06T12:05:36.430 回答