2

Lag is probably not the accurate term but when I add an image to a button the entire frame doesn't display, at least not at first. Re-sizing the window displays all the buttons as intended.

Without the image this issue doesn't occur, so I'm guessing some intermediate retrieval->load step is happening and until that happens I just get this 'error.' So my question is, presuming that's correct what can I do to circumvent/correct that so everything displays immediately as intended?

Here is the code:

/* 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
Legato
  • 609
  • 17
  • 24

1 Answers1

2

when I add an image to a button the entire frame doesn't display, at least not at first.

Call frame.setVisible(true); in the add after adding all the component in the JFrame.


Some points:

  1. Use SwingUtilities.invokeLater() to make sure that EDT is initialized properly.

    Read more

  2. Don't extend any class until and unless you are modifying the existing logic.

    Read more

Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76