gpt4 book ai didi

java - JPanel 没有出现在使用 BorderLayout 的 JFrame 中

转载 作者:行者123 更新时间:2023-11-29 07:47:37 25 4
gpt4 key购买 nike

我有一个使用 GridLayout 的 JPanel,其中包含 6 个 JLabel。如果我只将这个 JPanel 添加到 JFrame,一切正常,但是当我将它添加到 BorderLayout.WEST(连同其他 3 个面板在 EAST、CENTER 和 SOUTH)时,它就不会显示。

这是我使用的代码:

public class SwingView extends JFrame {
private DeckLabel[] terrains={
new DeckLabel(new ImageIcon("assets/graphics/mountains.png"),0),
new DeckLabel(new ImageIcon("assets/graphics/planes.png"),1),
new DeckLabel(new ImageIcon("assets/graphics/forest.png"),2),
new DeckLabel(new ImageIcon("assets/graphics/fields.png"),3),
new DeckLabel(new ImageIcon("assets/graphics/swamp.png"),4),
new DeckLabel(new ImageIcon("assets/graphics/desert.png"),5)};
public SwingView() {
super("Frame");
this.setSize(680, 740);
this.setLayout(new BorderLayout());
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
Utilities.center(this);

// panels
//terrains
JPanel terrainsPanel = new JPanel();
terrainsPanel.setSize(100, 640);
terrainsPanel.setLayout(new GridLayout(6, 1));
//map
JPanel mapPanel = new JPanel();
mapPanel.setSize(480, 640);
//info
JPanel infoPanel = new JPanel();
infoPanel.setSize(100, 640);
//chat
JPanel chatPanel = new JPanel();
chatPanel.setSize(680, 100);
chatView.setEditable(false);
txtChat.addKeyListener(this);
chatPanel.add(txtChat, BorderLayout.SOUTH);
chatPanel.add(chatView);

// terrains
for (int i = 0; i < 6; i++) {
terrainsPanel.add(terrains[i]);
}
this.add(mapPanel,BorderLayout.CENTER);
this.add(terrainsPanel, BorderLayout.WEST);
this.add(infoPanel, BorderLayout.EAST);
this.add(chatPanel, BorderLayout.SOUTH);

}
}

public class DeckLabel extends JLabel{
private Image image;
private int index;
public DeckLabel(ImageIcon icon,int index){
this.image=icon.getImage();
this.index=index;
}

@Override
public void paint(Graphics g){
BufferedImage bi = new BufferedImage(85, 78,
BufferedImage.TYPE_INT_RGB);
Graphics2D tg = bi.createGraphics();
tg.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// draw basic tile
tg.drawImage(image, 0, 0, null);
g.drawImage(bi,0,0,null);
}
}

谢谢

最佳答案

很多问题

  • 使用 JPanel 而不是 JLabel,
  • 重写 paintComponent 而不是 JLabel/JPanel/Swing JComponents 的绘制
  • 第一。代码行应该是 super.pain(Component),或者让 JPanel 停止重绘(鼠标和按键事件)
  • 或为图像使用 JLabel.setIcon
  • Utilities.center(this); 出了点问题,你试过布局容器吗
  • FlowLayout 是 JPanel 的默认布局管理器,然后是 chatPanel.add(txtChat, BorderLayout.SOUTH);被忽略而不遗漏代码行 chatPanel.setLayout(new BorderLayout)
  • txtChat.addKeyListener(这个);我希望这不是 JTextComponents 的一部分,如果是,则改用 DocumentListener/Filter

关于java - JPanel 没有出现在使用 BorderLayout 的 JFrame 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24206860/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com