有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在JavaSwing中对齐组件?

我正在用Java构建一个简单的初学者应用程序,我需要您帮助我调整组件。我要做的是将组件(JLabel“name”)对齐到面板的左侧。我已经尝试过使用“new FlowLayout(FlowLayout.LEFT)”,但它不起作用,所以我请求您帮助我。下面是框架的图片和源代码

public class firstClass extends JFrame implements ActionListener {


private JFrame frame1;
private JFrame frame2;
private JPanel mainPanelFirst;
private JPanel secondPanel;
private JButton newWindowButton;
private int mulitplyPanels;
private JLabel leftLabel;
private JLabel rightLabel;
private JComboBox leftCB;
private JComboBox rightCB;

第一个窗口:

https://i.stack.imgur.com/DhXXM.png

public JFrame createMainUI(){

   frame1 = new JFrame("Main frame");
   frame1.setSize(600,600);
   frame1.setResizable(false);
   frame1.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
   frame1.setVisible(true);

   mainPanelFirst = new JPanel();
   mainPanelFirst.setLayout(new FlowLayout());
   frame1.add(mainPanelFirst);


   newWindowButton = new JButton("Open new window");
   newWindowButton.addActionListener(this);
   mainPanelFirst.add(newWindowButton);


   return frame1;

}

第二个窗口(包括我要对齐的标签):

https://i.stack.imgur.com/VRIFr.png

 public JFrame createSecondUI() {

    frame2 = new JFrame("Second frame");
    frame2.setSize(600, 600);
    frame2.setResizable(false);
    frame2.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame2.setVisible(true);

    secondPanel = new JPanel();
    secondPanel.setLayout(new FlowLayout());
    secondPanel.setBackground(Color.gray);
    frame2.add(secondPanel);


    JPanel topPanel = new JPanel();
    topPanel.setLayout(new FlowLayout(70,400,20));
    topPanel.setBackground(Color.WHITE);
    secondPanel.add(topPanel);



    leftLabel = new JLabel("Name:");
    topPanel.add(leftLabel);



    return frame2;


}


 @Override
    public void actionPerformed(ActionEvent e) {

        createSecondUI();

    }
}

谢谢你的帮助:)


共 (2) 个答案

  1. # 2 楼答案

    我建议您的应用程序使用布局管理器。你要找的最有可能是BorderLayout,除非你想要特定的功能来控制对象的布局位置和方式

    希望这有帮助

    Layout Managers

    How to use BorderLayout