繁体   English   中英

Java Swing 将 JButton 添加到 JFrame 不起作用

[英]Java Swing adding a JButton to a JFrame doesn't work

I have been coding with Swing for a long moment in windows and when I switched to Manjaro Linux, something as basic as adding a JButton to a JFrame wouldn't work. (另外我在控制台中没有 output,没有丢失的库只有一个空白窗口)。

有人可以帮我解决这个问题吗?

这是代码:

package test;

import javax.swing.JButton;
import javax.swing.JFrame;

public class main {
    public static void main(String[] args) {
        JFrame window = new JFrame();
        JButton button = new JButton("My button");
        window.setSize(600,600);
        window.setVisible(true);
        window.add(button);
    }
}

在此处输入图像描述

如评论中所述:

window.setSize(600,600); 
window.setVisible(true); 
window.add(button); 

应该改为

window.add(button); 
window.pack(); 
window.setVisible(true); 

始终在设置 window 可见之前添加所有组件。

window.setSize(600,600); 只不过是猜测,而window.pack(); 使 window 达到所需的尺寸。

这是用于上述屏幕截图的代码。 代码注释中的更多详细信息。

import java.awt.Insets;
import javax.swing.*;

public class DisplayButton {
    public static void main(String[] args) {
        JFrame window = new JFrame();
        JButton button = new JButton("My button");
        // This is a random guess as to how big the window should be. DON'T GUESS
        //window.setSize(600,600);
        // The button should be added before the frame is packed to size and displayed
        window.add(button);
        // But since you want it BIG, let's make it so, 
        // usefully by first increasing the text size
        button.setFont(button.getFont().deriveFont(60f));
        // Then add a chunk of insets - adjust to need.
        button.setMargin(new Insets(20, 100, 20, 100));
        // Make the window the size it NEEDS to be to display the button.
        window.pack();
        window.setVisible(true);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM