How to position a component next to the Windows clock?

Asked

Viewed 128 times

2

I learned that to center a component in the center of the screen just use:

frame.setLocationRelativeTo(null);

But how do I show the component on top of the Windows clock independent of the screen size?

In my case my code is like this:

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {

        public void run() {
            try {
                UIManager.setLookAndFeel("com.jtattoo.plaf.graphite.GraphiteLookAndFeel");
                mainn frame = new mainn();
                frame.setLocationRelativeTo(null);
                frame.setResizable(false);
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

I use the Window Builder of my IDE.

1 answer

2


By the method setLocation(int x, int y) of your JFrame. I believe your doubt is actually how to get these two values to then position the component.

By means of an object GraphicsDevice you get the size x and y of the screen where the application is running.

import java.awt.EventQueue;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import javax.swing.JFrame;

public class MeuJFrame extends JFrame {

    public MeuJFrame(String titulo) {
        super(titulo);
        setSize(400,200);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        GraphicsDevice tela = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
        Rectangle tamanhoTela = tela.getDefaultConfiguration().getBounds();

        /**
         * Tendo o tamanho da tela, basta subtrair:
         * a) A largura da tela -  largura atual do componente
         * b) A altura da tela  -  altura atual do componente
         */
        int posicaoX = (int) tamanhoTela.getMaxX() - this.getWidth();
        int posicaoY = (int) tamanhoTela.getMaxY() - this.getHeight();

        // E então definir a posição do componente
        setLocation(posicaoX, posicaoY);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            new MeuJFrame("StackOverflow").setVisible(true);
        });
    }
}

resultado

  • Solved! I just can’t score. Thank you!

  • Renan. Thank you very much champion!

  • Entnedi. Excuse the ignorance kkk.. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.