I do not understand well, but I will do my best.
Basically, I am trying to add a border around mine JLabel, JTextFieldand JButtoncomponents in mine JPanel, however, the border expands to fit the size.
This is my code:
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();
}
});
}
}
This is the result:

I want the border to be like this:

I hope that the images explain more, I will answer and provide some more questions.
source
share