I need to align all the fields with the respective labels,
here is my
As a rule of thumb, Never extends the JPanel
/JFrame
unless you are really extending their functionality, always favour composition over inheritance.
For a swing layout manager, I highly recommend miglayout, simple and easy to get started with, you have to download the jar and add it to your CLASSPATH
.
The complete code for prototyping this GUI
Will be just as simple as :
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import net.miginfocom.swing.MigLayout;
/**
* Hello world!
*
*/
public class App {
private JPanel panel;
private JLabel cilentIPLabel= new JLabel();
private JLabel clientPWLabel= new JLabel();
private JTextField clientIPTextField= new JTextField();
private JTextField clientPWTextField= new JTextField();
private JButton printButton = new JButton();
public App() {
initComponents();
}
private void initComponents() {
cilentIPLabel.setText("Client IP :");
clientPWLabel.setText("Client Password :");
printButton.setText("print");
printButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("The ID of the clinet is " + clientIPTextField.getText());
}
});
}
public JPanel getPanel() {
if (panel == null) {
panel= new JPanel(new MigLayout("gap 10","[100]10[100, left, fill, grow]","[][]20[]"));
panel.add(cilentIPLabel);
panel.add(clientIPTextField, "wrap");
panel.add(clientPWLabel);
panel.add(clientPWTextField, "wrap");
panel.add(printButton, "skip, tag apply");
}
return panel;
}
public static void main(String[] args) {
JFrame frame= new JFrame("SO demo");
frame.setSize(400, 150);
frame.setContentPane(new App().getPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}