【问题标题】:JButton with imageicon "lag"带有图像图标“滞后”的 JButton
【发布时间】:2023-03-28 05:32:01
【问题描述】:

滞后可能不是准确的术语,但是当我将图像添加到按钮时,整个框架都不会显示,至少一开始不会。重新调整窗口大小会按预期显示所有按钮。

如果没有图像,这个问题就不会发生,所以我猜测一些中间检索->加载步骤正在发生,直到发生这种情况,我才得到这个“错误”。所以我的问题是,假设这是正确的,我能做些什么来规避/纠正它,以便一切都按预期立即显示?

代码如下:

/* Author: Luigi Vincent Exercise: 12.1 -
* Create a frame and set its layout to FlowLayout
* Create two panels and add them to the frame.
* Each panel contains three buttons. The panel uses FlowLayout
*/

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

public class Ex_1 {
    public static void main(String[] args) {
        Ex1_Layout frame = new Ex1_Layout();
        frame.setTitle("Exercise 12.1");
        frame.setSize(450, 250);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

        ImageIcon valk = new ImageIcon("C:/MyWork/Images/valk.gif");

        JButton alpha = new JButton("Disgaea");
        JButton beta = new JButton("Riviera: The Promised Land");
        JButton gamma = new JButton("Yggdra Union");
        JButton delta = new JButton("Dissidia");
        JButton epsilon = new JButton("Valkyrie Profile", valk);
        JButton zeta = new JButton("Ragnarok Online");

        JPanel p1 = new JPanel();
        JPanel p2 = new JPanel();

        p1.add(alpha);
        p1.add(beta);
        p1.add(gamma);
        p2.add(delta);
        p2.add(epsilon);
        p2.add(zeta);

        frame.add(p1);
        frame.add(p2);

    } // End of Main    
} // End of Ex_1

class Ex1_Layout extends JFrame {
    public Ex1_Layout(){
        setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0)); // Set FlowLayout, aligned left, horizontal and vertical gap of 0
    }
} // End of Ex1_Layout

【问题讨论】:

    标签: java image swing awt


    【解决方案1】:

    当我将图像添加到按钮时,整个框架都不会显示,至少一开始不会。

    JFrame中添加所有组件后,在add中调用frame.setVisible(true);


    几点:

    1. 使用SwingUtilities.invokeLater() 确保EDT 已正确初始化。

      阅读全文

    2. 在修改现有逻辑之前不要扩展任何类。

      阅读全文

    【讨论】:

    • 感谢提示:)
    猜你喜欢
    • 1970-01-01
    • 2014-01-10
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    • 2013-09-05
    • 2021-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多