如何将此JFrame设置为屏幕顶部?

时间:2013-11-16 13:16:33

标签: java swing user-interface location jframe

我一直试图将JFrame设置到屏幕顶部很长一段时间。我已经使用了setLocation(),setBounds()和其他一些方法无济于事。我想要的是一个阻止屏幕顶部栏的矩形(最小化和退出按钮的位置)。这是我的代码,我很感激任何帮助!

import java.awt.GridBagLayout;
import javax.swing.JOptionPane;
import javax.swing.WindowConstants;
import javax.swing.SwingUtilities;

public class Annoy2 extends javax.swing.JFrame {
    private int width;
    private int height;
    private boolean t = true;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                Annoy2 inst = new Annoy2();
                inst.setLocationRelativeTo(null);
                inst.setVisible(true);
            }
        });
    }

    public Annoy2() {
        super();
        getDimensions();
        initGUI();
    }

    private void initGUI() {
        try {
            GridBagLayout thisLayout = new GridBagLayout();
            setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            getContentPane().setLayout(null);
            {
            }
            setUndecorated(t);
            setAlwaysOnTop(true);
            this.setResizable(false);
            pack();
            setSize(width, height);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getDimensions() {
        width = Integer.parseInt(JOptionPane.showInputDialog(null, "Width: ", Math.round(java.awt.Toolkit.getDefaultToolkit().getScreenSize().getWidth())));
        height = Integer.parseInt(JOptionPane.showInputDialog(null, "Height: ", 30));
    }

}

2 个答案:

答案 0 :(得分:1)

删除inst.setLocationRelativeTo(null);,这会导致您的窗口在屏幕上居中。

要将窗口置于屏幕顶部,请使用setBounds()(在initGUI()中:

setBounds(0, 0, width, height);

您不必为JFrame创建子类来实现此目的。

JFrame block = new JFrame();
block.setUndecorated(true);
block.setBounds(0, 0, width, height);
block.setVisible(true);

答案 1 :(得分:1)

  

我一直试图将JFrame设置到屏幕顶部很长时间   时间

使用setAlwaysOnTop(true):设置此窗口是否应始终位于其他窗口之上。如果有多个始终在顶部的窗口,则它们的相对顺序是未指定且与平台相关。也就是说,如果某个其他窗口已经始终在顶部,那么这些窗口之间的relative order 未指定(取决于平台)。除了可能是另一个永远在顶部的窗口之外,没有任何窗口可以在总是在顶部的窗口上。

  

我想要的只是一个阻挡屏幕顶部栏的矩形(其中   最小化和退出按钮是。)

使用setUndecorated(true):只有在帧不可显示时才能调用此方法。也就是说,您需要在JFrame上调用此函数,然后再调用setVisible(true)