Java Swing JFrame Layout

前端 未结 6 679
面向向阳花
面向向阳花 2020-12-09 19:53

I just wrote a simple code where I want a textfield and a button to appear on the main frame, but after running all I see is the textfield.

If I write the code of th

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-09 19:59

    You can also use something like Flow Layout which is the default layout used by JPanel. It is used to arrange components in a line or a row. For example from left to right or from right to left:

    Flow layout arranges components in line and if no space left all remaining components goes to next line. Align property determines alignment of the components as left, right, center etc.

    To use it you will need to set JFrame layout by using JFrame.setLayout(layout) and to pass flow layout as a parameter.

    Following example shows components arranged in flow layout:

    package example.com;
    
    import java.awt.BorderLayout;
    import java.awt.FlowLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    
    public class FlowLayoutExample {
    
        FlowLayoutExample(){
            JFrame frame = new JFrame("Flow Layout");
            JButton button, button1, button2, button3, button4;
            button = new JButton("button 1");
            button1 = new JButton("button 2");
            button2 = new JButton("button 3");
            button3 = new JButton("button 4");
            button4 = new JButton("button 5");
            frame.add(button);
            frame.add(button1);
            frame.add(button2);
            frame.add(button3);
            frame.add(button4);
            frame.setLayout(new FlowLayout());
            frame.setSize(300,300);  
            frame.setVisible(true);  
    
        }
        public static void main(String[] args) {
            new FlowLayoutExample();
        }
    }
    

    Check out to learn more about JFrame layouts.

提交回复
热议问题