java - JButton 缩放整个屏幕

标签 java eclipse swing java-8 jbutton

我有以下代码

    JFrame frame = new JFrame("Organizer");
    frame.setBounds(100, 100, 700, 700);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);


    JButton testbutton = new JButton("testbutton");
    testbutton.setBounds(0, 0, 55, 55);

    JButton testbutton2 = new JButton("tdestbutton2");
    testbutton2.setBounds(55, 0, 44, 44);

    frame.add(testbutton2);
    frame.add(testbutton);

结果有时是正确的,有时是这样的 enter image description here

我做错了什么?

最佳答案

What am I doing wrong?

  • 不要使用setBounds();使用layout manager .

  • 在将组件添加到封闭容器后调用 setVisible()

  • event dispatch thread构造和操作 Swing GUI 对象.

下面的示例添加了一个具有空边框的面板和一个被填充以匹配的 GridLayout。对于这样的应用,还可以考虑 JToolBar对于按钮和 CardLayout用于工作屏幕。

image

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 * @see http://stackoverflow.com/a/37366846/230513
 */
public class Test {

    private static final int PAD = 50;

    private void display() {
        JFrame f = new JFrame("Test");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel p = new JPanel(new GridLayout(0, 1, PAD, PAD));
        p.setBorder(BorderFactory.createEmptyBorder(PAD, PAD, PAD, PAD));
        p.add(new JButton("Test Button 1"));
        p.add(new JButton("Test Button 2"));
        f.add(p, BorderLayout.CENTER);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Test()::display);
    }
}

关于java - JButton 缩放整个屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37366686/

相关文章:

java - IOException:读取错误

java - 是否可以反编译和调试 Java 应用程序?

eclipse - 获取 Eclipse IDE 以显示它正在使用的 Java RE 版本

java - 面积计算器无法运行,不知道为什么

java - Spring @Transactional 和 @Async

java - 如何对发送到 Activity 的不同 Extras 执行不同的操作?

java - 如何在 Birt 报告中对标签进行垂直对齐(文本旋转)

java - 基于 Eclipse 的 E3 应用程序,切换工作区不起作用

java - 如何构建 Swing 应用程序

java - JFrame:如何禁用窗口大小调整?