2013-05-09 3 views
0

Я пытаюсь получить JPanel, чтобы появиться внутри другого JPanel. В настоящее время JPanel находится во внешнем JFrame и загружается вместе с другим JFrame. Я хочу, чтобы JPanel находился внутри другого JPanel, поэтому программа не открывала два разных окна.JPanel Inside Of A JPanel

Вот картина:

Picture

Маленькие JPanel с текстом журналов, которые я хочу внутри основного игрового кадра. Я попытался добавить панель на панель, panel.add(othePanel). Я пробовал добавить JFrame, frame.add(otherPanel). Он просто перезаписывает все остальное и дает ему черный фон.

Как добавить панель, изменить ее размер и переместить?

редактирует:

Вот где я хочу быть Chatbox.

That is where I want the chatbox to be.

Код класса:

Вышедшие из верхней части класса.

public static JPanel panel; 
public static JTextArea textArea = new JTextArea(5, 30); 
public static JTextField userInputField = new JTextField(30); 

public static void write(String message) { 
    Chatbox.textArea.append("[Game]: " + message + "\n"); 
    Chatbox.textArea.setCaretPosition(Chatbox.textArea.getDocument() 
      .getLength()); 
    Chatbox.userInputField.setText(""); 
} 

public Chatbox() { 
    panel = new JPanel(); 
    panel.setPreferredSize(new Dimension(220, 40)); 
    panel.setBackground(Color.BLACK); 

    JScrollPane scrollPane = new JScrollPane(textArea); 
    scrollPane.setPreferredSize(new Dimension(380, 100)); 
    textArea.setLineWrap(true); 
    textArea.setWrapStyleWord(true); 
    textArea.setEditable(false); 
    scrollPane 
      .setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); 
    userInputField.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent event) { 
      String fromUser = userInputField.getText(); 
      if (fromUser != null) { 
       textArea.append(Frame.username + ":" + fromUser + "\n"); 
       textArea.setCaretPosition(textArea.getDocument() 
         .getLength()); 
       userInputField.setText(""); 
      } 
     } 
    }); 
    panel.add(userInputField, SwingConstants.CENTER); 
    panel.add(scrollPane, SwingConstants.CENTER); 

    //JFrame frame = new JFrame(); 
    //frame.add(panel); 
    //frame.setSize(400, 170); 
    //frame.setVisible(true); 
} 

Основной класс кадра:

public Frame() { 
    frame.getContentPane().remove(loginPanel); 
    frame.repaint(); 

    String capName = capitalizeString(Frame.username); 
    name = new JLabel(capName); 

    new EnemyHealth("enemyhealth10.png"); 
    new Health("health10.png"); 
    new LoadRedCharacter("goingdown.gif"); 
    new Spellbook(); 
    new LoadMobs(); 
    new LoadItems(); 
    new Background(); 
    new Inventory(); 
    new ChatboxInterface(); 

    frame.setBackground(Color.black); 
    Frame.redHealthLabel.setFont(new Font("Serif", Font.PLAIN, 20)); 
    ticks.setFont(new Font("Serif", Font.PLAIN, 20)); 
    ticks.setForeground(Color.yellow); 
    Frame.redHealthLabel.setForeground(Color.black); 

    // Inventory slots 
    panel.add(slot1); 

    panel.add(name); 

    name.setFont(new Font("Serif", Font.PLAIN, 20)); 
    name.setForeground(Color.white); 

    panel.add(enemyHealthLabel); 
    panel.add(redHealthLabel); 
    panel.add(fireSpellBookLabel); 
    panel.add(iceSpellBookLabel); 
    panel.add(spiderLabel); 
    panel.add(appleLabel); 
    panel.add(fireMagicLabel); 
    panel.add(swordLabel); 

    // Character 
    panel.add(redCharacterLabel); 

    // Interface 
    panel.add(inventoryLabel); 
    panel.add(chatboxLabel); 

    // Background 
    panel.add(backgroundLabel); 

    frame.setContentPane(panel); 
    frame.getContentPane().invalidate(); 
    frame.getContentPane().validate(); 
    frame.getContentPane().repaint(); 

     //I WOULD LIKE THE LOADING OF THE PANEL SOMEWHERE IN THIS CONSTRUCTOR. 

    new ResetEntities(); 
    frame.repaint(); 

    panel.setLayout(null); 
    Run.loadKeyListener(); 

    Player.px = Connect.x; 
    Player.py = Connect.y; 

    new Mouse(); 

    TextualMenu.rect = new Rectangle(Frame.inventoryLabel.getX() + 80, 
      Frame.inventoryLabel.getY() + 100, 
      Frame.inventoryLabel.getWidth(), 
      Frame.inventoryLabel.getHeight()); 

    Player.startMessage(); 
} 
+0

Ваш фон кадр имеет три отдельные зоны. Где именно вы хотите, чтобы ваши текстовые журналы появлялись? Какой менеджер макетов вы используете для фона? –

+0

Вам нужно будет больше рассказать о том, как вы уже структурировали фрейм. –

+0

Я обновил свой основной пост с дополнительной информацией. Фоновый фрейм имеет нулевой макет. – Nic

ответ

4

Не использовать статические переменные.

Не используйте нулевой макет.

Используйте соответствующие менеджеры макетов. Возможно, основная панель использует BorderLayout. Затем вы добавляете свой основной компонент в CENTER и вторую панель на EAST. Вторая панель также может использовать BorderLayout. Затем вы можете добавить два компонента в СЕВЕР, ЦЕНТР или ЮЖНЫЙ, как вам нужно.

+0

Моя рамка, основная панель и панель чата используют нулевой макет. – Nic

+1

Я знаю. Мое предложение - правильно использовать Swing и использовать менеджеры макетов. – camickr

+0

Это проблема. Мне нужно разместить изображения в определенных местах. Не общие местоположения компаса. – Nic

1

Например, с помощью пользовательского Border:

import java.awt.BorderLayout; 
import java.awt.Color; 
import java.awt.Component; 
import java.awt.Dimension; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.GridLayout; 
import java.awt.Insets; 
import java.awt.RadialGradientPaint; 
import java.awt.geom.Point2D; 
import java.awt.image.BufferedImage; 
import java.io.IOException; 
import java.net.MalformedURLException; 
import java.net.URL; 

import javax.imageio.ImageIO; 
import javax.swing.*; 
import javax.swing.border.AbstractBorder; 

@SuppressWarnings("serial") 
public class FrameEg extends JPanel { 
    public static final String FRAME_URL_PATH = "http://th02.deviantart.net/" 
     + "fs70/PRE/i/2010/199/1/0/Just_Frames_5_by_ScrapBee.png"; 
    public static final int INSET_GAP = 120; 

    private BufferedImage frameImg; 
    private BufferedImage smlFrameImg; 

