📅  最后修改于: 2020-09-29 09:56:21             🧑  作者: Mango
Java Swing教程是Java基础类(JFC)的一部分,用于创建基于窗口的应用程序。它建立在AWT(抽象窗口工具包)API的顶部,并且完全用Java编写。
与AWT不同,Java Swing提供了平台无关的轻量级组件。
javax.swing包提供了Java swing API的类,例如JButton,JTextField,JTextArea,JRadioButton,JCheckbox,JMenu,JColorChooser等。
下面列出了java awt和swing之间的许多区别。
No. | Java AWT | Java Swing |
---|---|---|
1) | AWT components are platform-dependent. | Java swing components are platform-independent. |
2) | AWT components are heavyweight. | Swing components are lightweight. |
3) | AWT doesn’t support pluggable look and feel. | Swing supports pluggable look and feel. |
4) | AWT provides less components than Swing. | Swing provides more powerful components such as tables, lists, scrollpanes, colorchooser, tabbedpane etc. |
5) | AWT doesn’t follows MVC(Model View Controller) where model represents data, view represents presentation and controller acts as an interface between model and view. | Swing follows MVC. |
Java基础类(JFC)是一组GUI组件,可简化桌面应用程序的开发。
Java swing API的层次结构如下。
Component类的方法在java swing中被广泛使用,如下所示。
Method | Description |
---|---|
public void add(Component c) | add a component on another component. |
public void setSize(int width,int height) | sets size of the component. |
public void setLayout(LayoutManager m) | sets the layout manager for the component. |
public void setVisible(boolean b) | sets the visibility of the component. It is by default false. |
有两种创建框架的方法:
我们可以在main(),构造函数或任何其他方法中编写swing代码。
让我们看一个简单的swing示例,其中我们创建一个按钮并将其添加到main()方法内的JFrame对象上。
文件:FirstSwingExample.java
import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButton
b.setBounds(130,100,100, 40);//x axis, y axis, width, height
f.add(b);//adding button in JFrame
f.setSize(400,500);//400 width and 500 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
}
我们还可以在Java构造函数中编写创建JFrame,JButton和方法调用的所有代码。
文件:Simple.java
import javax.swing.*;
public class Simple {
JFrame f;
Simple(){
f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButton
b.setBounds(130,100,100, 40);
f.add(b);//adding button in JFrame
f.setSize(400,500);//400 width and 500 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
public static void main(String[] args) {
new Simple();
}
}
在上面的示例中使用setBounds(int xaxis,int yaxis,int width,int height)设置按钮的位置。
我们还可以继承JFrame类,因此无需显式创建JFrame类的实例。
文件:Simple2.java
import javax.swing.*;
public class Simple2 extends JFrame{//inheriting JFrame
JFrame f;
Simple2(){
JButton b=new JButton("click");//create button
b.setBounds(130,100,100, 40);
add(b);//adding button on frame
setSize(400,500);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
new Simple2();
}}