I am working on a program for my school to use. It is like match.com, but for a public school. Yes there has been permission from the school to do this.
This is the first time I have ever used swing and I am having an issue with adding my JPanel to my JFrame so that I can see and use the button.
private void Framing()
{
JPanel Panel = new JPanel();
Panel.setLayout(new BorderLayout());
JFrame Frame = new JFrame("Warning");
Frame.setUndecorated(true);
JButton OK = new JButton("EXIT");
OK.addActionListener((ActionEvent event) -> {System.exit(0);});
OK.setBounds(100,100,100,100);
Panel.add(OK, BorderLayout.CENTER);
Frame.getContentPane().add(Panel, BorderLayout.CENTER);
Panel.setLocation((Frame.getWidth()-Panel.getWidth())/2,0);
Frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
Frame.setLocation(600, 300);
Frame.setResizable(false);
Frame.setLayout(null);
Frame.setVisible(true);
}
What is the fastest way to fix the issue with the panel not even showing up? Any solutions are welcomed.
Since you are a new Swing programmer, I'll try to explain with below sample code. Here I have taken your code and done few changes. See my comments in the code.
With these changes, now the program works and shows a window with a big button. When user clicks the button program exits.
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
public class SwingTest
{
private void Framing() //Better method name would be "showFrame()"
{
JPanel Panel = new JPanel(); //Better variable name would be "panel"
Panel.setLayout(new BorderLayout());
JFrame Frame = new JFrame("Warning"); //Better variable name would be "frame"
Frame.setUndecorated(true);
JButton OK = new JButton("EXIT"); //Better variable name would be "exitButton"
OK.addActionListener((ActionEvent event) -> {System.exit(0);});
//Not necessary. Layout manager will handle this.
//OK.setBounds(100,100,100,100);
Panel.add(OK, BorderLayout.CENTER);
Frame.getContentPane().add(Panel, BorderLayout.CENTER);
//Not necessary. Layout manager will handle this.
//Panel.setLocation((Frame.getWidth()-Panel.getWidth())/2,0);
Frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
Frame.setLocation(600, 300);
Frame.setResizable(false);
//This is the main problem. You should avoid this.
//Frame.setLayout(null);
Frame.setVisible(true);
}
public static void main(String[] args)
{
new SwingTest().Framing();
}
}
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.