Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 重写JComponent方法_Java_User Interface - Fatal编程技术网

Java 重写JComponent方法

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

运行此代码后,将显示windows大小的0x0。 我可以通过在main方法中写入“f.setSize(640480);”来修复它。 我听说这不好,所以。。有没有办法使这一压倒一切的工作

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组件。仅从事件分派线程。阅读