2016-11-17 1 views
0

J'essaie de créer un programme simple en Java qui nécessite 8 JLabels en haut avec un JButton directement au-dessous. J'ai essayé d'utiliser BoxLayout puis FlowLayout, mais ce qui se passe est le JLabels disparaître au début du programme. Lorsque vous cliquez sur button, tout s'affiche correctement, mais vous devez redimensionner manuellement la fenêtre. Quelqu'un pourrait-il expliquer ce que je fais mal? Merci!Problèmes de mise en page de l'interface graphique Java

public class ProgramUI { 
    private JButton _jbutton; 
    private ArrayList<JLabel> _jlabels; 
    private JFrame _jframe; 
    private JPanel _top, _bottom; 

public ProgramUI(){ 
_jframe = new JFrame(); 
_jframe.getContentPane().setLayout(new BoxLayout(_jframe.getContentPane(), BoxLayout.Y_AXIS)); 

_top = new JPanel(); 
_jframe.add(_top); 

_bottom = new JPanel(); 
_jframe.add(_bottom); 

_top.setLayout(new FlowLayout(FlowLayout.LEFT)); 
_bottom.setLayout(new FlowLayout(FlowLayout.LEFT)); 

_jlabels = new ArrayList<JLabel>(); 
for (int i=0; i<8; i++) { 
    JLabel label = new JLabel(); 
    _jlabels.add(label); 
    _top.add(label); 
    //...rest of code is not relevant 
} 

_jbutton = new JButton(); 
    _bottom.add(_jbutton); 

_jframe.pack(); 
_jframe.setVisible(true); 
_jframe.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); 
} 

Répondre

0

Je ne recommande pas ni FlowLayout ni BoxLayout. BoxLayout est très simpliste et non portable. FlowLayout n'est même pas un gestionnaire mise en page , c'est une blague. Je recommande d'utiliser soit GroupLayout intégré ou MigLayout de tiers. Vous devez consacrer du temps pour apprendre comment créer une bonne mise en page.

Voici votre exemple avec MigLayout.

package com.zetcode; 

import java.awt.EventQueue; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import net.miginfocom.swing.MigLayout; 

public class ProgramUI extends JFrame { 

    public ProgramUI() { 

     initUI(); 
    } 

    private void initUI() { 

     setLayout(new MigLayout("nogrid")); 

     add(new JLabel("Label")); 
     add(new JLabel("Label")); 
     add(new JLabel("Label")); 
     add(new JLabel("Label")); 
     add(new JLabel("Label")); 
     add(new JLabel("Label")); 
     add(new JLabel("Label")); 
     add(new JLabel("Label"), "wrap"); 
     add(new JButton("Button")); 

     pack(); 

     setTitle("MigLayout example"); 
     setLocationRelativeTo(null);   
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    } 

    public static void main(String[] args) { 

     EventQueue.invokeLater(() -> { 
      ProgramUI ex = new ProgramUI(); 
      ex.setVisible(true); 
     }); 
    } 
} 

Screenshot:

Exampe screenshot