Heim  >  Artikel  >  So legen Sie die Position eines JPanels an einer beliebigen Stelle auf dem Bildschirm fest

So legen Sie die Position eines JPanels an einer beliebigen Stelle auf dem Bildschirm fest

WBOY
WBOYnach vorne
2024-02-09 10:40:09607Durchsuche

php小编草莓为您介绍如何设置JPanel在屏幕上任意位置的方法。JPanel是Java Swing中常用的容器组件,通过设置布局管理器和设置组件的位置可以实现对JPanel的定位。首先,我们需要选择合适的布局管理器,如FlowLayout、BorderLayout等。然后,通过设置组件的边界和位置属性,可以将JPanel放置在屏幕的任意位置。这样,就可以轻松实现JPanel的自由定位,提供更灵活的界面设计和交互体验。

问题内容

我需要有许多 JPanel,但我无法将它们放置在我想要的位置,因为当我尝试更改边界等内容时,它们要么会消失。感谢任何帮助

这是我尝试定位的面板的代码。我希望它位于屏幕右侧大约 3/4 的位置,但我无法将其移出右上角

textField = new JTextField("Sample Text");
textField.setPreferredSize(new Dimension(200, 30));
textField.setFont(new Font("Arial", Font.PLAIN, 16));
textField.setEditable(false); // Set to false to make it read-only

JPanel textPanel = new JPanel(new GridBagLayout());
textPanel.add(textField);
add(textPanel, BorderLayout.NORTH);

解决方法

面板(以及所有 Swing)始终需要顶级组件(如 JFrame、JDialog 或 JWindow)才能在屏幕上呈现。即使您将面板绝对定位在顶级容器内(布局管理器的工作就是纠正该错误) - 您需要更改的是顶级容器的位置。

这里是一个创建不在左上角的窗口的示例:

import javax.swing.JFrame;
import javax.swing.JLabel;

public class Main {
    
    public static void main(String[] args) {
        JFrame f = new JFrame("Positioning Test Frame");
        f.add(new JLabel("Window Content Area"));
        f.pack(); // make the Window as small as possible
        //f.setLocationRelativeTo(null); // this line will center the window
        f.setLocation(200, 200); // this line will go to absolute coordinates
        f.setVisible(true);
    }
}

您可能需要根据屏幕尺寸计算窗口位置(在右侧大约 3/4 处)。下面的代码将提供桌面大小(可能由多个屏幕组成)。如果您只对其中一个屏幕感兴趣,您可能会看到从哪里获得该值。

public static Rectangle2D getDesktopSize() {
    Rectangle2D result = new Rectangle2D.Double();
    GraphicsEnvironment localGE = GraphicsEnvironment.getLocalGraphicsEnvironment();
    for (GraphicsDevice gd : localGE.getScreenDevices()) {
      for (GraphicsConfiguration graphicsConfiguration : gd.getConfigurations()) {
        result.union(result, graphicsConfiguration.getBounds(), result);
      }
    }
    return result;
}

Das obige ist der detaillierte Inhalt vonSo legen Sie die Position eines JPanels an einer beliebigen Stelle auf dem Bildschirm fest. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Dieser Artikel ist reproduziert unter:stackoverflow.com. Bei Verstößen wenden Sie sich bitte an admin@php.cn löschen