Java Swing JFrame 布局

2022-01-24 00:00:00 java swing layout-manager jbutton jframe

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 the button after the textfield then only the button is displayed.

Any idea why?

    JFrame mainframe=new JFrame();
    mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mainframe.setBounds(0,0,200,200);
    JButton jb=new JButton();
    jb.setText("Leech");
    mainframe.add(jb);
    JTextField link=new JTextField(50);
    mainframe.add(link);
    mainframe.pack();
    mainframe.setVisible(true);

解决方案

Add your components to a JPanel and then add that panel to the ContentPane of JFrame.

JFrame window = new JFrame();
JPanel mainframe = new JPanel();

window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(0,0,200,200);

JButton jb = new JButton();
jb.setText("Leech");

mainframe.add(jb);

JTextField link = new JTextField(50);
mainframe.add(link);

window.getContentPane().add(mainframe);
window.pack();
window.setVisible(true);

相关文章