gpt4 book ai didi

Java SWING : How to fix size of components in GridLayout

转载 作者:行者123 更新时间:2023-11-30 06:58:13 25 4
gpt4 key购买 nike

我正在 GridLayout 中创建一个简单的窗口,这是我的代码:

package com.company.app;

import javax.swing.*;
import java.awt.*;


public class SpamGUI {

public static void main(String[] args) {
System.out.println("Loading Program..");
JFrame frame = new JFrame("My awesome Program");
frame.setVisible(true);
frame.setSize(800, 200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 3));
panel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);

JLabel lblTrainPath = new JLabel("Enter Training Folder Path");
lblTrainPath.setSize(100,10);
panel.add(lblTrainPath);

JTextField txtTrainPath = new JTextField();
txtTrainPath.setSize(100,10);
panel.add(txtTrainPath);

JButton btnTrainPath = new JButton("Select");
panel.add(btnTrainPath);


JLabel lblTrainPath3 = new JLabel("Enter Training3 Folder Path");
panel.add(lblTrainPath3);

JTextField txtTestPath = new JTextField();
panel.add(txtTestPath);

JButton btnTestPath = new JButton("Select");
panel.add(btnTestPath);


frame.add(panel);

}
}

它生成这样的屏幕:

enter image description here

正如您所看到的,它不考虑组件的大小,在屏幕上显示得相当宽。另外,当我从 INtelliJ IDEA 运行程序时,除非调整屏幕大小,否则它不会渲染组件。

我还想要一个具有自定义尺寸组件的固定尺寸窗口。

请指导

最佳答案

Font 类允许您指定字体大小。

因此,要创建字体,您应该像这样编写代码:

Font f = new Font("serif", Font.PLAIN, fontSize);

fontSize 参数将确定Font 的大小因此,在这里输入您想要的字体大小。然后将该字体实例变量 f 设置为您的 JLabel 实例变量,如下所示:

lblTrainPath.setFont(f);

以及具有自定义尺寸的组件。你应该尝试 pack() 而不是 frame.setSize(800,200)并在将所有组件添加到框架后使用此 pack() ,对于固定大小的窗口,请使用 setResizes(false)...

关于Java SWING : How to fix size of components in GridLayout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41422471/

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