我不太擅长解释,但我会尽力。
基本上,我一直在尝试在我的JPanel
中的JLabel
,JTextField
和JButton
组件周围添加边框,但边框的大小依据组件大小而变化。
这是我的代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class LoginPanel
{
private JPanel loginPanel = new JPanel();
private JFrame loginFrame = new JFrame();
public LoginPanel()
{
loginPanel.setLayout(new GridBagLayout());
GridBagConstraints gridBagConstraints = new GridBagConstraints();
JTextField textLogin = new JTextField(10);
JPasswordField password = new JPasswordField(10);
JButton login = new JButton("Login");
JButton register = new JButton("Register");
gridBagConstraints.insets = new Insets(0,0,0,0);
gridBagConstraints.gridy = 0;
gridBagConstraints.gridx = 0;
loginPanel.setBorder(BorderFactory.createTitledBorder("Login"));
loginPanel.add(new JLabel("E-Mail"), gridBagConstraints);
gridBagConstraints.gridy++;
loginPanel.add(textLogin, gridBagConstraints);
gridBagConstraints.gridy++;
loginPanel.add(new JLabel("Password"), gridBagConstraints);
gridBagConstraints.gridy++;
loginPanel.add(password, gridBagConstraints);
gridBagConstraints.gridy++;
loginPanel.add(login, gridBagConstraints);
gridBagConstraints.gridy++;
loginPanel.add(register, gridBagConstraints);
loginFrame.pack();
loginFrame.add(loginPanel);
loginFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
loginFrame.setLocationRelativeTo(null);
loginFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
loginFrame.setVisible(true);
}
public static void main(String[] args)
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(Exception e)
{
e.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
new LoginPanel();
}
});
}
}
这是结果:
![图像1:结果](https://istack.dev59.com/rKzSl.webp)
![图像2:我想要的外观](https://istack.dev59.com/9FG4S.webp)