Java 重写JComponent方法
运行此代码后,将显示windows大小的0x0。 我可以通过在main方法中写入“f.setSize(640480);”来修复它。 我听说这不好,所以。。有没有办法使这一压倒一切的工作Java 重写JComponent方法,java,user-interface,Java,User Interface,运行此代码后,将显示windows大小的0x0。 我可以通过在main方法中写入“f.setSize(640480);”来修复它。 我听说这不好,所以。。有没有办法使这一压倒一切的工作 public class Gui { public static void main(String[] args) throws IOException { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFram
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()
引自:
使此窗口的大小适合其子组件的首选大小和布局。如果任意一个尺寸小于上一次调用setMinimumSize方法指定的最小尺寸,则生成的窗口宽度和高度将自动放大
此外,不应使用主线程中的swing组件。仅从事件分派线程。阅读