gpt4 book ai didi

java - 重写 JComponent 方法

转载 作者:行者123 更新时间:2023-12-01 12:46:50 25 4
gpt4 key购买 nike

运行此代码后,出现的窗口大小为 0x0。我可以通过编写“f.setSize(640, 480);”来修复它在主要方法中。我听说它的做法很糟糕,所以..有没有办法让这个压倒性的工作发挥作用?

public class Gui {

public static void main(String[] args) throws IOException {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().setBackground(Color.BLACK);
f.add(new DrawingPad());
f.setVisible(true);
}
}

class DrawingPad extends JComponent{
Image img = new ImageIcon("res/icon.jpg").getImage();
Dimension d = new Dimension(640, 480);

public void paintComponent(Graphics g){
g.drawImage(img, 50, 50, null);
}

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

最佳答案

在使框架可见之前调用f.pack()

引自 javadoc :

Causes this Window to be sized to fit the preferred size and layouts of its subcomponents. The resulting width and height of the window are automatically enlarged if either of dimensions is less than the minimum size as specified by the previous call to the setMinimumSize method.

此外,您不应该在主线程中使用 swing 组件。仅来自事件调度线程。阅读 http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html

关于java - 重写 JComponent 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24620264/

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