Java swing - 尺寸错误

标签 java swing layout size

所以我有这个问题。我在 Java Eclipse SDK 4.2.1 中编写了这段代码。我没有在这里全部写出来,actionPerformed 方法现在无关紧要,它从 Main 调用一次。问题是有时当我运行它时,其中一个组件会填满整个窗口并与所有其他组件重叠。我尝试通过随机数更改大小,例如从 400 到 350,有时它起作用,然后又坏了。我可能错过了什么,我只是不知道是什么。我搜索了其他论坛,但一无所获。

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collections;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;


public class Window extends JFrame implements ActionListener
{
    JTextField field1;
    JTextField field2;

    public Window()
    {
        super("Main Window");
        setVisible(true);
        setSize(500, 500);
        setResizable(false);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        Initialize();
    }
    private void Initialize()
    {
        field1 = new JTextField();
        field2 = new JTextField();
        field1.setBounds(0, 0, 400, 100);
        field2.setBounds(0,100,400,100);
        add(field1);
        add(field2);
        field1.setBackground(Color.PINK);
        field1.setForeground(Color.RED);
        field2.setBackground(Color.PINK);
        field2.setForeground(Color.RED);
        JButton button = new JButton("Create");
        button.setBounds(0, 200, 400, 100);
        add(button);
        button.setBackground(Color.BLACK);
        button.setForeground(Color.YELLOW);
        button.addActionListener(this);

    }

最佳答案

您的问题是您的代码不遵守正在使用的布局管理器,因为您正在尝试添加组件,就好像正在使用的布局为空,而实际上它不是。解决方案是阅读并了解布局管理器,并使用它们;这包括避免调用 setBounds(...)。请注意,JFrame 的 contentPane 默认使用 BorderLayout。此信息应该可以帮助您入门。另请注意,错误 解决方案是使用空布局。因此,如果有人提出此建议,我强烈建议您忽略他们。

关于Java swing - 尺寸错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15313380/

相关文章:

Java Swing - 如何从 PlainDocument 将光标定位在 JTextField 内

java - Activity 标题显示奇数值

android - 如何通过代码在 RelativeLayout 中定位 Button?

Java 支持无法弄清楚

java - Map<String, Collection<Object>> 是否可以在 Spring 中声明

java - 以 gzip 格式包装压缩数据

java - 在 JTextFIeld 中隐藏/显示密码 (Java Swing)

java - 将 Android Java 模块转换为普通 Java 模块需要执行哪些步骤?

java - 如何在 JRadioButtons 的 ButtonGroup 中随机选择一个按钮?

java - 向 RatingBar 添加边距/填充