문제

I am trying to create a GUI for a game I am trying to make, the game is irrelevant.

what this should do according to me is show me a GUI, with a frame, with a picture, however, just the frame displays, the image is nowhere to be found :(

Could anyone tell me what I did wrong? Thank you for your time!

     import javax.swing.JFrame;
     import javax.swing.JPanel;
     import javax.swing.ImageIcon;
     import javax.swing.JLabel;
     import javax.swing.*;
     import java.awt.BorderLayout;
     import java.awt.*;

     public class Graph
     {
     int maxX,maxY;
     private JFrame frame;

     Graph()
     {
     Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
     maxX = screenSize.width;
     maxY = screenSize.height;
     frame = new JFrame("My Application");
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     frame.setSize(maxX, maxY);
     frame.setLocationRelativeTo(null);
     JLabel label = new JLabel(icon);
     JPanel panel = new JPanel(new BorderLayout());
     panel.add(label, BorderLayout.CENTER);
     frame.add(panel, BorderLayout.CENTER);
     frame.setVisible(true);




    }


    public String g()
    {

    return this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath().replaceAll("´        20", " ");
    }

    public static void main(String args[]) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            Graph g = new Graph();
        }
    });
    }
    }
도움이 되었습니까?

해결책

This example should show you the correct order in which to perform the operations you want. Also, the SwingUtilities.invokeLater() method is the way you should start a swing application. This uses the EDT which you can read about here. Another note is that you set the size of the frame, but when it displays it will be much smaller. That is because you have used frame.pack() which will make sure that only the space you really need is used up.

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Graph {
    JFrame frame;

    public Graph() {
        frame = new JFrame("My Application");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(1366,770);
        frame.setLocationRelativeTo(null);

        JLabel label = new JLabel("SomeLabel");
        JPanel panel = new JPanel(new BorderLayout());
        panel.add(label, BorderLayout.CENTER);

        frame.add(panel, BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String args[]) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                Graph g = new Graph();
            }
        });
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top