[英]This is my first time using swing and I'm having issues with the JPanel
我正在开发一个供我学校使用的程序。 它就像match.com,但对于一所公立学校。 是的,学校已经允许这样做。
这是我第一次使用 Swing,我在将 JPanel 添加到 JFrame 时遇到了问题,以便我可以看到和使用该按钮。
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);
}
解决面板甚至没有出现的问题的最快方法是什么? 欢迎任何解决方案。
由于您是一个新的 Swing 程序员,我将尝试用下面的示例代码进行解释。 在这里,我采用了您的代码并做了一些更改。 请参阅我在代码中的评论。
通过这些更改,现在程序可以运行并显示一个带有大按钮的窗口。 当用户点击按钮程序退出。
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.