java - JPanels 文本字段 GBC

标签 java swing jframe jpanel gridbaglayout

我不明白为什么我的文本字段显示为狭缝而不是给定的大小?我是否遗漏了什么,或者我认为问题是我施加的限制太小?提前致谢!

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;

public class addEntry 
{

public void addEntryFrame()
{
    JFrame entryFrame = new JFrame("Passafe");
    entryFrame.setSize(500,500);
    entryFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    JPanel topPanel = new JPanel();
    JLabel topHeader = new JLabel("Add New Entry: ");

    topHeader.setFont(new Font("Ariel", Font.BOLD, 24));
    topPanel.add(topHeader);

    JPanel centerPanel = new JPanel(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.insets = new Insets(15,15,15,15);
    JLabel name = new JLabel("Name: ");
    JLabel username = new JLabel("Username: ");
    JLabel password = new JLabel("Password: ");
    JLabel description = new JLabel("Description: ");
    JTextField nametf = new JTextField(20);
    JTextField usernametf = new JTextField(20);
    JTextField passwordtf = new JTextField(20);
    JTextField descriptiontf = new JTextField(50);

    gbc.gridx = 0;
    gbc.gridy = 0;
    centerPanel.add(name, gbc);
    gbc.gridx = 1;
    gbc.gridy = 0;
    centerPanel.add(nametf, gbc);
    gbc.gridx = 0;
    gbc.gridy = 2;
    centerPanel.add(username, gbc);
    gbc.gridx = 1;
    gbc.gridy = 2;
    centerPanel.add(usernametf, gbc);
    gbc.gridx = 0;
    gbc.gridy = 3;
    centerPanel.add(password, gbc);
    gbc.gridx = 1;
    gbc.gridy = 3;
    centerPanel.add(passwordtf, gbc);
    gbc.gridx = 0;
    gbc.gridy = 4;
    centerPanel.add(description, gbc);
    gbc.gridx = 1;
    gbc.gridy = 4;
    centerPanel.add(descriptiontf, gbc);

    JPanel bottomPanel = new JPanel();
    JButton saveEntryButton = new JButton("SAVE");
    bottomPanel.add(saveEntryButton);

    entryFrame.add(topPanel, BorderLayout.NORTH);
    entryFrame.add(centerPanel, BorderLayout.CENTER);
    entryFrame.add(bottomPanel, BorderLayout.SOUTH);


    entryFrame.setVisible(true);
}
}

最佳答案

不要在 addEntryFrame() 末尾使用 entryFrame.setSize(500, 500); 而应使用 entryFrame.pack(); 方法。

关于java - JPanels 文本字段 GBC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24060218/

相关文章:

java - GlazedList 更新 JTable 中的 EventList

java - JTable 标题中的不同颜色

Java 字符串文字自动解释为 String 对象,但是如何呢?

java - JDBC:多个请求时安全行更新

java - 试图实现选择排序但它不会工作

java - 在java中打印2页jframe

java - Swing 组件出现问题

java - Android Java Sqlite 搜索和替换

java - 使用 BoxLayout 布局管理器自动调整高度

java - 如何创建另一个线程,以便在行星模拟运行时我的 ActionListener 仍然监听按钮按下事件?