我有一个 JFrame,由于某种原因只出现一个组件
public JFrame mainMenuFrame = new JFrame();
public JLabel welcomeText1 = new JLabel();
public JLabel welcomeText2 = new JLabel("What would you like to do?");
public void mainMenuWindow() {
setNameFrame.dispose();
welcomeText1.setPreferredSize(new Dimension(300, 200));
welcomeText1.setHorizontalAlignment(JLabel.CENTER);
welcomeText1.setVerticalAlignment(JLabel.TOP);
welcomeText1.setFont(new Font("Arial", Font.PLAIN, 15));
welcomeText2.setPreferredSize(new Dimension(200, 200));
welcomeText2.setHorizontalAlignment(JLabel.CENTER);
welcomeText2.setVerticalAlignment(JLabel.CENTER);
welcomeText2.setFont(new Font("Arial", Font.PLAIN, 15));
mainMenuFrame.add(welcomeText1);
mainMenuFrame.add(welcomeText2);
mainMenuFrame.revalidate();
mainMenuFrame.repaint();
mainMenuFrame.setTitle(game);
mainMenuFrame.setLayout(new FlowLayout());
mainMenuFrame.getContentPane();
mainMenuFrame.pack();
mainMenuFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainMenuFrame.setSize(new Dimension(300, 200));
mainMenuFrame.setLocationRelativeTo(null);
mainMenuFrame.setResizable(false);
mainMenuFrame.setVisible(true);
}
我尝试过更改组件类型,但似乎只会显示一个组件
回顾一下评论:
JFrame
默认使用 BorderLayout
作为其 布局管理器。BorderLayout
在其五个区域中的每一个区域中仅包含一个单个组件。BorderLayout
在一个区域中最多包含一个组件,连续的 add
调用将用下一个组件替换前一个组件。在此示例中,
two
组件替换了之前添加的one
组件。我们添加了两个组件,但只看到一个。
package work.basil.example.swing;
import javax.swing.*;
public class OneComponent
{
private static void createAndShowGUI ( )
{
// Window
JFrame.setDefaultLookAndFeelDecorated ( true );
JFrame frame = new JFrame ( "Adding Components In Swing" );
frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
// Widgets
JLabel one = new JLabel ( "One" );
frame.getContentPane ( ).add ( one );
JLabel two = new JLabel ( "Two" );
frame.getContentPane ( ).add ( two );
// Display.
frame.pack ( );
frame.setVisible ( true );
}
public static void main ( String[] args )
{
javax.swing.SwingUtilities.invokeLater ( new Runnable ( )
{
public void run ( ) { OneComponent.createAndShowGUI ( ); }
} );
}
}
解决方案是在添加小部件之前指定所需的布局管理器。
在我们修改后的示例中,我们在顶部指定 ,而不是使用默认的BorderLayout
。现在,当运行时,我们现在看到两个添加的组件,第二个组件按照预期在第一个组件之后流动,并带有
FlowLayout
。
package work.basil.example.swing;
import javax.swing.*;
import java.awt.*;
public class OneComponent
{
private static void createAndShowGUI ( )
{
// Window
JFrame.setDefaultLookAndFeelDecorated ( true );
JFrame frame = new JFrame ( "Adding Components In Swing" );
frame.setLayout ( new FlowLayout ( ) ); // Specify desired layout manager, to replace default `BorderLayout`.
frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
// Widgets
JLabel one = new JLabel ( "One" );
frame.getContentPane ( ).add ( one );
JLabel two = new JLabel ( "Two" );
frame.getContentPane ( ).add ( two );
// Display.
frame.pack ( );
frame.setVisible ( true );
}
public static void main ( String[] args )
{
javax.swing.SwingUtilities.invokeLater ( new Runnable ( )
{
public void run ( ) { OneComponent.createAndShowGUI ( ); }
} );
}
}