在使用Swing创建应用程序时,我看到人们会做两件事之一来创建JFrame.哪种方法更好,为什么?
我是Java和编程的初学者.我唯一的学习来源是书籍,YouTube和Stack Overflow.
import {imports};
public class GuiApp1 {
public static void main(String[] args) {
new GuiApp1();
}
public GuiApp1() {
JFrame guiFrame = new JFrame();
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("Example GUI");
guiFrame.setSize(300,250);
................
}
Run Code Online (Sandbox Code Playgroud)
和
import {imports};
public class GuiApp1 extends JFrame {
public Execute() {
getContentPane().setBackground(Color.WHITE);
getContentPane().setLayout(null);
setSize(800, 600);
.............
}
public static void main(String[] args) {
Execute frame1 = new Execute();
frame1.setVisible(true);
}
}
Run Code Online (Sandbox Code Playgroud) 为什么我们需要JFrame在构建Swing应用程序时扩展类.据我所知extends,用于继承基类.JFrame在以下程序中没有使用该类的任何功能,但仍然进行了扩展.我知道我错过了一些信息.是否像JFrame类的一些函数在后台运行.
1)代码
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JOptionPane;
public class tuna extends JFrame{
private JTextField item1;
private JTextField item2;
private JTextField item3;
private JPasswordField passwordField;
Container contentPane ;
public tuna(){
super("The title");
setLayout(new FlowLayout());
item1 = new JTextField(10);
contentPane.add(item1);
item2 = new JTextField("enter text here");
add(item2);
item3 = new JTextField("uneditable", 20);
item3.setEditable(false);
add(item3);
passwordField = new JPasswordField("mypass");
add(passwordField);
thehandler handler = new thehandler();
item1.addActionListener(handler); …Run Code Online (Sandbox Code Playgroud)