gpt4 book ai didi

Java swing 设置大小

转载 作者:行者123 更新时间:2023-12-01 18:00:43 25 4
gpt4 key购买 nike

我遇到问题,我设置了框架的大小,但不起作用。我找到了一个关于此的主题,但这对我没有帮助......

我尝试使用getContentPane().getSize(500,500),但没有任何结果。

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class Mere extends JFrame{
private JPanel b;
public Mere(String titlu){
setSize(500,500);
setLayout(null);
this.getSmth();
pack();
show();
}
public void getSmth(){
JLabel user=new JLabel("User");
user.setBounds(10,10,80,25);
getContentPane().add(user);

JTextField userText=new JTextField(20);
userText.setBounds(100,10,160,25);
getContentPane().add(userText);

JPasswordField pas=new JPasswordField(20);
pas.setBounds(100,40,160,25);
getContentPane().add(pas);

JButton n=new JButton("Register");
n.setBounds(180,80,100,30);
getContentPane().add(n);

JLabel pass=new JLabel("Pass");
pass.setBounds(10,40,100,25);
getContentPane().add(pass);
getContentPane().setVisible(true);
}
public static void main(String[]args){
new Mere("yas");
}
}

最佳答案

  1. 您在调用 setSize() 之后调用 pack();

    来自Oracle docs

    Causes this Window to be sized to fit the preferred size and layouts of its subcomponents. The resulting width and height of the window are automatically enlarged if either of dimensions is less than the minimum size as specified by the previous call to the setMinimumSize method.

    因此,您宁愿重写 getPreferredSize() 方法或删除 pack() 调用。请参阅Should I avoid the use of setPreferred/Maximum/MinimumSize? (是)

    但是,最佳实践是使用布局管理器(如下所述),然后调用 pack() 并让管理器在计算 preferredSize 时完成其工作为你

  2. 此外,您还使用 null 布局。 Swing 被设计为与不同的 PLAF 以及屏幕尺寸和分辨率配合使用,而像素完美的 GUI 似乎是制作复杂 GUI 的最佳且更快的方法,您在这方面进步得越多,维护它的问题就越多,因为这个,所以继续使用正确的 Layout Manager或它们的组合。请参阅Null Layout is EvilWhy is it frowned upon to use a null layout in Java Swing?

  3. 另一件事是您没有将程序放在 Event Dispatch Thread (EDT) 上,参见SwingUtilities.invokeLater() why is it needed?this answer有关如何使用它的示例

  4. 我看到的另一件事是,您正在扩展 JFrame ,它翻译成英语,它表示您的类 JFrame ,当您需要将 JFrame 添加到另一个 Component 时,它并不灵活,您应该创建一个 JFrame 实例,如果您确实需要的话扩展某些东西,从 JPanel 扩展。

关于Java swing 设置大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41189286/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com