2012-10-03 32 views
7

Quiero mostrar 2 objetos en JFrame. Intenté agregando objetos a JPanel y luego agregué JPanel a JFrame, pero tampoco funcionó. También traté de agregar objetos ball1 y ball1 directamente a JFrame, pero solo muestra el último objeto agregado. Quiero mostrar ambos objetos en JFrame a la vez. El código a continuación solo muestra el objeto ball1.Agregar 2 o más objetos a JFrame

JFrame f = new JFrame("Moving"); 
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    //making 2 objects 
    Ballbewegung2 ball = new Ballbewegung2(); 
    Ballbewegung3 ball1 = new Ballbewegung3(); 
    JPanel contentPane = new JPanel(new BorderLayout()); 
    JPanel contentPane1 = new JPanel(new BorderLayout()); 

    //adding objects to JPanel 
    contentPane.add(ball, BorderLayout.CENTER);     
    contentPane1.add(ball1, BorderLayout.CENTER);     

    //Adding JPanel to JFrmae 
    f.getContentPane().add(contentPane); 
    f.getContentPane().add(contentPane1); 
    f.setSize(500, 500); 
    f.setVisible(true); 

Respuesta

4

El panel de contenido de JFrame tiene BorderLayout controlador de distribución por defecto. Eso significa que si agrega un componente, se colocará en el CENTRO. Si agrega otro componente, volverá a colocarlo en el CENTRO y reemplazará el componente agregado anteriormente.

Un ejemplo de cómo agregar varios componentes:

JFrame f = new JFrame(); 

JPanel p = new JPanel(); 

p.add(new JButton("One")); 
p.add(new JButton("Two")); 

f.getContentPane().add(p, BorderLayout.CENTER); 

O cuando se añade un componente al panel de contenido, especificar donde para decirlo (y especificar diferentes ubicaciones):

JFrame f = new JFrame(); 

f.getContentPane().add(new JButton("One"), BorderLayout.NORTH); 
f.getContentPane().add(new JButton("Two"), BorderLayout.CENTER); 
+0

estoy dando diferentes coordenadas de los objetos donde están shown.I también han probado el segundo método, todavía sobrescribe el primer objeto. – user1717353

+0

Incorrecto, usted llama 'f.getContentPane()' dos veces pasando 2 componentes diferentes, pero sin especificar restricciones. Y un panel con BorderLayout sin restricciones explícitamente especificado agregará el componente a la posición CENTRAL, el segundo reemplazando al primero. – icza

5

Le sugiero que use un JPanel para mantener ambos JPanels como secundarios, y agregue un solo JPanel al panel de contenido de JFrame.

La segunda llamada al método JFrame.add() reemplazará el primer JPanel agregado, si no especifica explicitamente una ubicación de diseño diferente.

Un ejemplo sencillo usando BoxLayout:

JPanel mainPanel= new JPanel(); 
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS)); 

mainPanel.add(contentPane); 
mainPanel.add(contentPane1); 
contentPane.add(mainPanel); 
+0

El código funciona bien cuando agrego más de 1 botones en el JFrame pero no funciona con los objetos de mis clases. También he intentado usar 3 JPanles y luego agregar mainPanel a JFrame, pero igual salida. – user1717353

1

Aquí hay un ejemplo para lograr la interfaz de usuario algo como esto

UI

Los componentes de Java utilizadas son las siguientes Java Components

Código :

// Call this function from the main 
private static void createAndShowGUI() { 
    // Create and set up the content pane. 
    MainPanel panel = new MainPanel(); 
    panel.setOpaque(true); // content panes must be opaque 

    // Display the window. 
    JFrame frmConsole = new JFrame("ITSME"); 
    frmConsole.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frmConsole.setPreferredSize(new Dimension(640, 480)); 
    frmConsole.add(panel); 
    frmConsole.pack(); 
    frmConsole.setLocationRelativeTo(null); 
    frmConsole.setVisible(true); 
} 

Clase MainPanel

public class MainPanel extends JPanel implements ActionListener { 
    private static final long serialVersionUID = 1L; 
    private int m_nX, m_nY; 
    private int m_nHeight = 30, m_nWidthLabel = 500, m_nPadding = 2; 

    private JLabel m_lblFilename, m_lblFileGen; 

    public MainPanel() { 
     // TODO Auto-generated constructor stub 
     super(new BorderLayout()); 
     try { 
      this.setLayout(null); 
      this.setBorder(new TitledBorder(new EtchedBorder(), 
       "Dynamic Time Warping")); 

      m_nX = this.getX() + 12; 
      m_nY = this.getY() + 24; 

      // Add the Filename Label 
      m_lblFilename = new JLabel("Label1"); 
      m_lblFilename.setBorder(new LineBorder(Color.BLUE, 2)); 
      m_lblFilename.setBounds(nX, nY, m_nWidthLabel, m_nHeight); 
      this.add(m_lblFilename); 

      // Adding a Label 
      nY += m_lblFilename.getHeight() + m_nPadding; 
      m_lblFileGen = new JLabel("Label1"); 
      m_lblFileGen.setBorder(new LineBorder(Color.RED, 2)); 
      m_lblFileGen.setBounds(nX, nY, m_nWidthLabel, 3 * m_nHeight); 
      m_lblFileGen.setForeground(Color.BLUE); 
      this.add(m_lblFileGen); 
     } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 
Cuestiones relacionadas