Arrange the Label with its respective field Swing

前端 未结 6 1883
小鲜肉
小鲜肉 2021-01-20 18:06

I need to align all the fields with the respective labels,

\"enter

here is my

6条回答
  •  南笙
    南笙 (楼主)
    2021-01-20 18:58

    As a rule of thumb, Never extends the JPanel/JFrameunless 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

    enter image description here

    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);
    
        }
    }
    

提交回复
热议问题