So I have this code in my main class:
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JLabel;
@SuppressWarnings("serial")
public class Main extends JPanel{
private final int height = 285;
private final int width = 416;
private static final double appversion = 0.1;
private BufferedImage sdk001;
private static final String appname = "App's Name";
private static final String appstage = "Alpha";
private JFrame frame;
public Main() {
try {
sdk001 = ImageIO.read(getClass().getResourceAsStream("img\\cards\\sdk001.png"));
frame = new JFrame(appname + " (" + appversion + " " + appstage + ")");
frame.add(new Main());
frame.setSize(1020, 680);
frame.setVisible(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
catch (IOException e) {
Logger LogErr = Logger.getLogger(Main.class.getName());
System.err.println("Caught IOException: " + e.getMessage());
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(sdk001, 0, 0, height, width, null);
}
public static void main(String[] args) {
Main main = new Main();
JFrame frame = main.getFrame();
}
public JFrame getFrame() {
return frame;
}
And I tried to call it in my "A" class, here's the code:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
public class A {
public A(Main main){
JFrame frame = main.getFrame();
frame.add(new JLabel("Hi OtherClass did this") );
}
The code returns without error but no JFrame, or any GUI, showing up. Can anyone help me with this; I'm quite baffled by this. Thanks.
You need to initialize JFrame
with new
keyword and make it visible with preferred size, than you can view your GUI.
Main main = new Main();
JFrame frame = new JFrame(); //main.getFrame();
frame.add(main); // Add JPanel with components to JFrame
frame.setSize(300,300);
frame.setVisible(true);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.