JButton setlocation不起作用

Bad*_*ral 2 java swing jframe jbutton layout-manager

我是Java新手.我正在尝试移动JButton当前居中的位置,因此我将位置更改为静态位置并且它没有移动.任何的想法?

public Main(BufferedImage image) {
    this.image = image;
}

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    // Draw image centered.
    int x = (getWidth() - image.getWidth())/2;
    int y = 0;//(getHeight() - image.getHeight())/2;
    g.drawImage(image, x, y, this);
}

public static void main(String[] args) throws IOException {
    String path = "img/visualizerLogo3.jpg";
    BufferedImage image = ImageIO.read(new File(path));
    Main contentPane = new Main(image);
    contentPane.setOpaque(true);
    contentPane.setLayout(new GridBagLayout());
    JButton submit = new JButton("Load File");
    submit.setLocation(600, 800);
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setContentPane(contentPane);
    f.setSize(1200,1000);
    //f.setLocation(200,200);
    f.setVisible(true);
    f.add(submit);
}
Run Code Online (Sandbox Code Playgroud)

FTh*_*son 5

GridBagLayout指示JButton的位置.要自由定位它,您应该将内容窗格的布局设置为null(默认情况下它是一个水平的FlowLayout).

public static void main(String[] args) throws IOException {
    String path = "img/visualizerLogo3.jpg";
    BufferedImage image = ImageIO.read(new File(path));
    Main contentPane = new Main(image);
    contentPane.setOpaque(true);
    contentPane.setLayout(null);
    JButton submit = new JButton("Load File");
    submit.setLocation(600, 800);
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setContentPane(contentPane);
    f.setSize(1200,1000);
    //f.setLocation(200,200);
    f.setVisible(true);
    f.add(submit);
}
Run Code Online (Sandbox Code Playgroud)