javaswingalignmentjmenu

Java swing menu control not align


I created a swing application which looks fine on 2 laptops with JDK8 but on 3rd laptop, all menu controls going little down. I am attaching image.
I created maven structure where below java file and pom is present. Only these two files. Run either using maven or main method.

Correct and Problem image

Java Code

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>

Command to compile

mvn install

Command to run

mvn exec:java -D"exec.mainClass"="com.sv.test.Test"

Solution

  • Default layout to JToolbar is BoxLayout. In case of JMenu as one of item in JToolbar this goes off due to BoxLayout.
    You need to manually set layout and manage margins which will solve your problem. I add below line to your code and it worked but put some margins between buttons.

    tb.setLayout (new FlowLayout());
    

    You can read more about JToolbar here