Java如何新建jframe
新建 JFrame 的基本方法
在 Java 中创建 JFrame 可以通过继承 JFrame 类或直接实例化 JFrame 对象。以下是两种常见方式:

方式1:继承 JFrame 类

import javax.swing.JFrame;
public class MyFrame extends JFrame {
public MyFrame() {
setTitle("我的窗口");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new MyFrame();
}
}
方式2:直接实例化 JFrame 对象
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("我的窗口");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
设置 JFrame 常用属性
setTitle(String title):设置窗口标题setSize(int width, int height):设置窗口大小setDefaultCloseOperation(int operation):设置关闭行为setVisible(boolean visible):显示或隐藏窗口setLocationRelativeTo(Component c):设置窗口居中
添加组件到 JFrame
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("带按钮的窗口");
frame.setSize(400, 300);
JPanel panel = new JPanel();
JButton button = new JButton("点击我");
panel.add(button);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
使用布局管理器
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.FlowLayout;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("布局示例");
frame.setLayout(new FlowLayout());
frame.add(new JButton("按钮1"));
frame.add(new JButton("按钮2"));
frame.add(new JButton("按钮3"));
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
事件处理示例
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("事件示例");
JButton button = new JButton("点击我");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("按钮被点击了");
}
});
frame.add(button);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
以上代码示例展示了创建 JFrame 的基本方法、常用属性设置、添加组件、使用布局管理器以及事件处理等核心功能。






