How to display Java Swing window on top of dock bar in macOS?

Viewed 191

My code is like this:

import javax.swing.*;
import java.awt.*;

/**
 * @author recluse
 * @since 2020/10/2
 */
public class Test {
    public static void main(String[] args) {
        JFrame f = new JFrame();
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

        f.setUndecorated(true);
        f.setAlwaysOnTop(true);
        f.setSize(screenSize.width, screenSize.height/3);
        f.setLocation(0, screenSize.height - f.getHeight());
        f.setVisible(true);
    }
}

The effect is like this: enter image description here

The dock always display on the top. But I want the JFrame window display on the top of dock. Could anyone give me some advice?

Btw, if I dont set this JFrame undecorated, the JFrame will not be able to set location under the dock(you can try if possible). I want to know why the JFrame can be put under dock when undecorated set.

1 Answers

Sorry this answer is way too long :|
For relocation and readjustments use this code, its a small code from netbeans GUI JFrame drag and drop feature:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author hp
 */
public class NewJFrame extends javax.swing.JFrame {

    /**
     * Creates new form NewJFrame
     */
    public NewJFrame() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    // End of variables declaration                   
}

Use this Class for Frame Draggign in your code:

class FrameDragListener extends MouseAdapter {

    private final JFrame frame;
    private Point mouseDownCompCoords = null;

    public FrameDragListener(JFrame frame) {
        this.frame = frame;
    }

    public void mouseReleased(MouseEvent e) {
        mouseDownCompCoords = null;
    }

    public void mousePressed(MouseEvent e) {
        mouseDownCompCoords = e.getPoint();
    }

    public void mouseDragged(MouseEvent e) {
        Point currCoords = e.getLocationOnScreen();
        frame.setLocation(currCoords.x - mouseDownCompCoords.x, currCoords.y - mouseDownCompCoords.y);
    }
}

also you can create your own titleBar if you want, it will be much cooler. Contact me if you need more info.

This is the code from a class, hope u find something good from it :)

/==========================================> MAIN J-FRAME <========

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setBounds(450, 200, 500, 400);
        this.setUndecorated(true);
        setShape(new RoundRectangle2D.Double(0, 0, 500, 400, 30, 30));
        setLayout(null);

//==========================================> J-PANEL TITLE BAR <=========

        titleBar.setBounds(0, 0, 500, 50);
        titleBar.setBackground(new Color(171, 183, 183));
        titleBar.setLayout(null);

        FrameDragListener frameDragListener = new FrameDragListener(this);
        super.addMouseListener(frameDragListener);
        super.addMouseMotionListener(frameDragListener);

//==========================================> J-PANEL MAIN ICON <=======

        this.icon = new ImageIcon("Icons/Cash_Book_Icon.png");
        setIconImage(icon.getImage());

        img = this.icon.getImage();
        img = img.getScaledInstance(60,60,Image.SCALE_SMOOTH);
        this.icon = new ImageIcon(img);

        JLabel mainIcon = new JLabel(this.icon);
        mainIcon.setBounds(10,-5,60,60);
        mainIcon.setLayout(null);

//==========================================> J-PANEL MAIN BODY <=====

        mainBody.setBounds(0, 50, 500, 350);
        mainBody.setBackground(new Color(52, 73, 94));
        mainBody.setLayout(null);

//==========================================> TITLE LABEL <=======

        titleLabel = new JLabel("Cash Book - Log In Menu");
        titleLabel.setBounds(115, 13, 350, 30);
        titleLabel.setForeground(new Color(46, 46, 49));
        titleLabel.setFont(new Font("Arial", Font.BOLD, 23));

//==========================================> CLOSE LABEL <=======

        btn_Close = new JButton("X");
        btn_Close.setBounds(465, 13, 30, 30);
        btn_Close.setBackground(new Color(242, 38, 19));
        btn_Close.setForeground(new Color(0, 0, 0));
        btn_Close.setBorder(BorderFactory.createEmptyBorder(0,0,0,0));
        btn_Close.setToolTipText("Close");
        btn_Close.setFont(font);
        btn_Close.setFocusPainted(false);
        btn_Close.addActionListener(this);

//==========================================> MINUS LABEL <=========

        btn_Mini = new JButton("-");
        btn_Mini.setBounds(435, 13, 30, 30);
        btn_Mini.setBackground(new Color(255, 255, 255));
        btn_Mini.setForeground(new Color(0, 0, 0));
        btn_Mini.setBorder(BorderFactory.createEmptyBorder(0,0,0,0));
        btn_Mini.setToolTipText("Close");
        btn_Mini.setFont(font);
        btn_Mini.setFocusPainted(false);
        btn_Mini.addActionListener(this);

//==========================================> MAIN LABEL <=========

        mainLabel = new JLabel("Log In");
        mainLabel.setBounds(200, 35, 300, 50);
        mainLabel.setForeground(new Color(243, 241, 239));
        mainLabel.setFont(new Font("Arial", Font.BOLD, 32));

//==========================================> ADDING FUNCTIONALITIES <=========
    
        titleBar.add(titleLabel);
        titleBar.add(mainIcon);
        titleBar.add(btn_Close);
        titleBar.add(btn_Mini);

        mainBody.add(mainLabel);

        add(titleBar);
        add(mainBody);
Related