2015-10-15 56 views
0

我是新來的編碼,我有一個小項目可以爲我的班級做。 首先我需要在顯示器上放置兩張圖片,我使用Jpanel標籤來完成。然而,我只是在拍照「狗」的方式出現。狗和貓必須在不同的面板上。我不明白爲什麼只有一個人出現。我的顯示器上只出現一個標籤

以下是我有:

import java.awt.BorderLayout; 
import javax.swing.ImageIcon; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 

public class Cat extends JPanel 
{ 
    //instance variables 
    ImageIcon pic; 
    JLabel label; 

    public Cat() 
    { 
     //constructor 
     pic = new ImageIcon("/Users/dell/Desktop/runKittyRun/cat.png"); 
     // setLayout(new BorderLayout()); 
     label = new JLabel(pic); 
     add(label); 
    } 

} 

================================= =====================

import java.awt.BorderLayout; 
import javax.swing.ImageIcon; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 

public class Dog extends JPanel 
{ 
    //instance variables 
    ImageIcon pic2; 
    JLabel label2; 

    public Dog() 
    { 
     //constructor 
     pic2 = new ImageIcon("/Users/dell/Desktop/runKittyRun/dog.png");   
     label2 = new JLabel(pic2); 
     // add(label2, BorderLayout.NORTH); 
     add(label2); 
    } 

} 

====================== ==========================

import javax.swing.JFrame; 

public class Map { 

    public static void main(String[] args) { 
     map(); 
    } 

    private static void map() { 

       //Creates the frame where panels will be. 
       JFrame frame = new JFrame("Run Kitty Run!"); 
       frame.setSize(1000, 500); 

       Cat player = new Cat(); 
       frame.add(player); 

       Dog pc = new Dog(); 
       frame.add(pc); 

       frame.setVisible(true);   
    } 
} 

回答

0

JFrame使用BorderLayout默認情況下,這意味着它的默認POSITI (CENTER),它只會佈置添加到該位置的最後一個組件。

相反,你可以使用一個GridLayout,例如

JFrame frame = new JFrame("Run Kitty Run!"); 
frame.setLayout(new GridLayout(2, 1)); 

Cat player = new Cat(); 
frame.add(player); 

Dog pc = new Dog(); 
frame.add(pc); 

看一看How to Use GridLayoutLaying Out Components Within a Container的更多細節和其他佈局管理器的例子

+0

有真的已經成爲很多重複的答案,這樣常見問題 - 你不覺得? –

+0

發現一個重複。考慮讓你的答案成爲一個社區wiki。 –

+0

@HovercraftFullOfEels這幾乎適用於任何佈局相關的問題:P – MadProgrammer

相關問題