java - 元素不会出现在具有 GridLayout 或 FlowLayout 的面板中,但具有 setBounds 时它们会出现在面板中

标签 java swing jpanel layout-manager

我正在编写一个由 JFrame 中的多个面板组成的程序。 我需要在不同的类中完成每个元素(这是因为在我的学校,我们需要将每个元素分开在不同的类中以获得干净的代码),但是我看到的针对我的问题的每个示例,他们都在一个类中完成所有操作。 我认为我的问题来自于有多个类(class),所以我向您展示我的类(class)。

我有一个面板,我需要在其中放置 2 个面板,这是代码:

public class Inscription extends JPanel{
private PanneauBoutons panneauBoutons = new PanneauBoutons();
private PanneauFormulaire panneauFormulaire = new PanneauFormulaire();

  public Inscription(){
    this.setLayout(new BorderLayout());
    this.setBorder(BorderFactory.createLineBorder(Color.RED, 2));

    this.add(panneauFormulaire,BorderLayout.CENTER);
    this.add(panneauBoutons,BorderLayout.SOUTH);

    this.setVisible(true);
  }  
}

这是面板 panneauFormulaire :

public class PanneauFormulaire extends JPanel{
private JLabel labelMatricule;
private JTextField zoneTexteMatricule;

public PanneauFormulaire(){
    this.setLayout(new GridLayout(8,2,10,10));

    this.setBorder(BorderFactory.createLineBorder(Color.black));

    labelMatricule = new JLabel("Matricule : ");
    this.add(labelMatricule);
    zoneTexteMatricule = new JTextField(30);
    this.add(zoneTexteMatricule);

    this.setVisible(true);
}

因此,如果我不执行 setBounds,问题 Inscription 不会出现在主框架上,但我想要一个 BorderLayout... (我测试过,通过设置边界,我可以看到边框,所以我认为这意味着面板确实添加到框架中,所以为什么没有 setBounds 我看到任何东西?)。 另一个问题是 PanneauFormulaire 面板没有出现在 Inscription 面板上...

如果我错过了什么,你能帮我吗?谢谢

这是扩展 JFrame 的类:

public class FenetrePrincipale extends JFrame {
  private Container cont;
  private Inscription inscriptionForm;

  public FenetrePrincipale(){
    super("IESN");
    setBounds(100,100,1200,960);
    getContentPane().setLayout(null);
    setLocationRelativeTo(null);
    setResizable(false);

    ...

    inscription.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e){
            cont.removeAll();

            inscriptionForm = new Inscription();
            inscriptionForm.setOpaque(true);

            cont.add(inscriptionForm);

            invalidate();
            repaint();
        }
    });

最佳答案

您不应该使用 null 布局和 setBounds()。 Swing 被设计为与布局管理器一起使用。

but when I click on an option in the menu, the current panel need to be change by another one,

那么您应该使用CardLayout

阅读 Swing 教程中关于 How to Use CardLayout 的部分用于工作示例。因此,请下载示例并将其用作项目的起点。代码的结构将比您当前拥有的代码更好,并且更改工作代码比修复损坏的代码更容易。

关于java - 元素不会出现在具有 GridLayout 或 FlowLayout 的面板中,但具有 setBounds 时它们会出现在面板中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36248487/

相关文章:

java - 使 Jpanel 可滚动

java - 从 NetBeans GUI Builder 在 JPanel 中显示图像

java - 使用 xpath 获取 xml 文件的两个属性

java - java服务器在OutOfMemoryError之后还能生存吗

JAVAX:不需要的属性

java - 尝试从 jframe 制作屏幕保护程序,无法切换图像

java - 使用另一个类的 JavaFX 媒体播放器播放音频文件

java - 使用 JOOQ 仅存储表/列名称和类型而不考虑记录类型

Java Swing,如何使用鼠标调整 JPanel 的大小?

java - 按下按钮时不会重置时间