How to position a component near the Windows clock?

2

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

frame.setLocationRelativeTo(null);

But how do I display the component on top of the Windows clock regardless of screen size?

In my case my code looks 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 from my IDE.

    
asked by anonymous 28.03.2015 / 13:28

1 answer

2

Using the setLocation(int x, int y) method of your JFrame . I think your question is really how to get those two values to then position the component.

Using an GraphicsDevice object you can 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);
        });
    }
}

    
28.03.2015 / 14:52