gpt4 book ai didi

java - JButton setlocation 不工作

转载 作者:行者123 更新时间:2023-11-30 06:29:59 25 4
gpt4 key购买 nike

我是 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);
}

最佳答案

GridBagLayout 指定 JButton 的位置。要自由放置它,您应该将内容 Pane 的布局设置为 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);
}

关于java - JButton setlocation 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10973721/

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