    public FrameEg() { 
     try { 
     URL frameUrl = new URL(FRAME_URL_PATH); 
     frameImg = ImageIO.read(frameUrl); 

     final int smlFrameWidth = frameImg.getWidth()/2; 
     final int smlFrameHeight = frameImg.getHeight()/2; 
     smlFrameImg = new BufferedImage(smlFrameWidth, smlFrameHeight, 
       BufferedImage.TYPE_INT_ARGB); 
     Graphics g = smlFrameImg.getGraphics(); 
     g.drawImage(frameImg, 0, 0, smlFrameWidth, smlFrameHeight, null); 
     g.dispose(); 

     int top = INSET_GAP; 
     int left = top; 
     int bottom = top; 
     int right = left; 
     Insets insets = new Insets(top, left, bottom, right); 
     MyBorder myBorder = new MyBorder(frameImg, insets); 

     JTextArea textArea = new JTextArea(50, 60); 
     textArea.setWrapStyleWord(true); 
     textArea.setLineWrap(true); 
     for (int i = 0; i < 300; i++) { 
      textArea.append("Hello world! How is it going? "); 
     } 
     setLayout(new BorderLayout(1, 1)); 
     setBackground(Color.black); 

     Dimension prefSize = new Dimension(frameImg.getWidth(), 
       frameImg.getHeight()); 
     JPanel centerPanel = new MyPanel(prefSize); 
     centerPanel.setBorder(myBorder); 
     centerPanel.setLayout(new BorderLayout(1, 1)); 
     centerPanel.add(new JScrollPane(textArea), BorderLayout.CENTER); 

     MyPanel rightUpperPanel = new MyPanel(new Dimension(smlFrameWidth, 
       smlFrameHeight)); 
     MyPanel rightLowerPanel = new MyPanel(new Dimension(smlFrameWidth, 
       smlFrameHeight)); 
     top = top/2; 
     left = left/2; 
     bottom = bottom/2; 
     right = right/2; 
     Insets smlInsets = new Insets(top, left, bottom, right); 
     rightUpperPanel.setBorder(new MyBorder(smlFrameImg, smlInsets)); 
     rightUpperPanel.setLayout(new BorderLayout()); 
     rightLowerPanel.setBorder(new MyBorder(smlFrameImg, smlInsets)); 
     rightLowerPanel.setBackgroundImg(createBackgroundImg(rightLowerPanel 
       .getPreferredSize())); 

     JTextArea ruTextArea1 = new JTextArea(textArea.getDocument()); 
     ruTextArea1.setWrapStyleWord(true); 
     ruTextArea1.setLineWrap(true); 
     rightUpperPanel.add(new JScrollPane(ruTextArea1), BorderLayout.CENTER); 

     JPanel rightPanel = new JPanel(new GridLayout(0, 1, 1, 1)); 
     rightPanel.add(rightUpperPanel); 
     rightPanel.add(rightLowerPanel); 
     rightPanel.setOpaque(false); 
     add(centerPanel, BorderLayout.CENTER); 
     add(rightPanel, BorderLayout.EAST); 

     } catch (MalformedURLException e) { 
     e.printStackTrace(); 
     } catch (IOException e) { 
     e.printStackTrace(); 
     } 
    } 

    private BufferedImage createBackgroundImg(Dimension preferredSize) { 
     BufferedImage img = new BufferedImage(preferredSize.width, 
      preferredSize.height, BufferedImage.TYPE_INT_ARGB); 
     Point2D center = new Point2D.Float(img.getWidth()/2, img.getHeight()/2); 
     float radius = img.getWidth()/2; 
     float[] dist = {0.0f, 1.0f}; 
     Color centerColor = new Color(100, 100, 50); 
     Color outerColor = new Color(25, 25, 0); 
     Color[] colors = {centerColor , outerColor }; 
     RadialGradientPaint paint = new RadialGradientPaint(center, radius, dist, colors); 
     Graphics2D g2 = img.createGraphics(); 
     g2.setPaint(paint); 
     g2.fillRect(0, 0, img.getWidth(), img.getHeight()); 
     g2.dispose(); 

     return img; 
    } 

    private static void createAndShowGui() { 
     FrameEg mainPanel = new FrameEg(); 

     JFrame frame = new JFrame("FrameEg"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.getContentPane().add(mainPanel); 
     frame.setResizable(false); 
     frame.pack(); 
     frame.setLocationByPlatform(true); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
     public void run() { 
      createAndShowGui(); 
     } 
     }); 
    } 
} 

@SuppressWarnings("serial") 
class MyPanel extends JPanel { 
    private Dimension prefSize; 
    private BufferedImage backgroundImg; 

    public MyPanel(Dimension prefSize) { 
     this.prefSize = prefSize; 
    } 

    public void setBackgroundImg(BufferedImage background) { 
     this.backgroundImg = background; 
    } 

    @Override 
    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     if (backgroundImg != null) { 
     g.drawImage(backgroundImg, 0, 0, this); 
     } 
    } 

    @Override 
    public Dimension getPreferredSize() { 
     return prefSize; 
    } 
} 

@SuppressWarnings("serial") 
class MyBorder extends AbstractBorder { 
    private BufferedImage borderImg; 
    private Insets insets; 

    public MyBorder(BufferedImage borderImg, Insets insets) { 
     this.borderImg = borderImg; 
     this.insets = insets; 
    } 

    @Override 
    public void paintBorder(Component c, Graphics g, int x, int y, int width, 
     int height) { 
     g.drawImage(borderImg, 0, 0, c); 
    } 

    @Override 
    public Insets getBorderInsets(Component c) { 
     return insets; 
    } 
} 

Какой будет выглядеть:

enter image description here

+0

Я попробую это. Благодарю. – Nic

Смежные вопросы