java - JButton 设置位置不起作用

标签 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);
}

最佳答案

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 设置位置不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10973721/

相关文章:

java - 如何使用谷歌集合排序功能对 Java 中的值进行 Map<Key, Value> 排序

java - 如何修复线程 "main"java.lang.NoSuchMethodError : org. apache.poi.POIXMLDocumentPart.getPackageRelationship 中的此异常

java - 使用 Android 字符串更改操作栏标题

java - 类魔法 - 自动按类型对对象进行排序

java - 组件在 JPanel 中不可见

java - 我怎样才能获得我的应用程序的可见窗口数?

java - 作为调用父框架的对话框启动应用程序

java - 将 Java 图形呈现为 HTML

java - 停止循环 GIF 图标

java - 绘制用户选择的形状