我对 Java Swing 还很陌生,但我遇到了一个问题。
我必须创建一个登录窗口,从类似这样的图像中汲取灵感(类似这样,scilicet 窗口必须显示 2 个文本字段,用户在其中插入用户名和密码以及一个用于执行登录操作的按钮):
好吧,我认为这非常简单,我已经实现了以下类:
package com.techub.crystalice.gui.login;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.jdesktop.application.SingleFrameApplication;
import com.techub.crystalice.gui.Constants;
import com.techub.crystalice.gui.GUI;
public class LoginFrame extends SingleFrameApplication {
@Override
protected void startup() {
// TODO Auto-generated method stub
System.out.println("DENTRO: LoginFrame() ---> startup()");
this.getMainFrame().setTitle("MyApplication Login");
this.getMainFrame().setSize(600, 350); // Setta le dimensioni del JFrame che rappresenta la finestra principale
Container mainContainer = this.getMainFrame().getContentPane(); // Recupera l'oggetto Container del JFrame
// Imposta un layput manager di tipo GridLayout per il contenitore principale: 3 righe ed una singola colonna:
mainContainer.setLayout(new GridLayout(3,1));
// Contenitore rappresentato da 6 righe a singola colonna contenente i campi testuali e di input del login:
JPanel body = new JPanel();
body.setLayout(new GridLayout(6, 1));
body.add(new JLabel("Username"));
JTextField userName = new JTextField();
body.add(userName);
body.add(new JLabel("Password"));
JTextField password = new JTextField();
body.add(password);
this.getMainFrame().add(body); // Aggiunge al JFrame principale il JPanel contenente il form di login
show(this.getMainFrame());
JPanel footer = new JPanel();
footer.setLayout(new FlowLayout(FlowLayout.CENTER));
JButton loginButton = new JButton("Login");
footer.add(loginButton);
this.getMainFrame().add(footer); // Aggiunge al JFrame principale il JPanel contenente il bottone di login
}
public static void main(String[] args) {
System.out.println("DENTRO: LoginFrame() ---> main()");
launch(LoginFrame.class, args);
}
}
这个类使用一个名为JDesktop的小框架,其中涉及startup()方法的定义,但这是纯Swing代码。唯一要说的是,我通过以下代码行获取了主 **JFrame **:
this.getMainFrame()
这个示例似乎有效,但我在登录表单可视化中遇到了一些美观问题,因为我获得了以下结果:
正如您所看到的,这非常令人讨厌,而且如果结构与示例相同,则会出现一些问题:
- JTextField 的高度太小
- 我的元素之间没有上、左、右边界
- 字体太小
我可以通过某种方式纠正这个错误吗?你能帮我给我一些建议吗?我的windows结构没问题吗?
Tnx
安德里亚
最佳答案
this.getMainFrame().pack()
应用于将JFrame
的大小设置为显示所有组件所需的最小大小。我建议使用
GridBagLayout
,因为GridBagConstraints
允许您指定Insets
,它是组件之间的间距,并且还允许您定位组件正确。使用
java.awt.Font
对象设置适当大小的所需字体。保留对两个JLabel
的引用,然后使用setFont()
设置正确的字体。
关于java - 为什么这个 Swing 登录表单显示错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19841893/