gpt4 book ai didi

java - 自定义 JComponent 上的图像不可见?

转载 作者:行者123 更新时间:2023-11-30 06:31:42 26 4
gpt4 key购买 nike

当我运行我的代码时,它没有出现。基本上我有一个自定义的 Jcomponent,我将其添加到我的 JFrame 或 View,然后创建一个 View,在我的 main 方法中创建框架。我已经添加到 JFrame,这里是我的 JComponent 代码:

public class CardDisplay extends JComponent {
private Card card;
private Image cardImage;

public CardDisplay()
{
cardImage = Toolkit.getDefaultToolkit().createImage(("Phase10//res//Blue2.png"));
}

@Override
public void paint(Graphics g)
{
g.drawImage(cardImage, 125 ,200, this);
}
public class View {
public View(){

}

public void makeFrame()
{
JFrame frame = new JFrame("Phase 10");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JPanel handPanel = new JPanel();
CardDisplay cd = new CardDisplay();
handPanel.setLayout(new FlowLayout());
frame.add(handPanel, BorderLayout.SOUTH);
handPanel.add(cd);
frame.pack();
frame.setSize(600,500);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

public static void main(String[] args){
View view = new View();
Game game = new Game();
view.makeFrame();
//game.run();

}

最佳答案

这是工作版本。问题主要与组件的首选尺寸有关。请注意方法 getPreferredSize() 的实现。

如果您想查看组件边界是什么,我建议您使用 MigLayout Debug模式下的布局管理器(该站点具有所有必要的文档)。

public class CardDisplay extends JComponent {
private BufferedImage cardImage;

public CardDisplay() {
try {
cardImage = ImageIO.read(new File("Phase10//res//Blue2.png"));
} catch (final IOException e) {
e.printStackTrace();
}
}

@Override
public void paintComponent(final Graphics g) {
super.paintComponent(g);
g.drawImage(cardImage, 0, 0, null);
}

@Override
public Dimension getPreferredSize() {
if (cardImage == null) {
return new Dimension(100, 100);
} else {
return new Dimension(cardImage.getWidth(null), cardImage.getHeight(null));
}
}

public static class View {
public View() {}

public void makeFrame() {
final JFrame frame = new JFrame("Phase 10");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
final JPanel handPanel = new JPanel();
final CardDisplay cd = new CardDisplay();
handPanel.setLayout(new FlowLayout());
frame.add(handPanel, BorderLayout.SOUTH);
handPanel.add(cd);
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}

public static void main(final String[] args) {
final View view = new View();
view.makeFrame();
}
}

关于java - 自定义 JComponent 上的图像不可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9588118/

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