package com.myth;
import javax.swing.JButton;
import javax.swing.JFrame;public class JFrameExample1 {public static void main(String[] args) {// 主窗体JFrame frmMain = new JFrame("图形界面范例1");// 主窗体设置大小frmMain.setSize(800, 600);// 主窗体设置位置frmMain.setLocation(200, 200);// 主窗体中的组件设置为绝对定位frmMain.setLayout(null);// 按钮组件JButton btnOK = new JButton("按钮");// 同时设置组件的大小和位置btnOK.setBounds(50, 50, 100, 30);// 把按钮加入到主窗体中frmMain.add(btnOK);// 关闭窗体的时候,退出程序frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 让窗体变得可见frmMain.setVisible(true);}
}

JFrame是GUI中的容器
JButton是最常见的组件- 按钮
注意:frmMain.setVisible(true); 会对所有的组件进行渲染,所以一定要放在最后面

Swing 如何进行事件监听

package com.myth;import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;public class JFrameExample2 {public static void main(String[] args) {JFrame frmMain = new JFrame("图形界面范例2");frmMain.setSize(800, 600);frmMain.setLocation(580, 200);frmMain.setLayout(null);final JLabel lblImage = new JLabel();//图片路径从包开始写而绝对路径是无法显示的String path = "com/myth/2.png";  ImageIcon pic = new ImageIcon(ClassLoader.getSystemResource(path));lblImage.setIcon(pic);lblImage.setBounds(50, 50, pic.getIconWidth(), pic.getIconHeight());JButton btnOK = new JButton("隐藏图片");btnOK.setBounds(150, 200, 100, 30);// 给按钮增加监听btnOK.addActionListener(new ActionListener() {// 当按钮被点击时,就会触发ActionEvent事件// actionPerformed方法就会被执行public void actionPerformed(ActionEvent e) {lblImage.setVisible(false);}});frmMain.add(lblImage);frmMain.add(btnOK);frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frmMain.setVisible(true);}
}

创建一个匿名类实现ActionListener接口,当按钮被点击时,actionPerformed方法就会被调用

package com.myth;import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;public class JFrameExample2 {public static void main(String[] args) {JFrame frmMain = new JFrame("图形界面范例2");frmMain.setSize(800, 600);frmMain.setLocation(580, 200);frmMain.setLayout(null);final JLabel lblImage = new JLabel();//图片路径从包开始写而绝对路径是无法显示的String path = "com/myth/2.png";  ImageIcon pic = new ImageIcon(ClassLoader.getSystemResource(path));lblImage.setIcon(pic);lblImage.setBounds(50, 50, pic.getIconWidth(), pic.getIconHeight());// 增加键盘监听frmMain.addKeyListener(new KeyListener() {// 键被弹起public void keyReleased(KeyEvent e) {// 39代表按下了 “箭头右键”if (e.getKeyCode() == 39) {// 图片向右移动 (y坐标不变,x坐标增加)lblImage.setLocation(lblImage.getX() + 10, lblImage.getY());}}//键被按下public void keyPressed(KeyEvent e) {// TODO Auto-generated method stub}// 一个按下弹起的组合动作public void keyTyped(KeyEvent e) {}});frmMain.add(lblImage);frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frmMain.setVisible(true);}
}

键盘监听器: KeyListener
keyPressed 代表 键被按下
keyReleased 代表 键被弹起
keyTyped 代表 一个按下弹起的组合动作
KeyEvent.getKeyCode() 可以获取当前点下了哪个键

package com.myth;import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;public class JFrameExample2 {public static void main(String[] args) {final JFrame frmMain = new JFrame("图形界面范例2");frmMain.setSize(800, 600);frmMain.setLocationRelativeTo(null);frmMain.setLayout(null);final JLabel lblImage = new JLabel();//图片路径从包开始写而绝对路径是无法显示的String path = "com/myth/2.png";  ImageIcon pic = new ImageIcon(ClassLoader.getSystemResource(path));lblImage.setIcon(pic);lblImage.setBounds(375, 275, pic.getIconWidth(), pic.getIconHeight());frmMain.add(lblImage);lblImage.addMouseListener(new MouseListener() {// 释放鼠标public void mouseReleased(MouseEvent e) {// TODO Auto-generated method stub}// 按下鼠标public void mousePressed(MouseEvent e) {// TODO Auto-generated method stub}// 鼠标退出public void mouseExited(MouseEvent e) {// TODO Auto-generated method stub}// 鼠标进入public void mouseEntered(MouseEvent e) {Random rnd = new Random();int x = rnd.nextInt(frmMain.getWidth() - lblImage.getWidth());int y = rnd.nextInt(frmMain.getHeight() - lblImage.getHeight());lblImage.setLocation(x, y);}// 按下释放组合动作为点击鼠标public void mouseClicked(MouseEvent e) {// TODO Auto-generated method stub}});frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frmMain.setVisible(true);}
}

MouseListener 鼠标监听器
mouseReleased 鼠标释放
mousePressed 鼠标按下
mouseExited 鼠标退出
mouseEntered 鼠标进入
mouseClicked 鼠标点击
在本例中,使用mouseEntered,当鼠标进入图片的时候,图片就移动位置

package com.myth;import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;public class JFrameExample2 {public static void main(String[] args) {final JFrame frmMain = new JFrame("图形界面范例2");frmMain.setSize(800, 600);frmMain.setLocationRelativeTo(null);frmMain.setLayout(null);final JLabel lblImage = new JLabel();//图片路径从包开始写而绝对路径是无法显示的String path = "com/myth/2.png";  ImageIcon pic = new ImageIcon(ClassLoader.getSystemResource(path));lblImage.setIcon(pic);lblImage.setBounds(375, 275, pic.getIconWidth(), pic.getIconHeight());frmMain.add(lblImage);// MouseAdapter 适配器,只需要重写用到的方法,没有用到的就不用写了lblImage.addMouseListener(new MouseAdapter() {// 只有mouseEntered用到了public void mouseEntered(MouseEvent e) {Random r = new Random();int x = r.nextInt(frmMain.getWidth() - lblImage.getWidth());int y = r.nextInt(frmMain.getHeight() - lblImage.getHeight());lblImage.setLocation(x, y);}});frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frmMain.setVisible(true);}
}

MouseAdapter 鼠标监听适配器
一般说来在写监听器的时候,会实现MouseListener。
但是MouseListener里面有很多方法实际上都没有用到,比如mouseReleased ,mousePressed,mouseExited等等。
这个时候就可以使用 鼠标监听适配器,MouseAdapter 只需要重写必要的方法即可。

Java的图形界面中,容器是用来存放 按钮,输入框等组件的。
窗体型容器有两个,一个是JFrame,一个是JDialog

package com.myth;import javax.swing.JButton;
import javax.swing.JFrame;public class JFrameExample3 {public static void main(String[] args) {//普通的窗体,带最大和最小化按钮JFrame frmMain = new JFrame("图形界面范例3");frmMain.setSize(400, 300);frmMain.setLocation(200, 200);frmMain.setLayout(null);JButton btnOK = new JButton("按钮");btnOK.setBounds(50, 50, 280, 30);frmMain.add(btnOK);frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frmMain.setVisible(true);}
}

JFrame是最常用的窗体型容器,默认情况下,在右上角有最大化最小化按钮

JDialog也是窗体型容器,右上角没有最大和最小化按钮

package com.myth;import javax.swing.JButton;
import javax.swing.JDialog;public class JFrameExample3 {public static void main(String[] args) {//普通的窗体,带最大和最小化按钮,而对话框却不带JDialog dlgForm = new JDialog();dlgForm.setTitle("图形界面范例3");dlgForm.setSize(400, 300);dlgForm.setLocation(200, 200);dlgForm.setLayout(null);JButton b = new JButton("按钮");b.setBounds(50, 50, 280, 30);dlgForm.add(b);dlgForm.setVisible(true);}
}

模态JDialog

当一个对话框被设置为模态的时候,其背后的父窗体,是不能被激活的,除非该对话框被关闭

package com.myth;import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;public class JFrameExample3 {public static void main(String[] args) {JFrame frmMain = new JFrame("图形界面范例3 外部窗体");frmMain.setSize(800, 600);frmMain.setLocation(100, 100);// 根据外部窗体实例化JDialogJDialog dlgForm = new JDialog(frmMain);// 设置为模态dlgForm.setModal(true);dlgForm.setTitle("模态的对话框");dlgForm.setSize(400, 300);dlgForm.setLocation(200, 200);dlgForm.setLayout(null);JButton btnOK = new JButton("按钮");btnOK.setBounds(50, 50, 280, 30);dlgForm.add(btnOK);frmMain.setVisible(true);dlgForm.setVisible(true);}
}

窗体大小不可变化

通过调用方法 setResizable(false); 做到窗体大小不可变化

package com.myth;import javax.swing.JButton;
import javax.swing.JFrame;public class JFrameExample3 {public static void main(String[] args) {JFrame frmMain = new JFrame("图形界面范例3");frmMain.setSize(400, 300);frmMain.setLocation(200, 200);frmMain.setLayout(null);JButton btnOK = new JButton("按钮");btnOK.setBounds(50, 50, 280, 30);frmMain.add(btnOK);// 窗体大小不可变化frmMain.setResizable(false);frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frmMain.setVisible(true);}
}

图形界面布局

绝对定位就是指不使用布局器,组件的位置和大小需要单独指定

package com.myth;import javax.swing.JButton;
import javax.swing.JFrame;public class JFrameExample4 {
public static void main(String[] args) {JFrame frmMain = new JFrame("图形界面布局范例4");frmMain.setSize(400, 300);frmMain.setLocation(200, 200);// 设置布局器为null,即进行绝对定位,容器上的组件都需要指定位置和大小frmMain.setLayout(null);JButton btn1 = new JButton("按钮1");// 指定位置和大小 btn1.setBounds(x, y, width, height);btn1.setBounds(50, 50, 80, 30);JButton btn2 = new JButton("按钮2");btn2.setBounds(150, 50, 80, 30);JButton btn3 = new JButton("按钮3");btn3.setBounds(250, 50, 80, 30);// 没有指定位置和大小,不会出现在容器上JButton btn4 = new JButton("按钮4");frmMain.add(btn1);frmMain.add(btn2);frmMain.add(btn3);// b4没有指定位置和大小,不会出现在容器上frmMain.add(btn4);frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frmMain.setVisible(true);}
}

设置布局器为FlowLayout,顺序布局器
容器上的组件水平摆放
加入到容器即可,无需单独指定大小和位置

package com.myth;import java.awt.FlowLayout;import javax.swing.JButton;
import javax.swing.JFrame;public class JFrameExample4 {
public static void main(String[] args) {JFrame frmMain = new JFrame("图形界面布局范例4");frmMain.setSize(400, 300);frmMain.setLocation(200, 200);// 设置布局器为FlowLayerout// 容器上的组件水平摆放frmMain.setLayout(new FlowLayout());JButton btnA = new JButton("按钮A");JButton btnB = new JButton("按钮B");JButton btnC = new JButton("按钮C");// 加入到容器即可,无需单独指定大小和位置frmMain.add(btnA);frmMain.add(btnB);frmMain.add(btnC);frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frmMain.setVisible(true);}
}

设置布局器为BorderLayout
容器上的组件按照上北 下南 左西 右东 中的顺序摆放

package com.myth;import java.awt.BorderLayout;import javax.swing.JButton;
import javax.swing.JFrame;public class JFrameExample4 {
public static void main(String[] args) {JFrame frmMain = new JFrame("图形界面布局范例4");frmMain.setSize(400, 300);frmMain.setLocation(200, 200);// 设置布局器为BorderLayerout// 容器上的组件按照上北下南左西右东中的顺序摆放frmMain.setLayout(new BorderLayout());JButton b1 = new JButton("1");JButton b2 = new JButton("2");JButton b3 = new JButton("3");JButton b4 = new JButton("4");JButton b5 = new JButton("5");// 加入到容器的时候,需要指定位置frmMain.add(b1, BorderLayout.NORTH);frmMain.add(b2, BorderLayout.SOUTH);frmMain.add(b3, BorderLayout.WEST);frmMain.add(b4, BorderLayout.EAST);frmMain.add(b5, BorderLayout.CENTER);frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frmMain.setVisible(true);}
}

GridLayout,即网格布局器

package com.myth;import java.awt.GridLayout;import javax.swing.JButton;
import javax.swing.JFrame;public class JFrameExample4 {public static void main(String[] args) {JFrame frmMain = new JFrame("图形界面布局范例4");frmMain.setSize(400, 300);frmMain.setLocation(200, 200);// 设置布局器为GridLayerout,即网格布局器// 该GridLayerout的构造方法表示该网格是2行3列frmMain.setLayout(new GridLayout(2, 3));JButton b1 = new JButton("1");JButton b2 = new JButton("2");JButton b3 = new JButton("3");JButton b4 = new JButton("4");JButton b5 = new JButton("5");frmMain.add(b1);frmMain.add(b2);frmMain.add(b3);frmMain.add(b4);frmMain.add(b5);frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frmMain.setVisible(true);}
}

即便 使用 布局器 ,也可以 通过setPreferredSize,向布局器建议该组件显示的大小.
注 只对部分布局器起作用,比如FlowLayout可以起作用。 比如GridLayout就不起作用,因为网格布局器必须对齐

package com.myth;import java.awt.Dimension;
import java.awt.FlowLayout;import javax.swing.JButton;
import javax.swing.JFrame;public class JFrameExample4 {public static void main(String[] args) {JFrame frmMain = new JFrame("图形界面布局范例4");frmMain.setSize(400, 300);frmMain.setLocation(200, 200);frmMain.setLayout(new FlowLayout());JButton b1 = new JButton("按钮1");JButton b2 = new JButton("按钮2");JButton b3 = new JButton("按钮3");// 即便使用布局器 ,也可以通过setPreferredSize,向布局器建议该组件显示的大小b3.setPreferredSize(new Dimension(180, 40));frmMain.add(b1);frmMain.add(b2);frmMain.add(b3);frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frmMain.setVisible(true);}
}

package com.myth;import java.awt.Color;import javax.swing.JFrame;
import javax.swing.JLabel;public class JFrameExample4 {public static void main(String[] args) {JFrame frmMain = new JFrame("图形界面范例 - 标签");frmMain.setSize(400, 300);frmMain.setLocation(200, 200);frmMain.setLayout(null);JLabel lbl1 = new JLabel("用户姓名:");//文字颜色lbl1.setForeground(Color.red);lbl1.setBounds(50, 50, 280, 30);frmMain.add(lbl1);frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frmMain.setVisible(true);}
}

JCheckBox 复选框

使用isSelected来获取是否选中了

package com.myth;import javax.swing.JCheckBox;
import javax.swing.JFrame;public class JFrameExample4 {
public static void main(String[] args) {JFrame frmMain = new JFrame("图形界面范例 - 复选框");frmMain.setSize(400, 300);frmMain.setLocation(580, 200);frmMain.setLayout(null);JCheckBox chkItem1 = new JCheckBox("启用第一项");//设置 为 默认被选中chkItem1.setSelected(true);chkItem1.setBounds(50, 50, 130, 30);JCheckBox chkItem2 = new JCheckBox("启用第二项");chkItem2.setBounds(50, 100, 130, 30);//判断 是否 被 选中System.out.println(chkItem2.isSelected());frmMain.add(chkItem1);frmMain.add(chkItem2);frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frmMain.setVisible(true);}
}

JRadioButton 单选框
使用isSelected来获取是否选中了

在这个例子里,两个单选框可以被同时选中,为了实现只能选中一个,还需要用到ButtonGroup

package com.myth;import javax.swing.JFrame;
import javax.swing.JRadioButton;public class JFrameExample4 {public static void main(String[] args) {JFrame frmMain = new JFrame("图形界面范例 - 单选框");frmMain.setSize(400, 300);frmMain.setLocation(580, 200);frmMain.setLayout(null);JRadioButton rbt1 = new JRadioButton("第1项");// 设置 为 默认被选中rbt1.setSelected(true);rbt1.setBounds(50, 50, 130, 30);JRadioButton rbt2 = new JRadioButton("第2项");rbt2.setBounds(50, 100, 130, 30);System.out.println(rbt2.isSelected());frmMain.add(rbt1);frmMain.add(rbt2);frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frmMain.setVisible(true);}
}

ButtonGroup 对按钮进行分组,把不同的按钮,放在同一个分组里 ,同一时间,只有一个 按钮 会被选中

package com.myth;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JRadioButton;public class JFrameExample4 {public static void main(String[] args) {JFrame frmMain = new JFrame("图形界面范例 - 按钮组");frmMain.setSize(400, 300);frmMain.setLocation(580, 240);frmMain.setLayout(null);JRadioButton b1 = new JRadioButton("按钮组第一项");b1.setSelected(true);b1.setBounds(50, 50, 130, 30);JRadioButton b2 = new JRadioButton("按钮组第二项");b2.setBounds(50, 100, 130, 30);// 按钮分组ButtonGroup btng = new ButtonGroup();// 把b1,b2放在同一个按钮分组对象里 ,这样同一时间只有一个按钮会被选中btng.add(b1);btng.add(b2);frmMain.add(b1);frmMain.add(b2);frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frmMain.setVisible(true);}
}

JComboBox 下拉框
使用getSelectedItem来获取被选中项
使用setSelectedItem() 来指定要选中项

package com.myth;
import javax.swing.JComboBox;
import javax.swing.JFrame;public class JFrameExample4 {public static void main(String[] args) {JFrame frmMain = new JFrame("图形界面范例 - 下拉框");frmMain.setSize(400, 300);frmMain.setLocation(580, 240);frmMain.setLayout(null);//下拉框出现的条目String[] fruits = new String[] { "苹果", "香蕉" };JComboBox cmbFruits = new JComboBox(fruits);cmbFruits.setBounds(50, 50, 80, 30);frmMain.add(cmbFruits);frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frmMain.setVisible(true);}
}

JOptionPane 用于弹出对话框

JOptionPane.showConfirmDialog(f, "是否 使用外挂 ?");
表示询问,第一个参数是该对话框以哪个组件对齐
JOptionPane.showInputDialog(f, "请输入yes,表明使用外挂后果自负");
接受用户的输入
JOptionPane.showMessageDialog(f, "你使用外挂被抓住! 罚拣肥皂3次!");
显示消息

package com.myth;
import javax.swing.JFrame;
import javax.swing.JOptionPane;public class JFrameExample4 {public static void main(String[] args) {JFrame frmMain = new JFrame("图形界面范例 - 弹出对话框显示消息");frmMain.setSize(400, 300);frmMain.setLocation(580, 240);frmMain.setLayout(null);frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frmMain.setVisible(true);int option = JOptionPane.showConfirmDialog(frmMain, "您确定要这么做吗?");if (JOptionPane.OK_OPTION == option) {String answer = JOptionPane.showInputDialog(frmMain, "输入yes进入分支流程");if ("yes".equals(answer))JOptionPane.showMessageDialog(frmMain, "您已进入分支流程!");}}
}

JTextField 输入框
setText 设置文本
getText 获取文本
JTextField 是单行文本框,如果要输入多行数据,请使用JTextArea

txtPassword.grabFocus(); 表示让密码输入框获取焦点

package com.myth;
import java.awt.Dimension;
import java.awt.FlowLayout;import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;public class JFrameExample4 {public static void main(String[] args) {JFrame frmMain = new JFrame("图形界面范例 - 文本框");frmMain.setSize(400, 300);frmMain.setLocation(200, 200);frmMain.setLayout(new FlowLayout());JLabel lblName = new JLabel("用户名称:");// 输入框JTextField txtName = new JTextField("");txtName.setText("请输入账号");txtName.setPreferredSize(new Dimension(80, 30));JLabel lblPassword = new JLabel("用户密码:");// 输入框JTextField txtPassword = new JTextField("");txtPassword.setText("请输入密码");txtPassword.setPreferredSize(new Dimension(80, 30));frmMain.add(lblName);frmMain.add(txtName);frmMain.add(lblPassword);frmMain.add(txtPassword);frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frmMain.setVisible(true);txtPassword.grabFocus();}
}

JPasswordField 密码框
与文本框不同,获取密码框里的内容,推荐使用getPassword,该方法会返回一个字符数组,而非字符串

package com.myth;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;public class JFrameExample4 {public static void main(String[] args) {JFrame frmMain = new JFrame("图形界面范例 - 密码框");frmMain.setSize(400, 300);frmMain.setLocation(200, 200);frmMain.setLayout(new FlowLayout());JLabel lblPassword = new JLabel("密码:");// 密码框JPasswordField txtPassword = new JPasswordField("");txtPassword.setText("123456");txtPassword.setPreferredSize(new Dimension(80, 30));// 与文本框不同,获取密码框里的内容,推荐使用getPassword,该方法会返回一个字符数组,而非字符串char[] charPass = txtPassword.getPassword();String pass = String.valueOf(charPass);System.out.println(pass);frmMain.add(lblPassword);frmMain.add(txtPassword);frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frmMain.setVisible(true);}
}

JTextArea:文本域。
和文本框JTextField不同的是,文本域可以输入多行数据
如果要给文本域初始文本,通过\n来实现换行效果
JTextArea通常会用到append来进行数据追加
如果文本太长,会跑出去,可以通过setLineWrap(true) 来做到自动换行

package com.myth;
import java.awt.Dimension;
import java.awt.FlowLayout;import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;public class JFrameExample4 {public static void main(String[] args) {JFrame frmMain = new JFrame("图形界面范例 - 文本域");frmMain.setSize(400, 300);frmMain.setLocation(200, 200);frmMain.setLayout(new FlowLayout());JTextArea txtAreaContent = new JTextArea();txtAreaContent.setPreferredSize(new Dimension(300, 150));//\n换行符txtAreaContent.setText("默认行\n");//追加数据txtAreaContent.append("追加行\n");//设置自动换行txtAreaContent.setLineWrap(true);frmMain.add(lblSubject);frmMain.add(txtAreaContent);frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frmMain.setVisible(true);}
}
package com.myth;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JProgressBar;public class JFrameExample4 {
public static void main(String[] args) {JFrame frmMain = new JFrame("图形界面范例 - 进度条");frmMain.setSize(400, 300);frmMain.setLocation(200, 200);frmMain.setLayout(new FlowLayout());JProgressBar progressBar = new JProgressBar();//进度条最大100progressBar.setMaximum(100);//当前进度是50progressBar.setValue(50);//显示当前进度progressBar.setStringPainted(true);frmMain.add(progressBar);frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frmMain.setVisible(true);}
}

JFileChooser 表示文件选择器
使用FileFilter用于仅选择文件类型

package com.myth;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;public class JFrameExample4 {public static void main(String[] args) {JFrame frmMain = new JFrame("图形界面范例 - 文件选择器");frmMain.setLayout(new FlowLayout());JFileChooser fileChooser = new JFileChooser();fileChooser.setFileFilter(new FileFilter() {@Overridepublic String getDescription() {// TODO Auto-generated method stubreturn ".txt";}@Overridepublic boolean accept(File file) {return file.getName().toLowerCase().endsWith(".txt");}});JButton btnOpen = new JButton("打开文件");JButton btnSave = new JButton("保存文件");frmMain.add(btnOpen);frmMain.add(btnSave);frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frmMain.setSize(400, 300);frmMain.setLocationRelativeTo(null);frmMain.setVisible(true);btnOpen.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {int returnVal =  fileChooser.showOpenDialog(frmMain);File file = fileChooser.getSelectedFile();if (returnVal == JFileChooser.APPROVE_OPTION) {JOptionPane.showMessageDialog(frmMain, "计划打开文件:" + file.getAbsolutePath());}}});btnSave.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {int returnVal =  fileChooser.showSaveDialog(frmMain);File file = fileChooser.getSelectedFile();if (returnVal == JFileChooser.APPROVE_OPTION) {JOptionPane.showMessageDialog(frmMain, "计划保存到文件:" + file.getAbsolutePath());}}});}
}

JPanel即为基本面板
面板和JFrame一样都是容器,不过面板一般用来充当中间容器,把组件放在面板上,然后再把面板放在窗体上
一旦移动一个面板,其上面的组件,就会全部统一跟着移动,采用这种方式,便于进行整体界面的设计

package com.myth;
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;public class JFrameExample4 {public static void main(String[] args) {JFrame frmMain = new JFrame("图形界面范例 - 基本面板");frmMain.setSize(400, 300);frmMain.setLocation(200, 200);frmMain.setLayout(null);JPanel p1 = new JPanel();// 设置面板大小p1.setBounds(50, 50, 300, 60);// 设置面板背景颜色p1.setBackground(Color.RED);// 这一句可以没有,因为JPanel默认就是采用的FlowLayoutp1.setLayout(new FlowLayout());JButton b1 = new JButton("按钮1");JButton b2 = new JButton("按钮2");JButton b3 = new JButton("按钮3");// 把按钮加入面板p1.add(b1);p1.add(b2);p1.add(b3);JPanel p2 = new JPanel();JButton b4 = new JButton("按钮4");JButton b5 = new JButton("按钮5");JButton b6 = new JButton("按钮6");p2.add(b4);p2.add(b5);p2.add(b6);p2.setBackground(Color.BLUE);p2.setBounds(10, 150, 300, 60);// 把面板加入窗口frmMain.add(p1);frmMain.add(p2);frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frmMain.setVisible(true);}
}

JFrame上有一层面板,叫做ContentPane
平时通过frmMain.add()向JFrame增加组件,其实是向JFrame上的 ContentPane加东西

package com.myth;
import javax.swing.JButton;
import javax.swing.JFrame;public class JFrameExample4 {public static void main(String[] args) {JFrame frmMain = new JFrame("图形界面范例 - JFrame上集成的默认面板ContentPane");frmMain.setSize(600, 300);frmMain.setLocation(200, 200);frmMain.setLayout(null);JButton btnOK = new JButton("按钮");btnOK.setBounds(50, 50, 280, 30);frmMain.add(btnOK);// JFrame上有一层面板,叫做ContentPane// 平时通过frmMain.add()向JFrame增加组件,其实是向JFrame上的 ContentPane加东西// frmMain.add等同于frmMain.getContentPane().add(btnOK);frmMain.getContentPane().add(btnOK);// btnOK.getParent()获取按钮btnOK所处于的容器// 打印出来可以看到,实际上是ContentPane而非JFrameSystem.out.println(btnOK.getParent());frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frmMain.setVisible(true);}
}

创建一个水平JSplitPane,左边是pLeft,右边是pRight

package com.myth;
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSplitPane;public class JFrameExample4 {
public static void main(String[] args) {JFrame frmMain = new JFrame("图形界面范例 - JSplitPane面板");frmMain.setSize(400, 300);frmMain.setLocation(200, 200);frmMain.setLayout(null);JPanel pLeft = new JPanel();pLeft.setBounds(50, 50, 300, 60);pLeft.setBackground(Color.RED);pLeft.setLayout(new FlowLayout());JButton b1 = new JButton("按钮1");JButton b2 = new JButton("按钮2");JButton b3 = new JButton("按钮3");pLeft.add(b1);pLeft.add(b2);pLeft.add(b3);JPanel pRight = new JPanel();JButton b4 = new JButton("按钮4");JButton b5 = new JButton("按钮5");JButton b6 = new JButton("按钮6");pRight.add(b4);pRight.add(b5);pRight.add(b6);pRight.setBackground(Color.BLUE);pRight.setBounds(10, 150, 300, 60);// 创建一个水平JSplitPane,左边是p1,右边是p2JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, pLeft, pRight);// 设置分割条的位置sp.setDividerLocation(80);// 把sp当作ContentPanefrmMain.setContentPane(sp);frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frmMain.setVisible(true);}
}

使用带滚动条的面板有两种方式
1. 在创建JScrollPane,把组件作为参数传进去

JScrollPane sp = new JScrollPane(ta);
2. 希望带滚动条的面板显示其他组件的时候,调用setViewportView

sp.setViewportView(ta);

package com.myth;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;public class JFrameExample4 {
public static void main(String[] args) {JFrame frmMain = new JFrame("图形界面范例 - 带滚动条的面板");frmMain.setSize(400, 300);frmMain.setLocation(200, 200);frmMain.setLayout(null);//准备一个文本域,在里面放很多数据JTextArea ta = new JTextArea();for (int i = 0; i < 1000; i++) {ta.append(String.valueOf(i));}//自动换行ta.setLineWrap(true);JScrollPane sp = new JScrollPane(ta);frmMain.setContentPane(sp);frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frmMain.setVisible(true);}
}
package com.myth;
import java.awt.Color;
import java.awt.FlowLayout;import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;public class JFrameExample4 {
public static void main(String[] args) {JFrame frmMain = new JFrame("图形界面范例 - TabbedPanel面板");frmMain.setSize(400, 300);frmMain.setLocation(200, 200);frmMain.setLayout(null);JPanel p1 = new JPanel();p1.setBounds(50, 50, 300, 60);p1.setBackground(Color.RED);p1.setLayout(new FlowLayout());JButton b1 = new JButton("按钮1");JButton b2 = new JButton("按钮2");JButton b3 = new JButton("按钮3");p1.add(b1);p1.add(b2);p1.add(b3);JPanel p2 = new JPanel();JButton b4 = new JButton("按钮4");JButton b5 = new JButton("按钮5");JButton b6 = new JButton("按钮6");p2.add(b4);p2.add(b5);p2.add(b6);p2.setBackground(Color.BLUE);p2.setBounds(10, 150, 300, 60);JTabbedPane tp = new JTabbedPane();tp.add(p1);tp.add(p2);// 设置tab的标题tp.setTitleAt(0, "红色tab");tp.setTitleAt(1, "蓝色tab");//图片路径从包开始写而绝对路径是无法显示的//String path = "com/myth/2.png";  //ImageIcon pic = new ImageIcon(ClassLoader.getSystemResource(path));//tp.setIconAt(0,pic);//tp.setIconAt(1,pic);frmMain.setContentPane(tp);frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frmMain.setVisible(true);}
}

CardLayerout 布局器 很像TabbedPanel ,在本例里面上面是一个下拉框,下面是一个CardLayerout 的JPanel
这个JPanel里有两个面板,可以通过CardLayerout方便的切换

package com.myth;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;public class JFrameExample4 {
public static void main(String[] args) {JFrame frmMain = new JFrame("图形界面范例 - CardLayerout布局器");JPanel comboBoxPane = new JPanel();String buttonPanel = "按钮面板";String inputPanel = "输入框面板";String items[] = { buttonPanel, inputPanel };JComboBox<String> comboBox = new JComboBox<>(items);comboBoxPane.add(comboBox);// 两个Panel充当卡片JPanel p1 = new JPanel();p1.add(new JButton("按钮 1"));p1.add(new JButton("按钮 2"));p1.add(new JButton("按钮 3"));JPanel p2 = new JPanel();p2.add(new JTextField("输入框", 20));JPanel p; // a panel that uses CardLayoutp = new JPanel(new CardLayout());p.add(p1, buttonPanel);p.add(p2, inputPanel);frmMain.add(comboBoxPane, BorderLayout.NORTH);frmMain.add(p, BorderLayout.CENTER);frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frmMain.setSize(400, 300);frmMain.setLocationRelativeTo(null);frmMain.setVisible(true);comboBox.addItemListener(new ItemListener() {@Overridepublic void itemStateChanged(ItemEvent e) {CardLayout cardLayout = (CardLayout) (p.getLayout());cardLayout.show(p, (String) e.getItem());}});    }
}

/** To change this license header, choose License Headers in Project Properties.* To change this template file, choose Tools | Templates* and open the template in the editor.*/
package com.myth;
import java.awt.*;
import javax.swing.*;public class MSCommDemo  {public static void main(String[] agrs) {// 主窗体JFrame frmMain = new JFrame("图形界面 - 串口通讯范例1");// 主窗体设置大小frmMain.setSize(1100, 560);// 主窗体设置位置frmMain.setLocation(200, 200);String[] port = {"COM1", "COM2", "CO3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9"};String[] baud = {"2400", "4800", "9600", "115200", "384000"};String[] data = {"6", "7", "8"};String[] xor = {"0", "1", "2"};String[] stop = {"0", "1", "1.5", "2"};//定义标签JLabel lblPort = new JLabel("端口号:");JLabel lblBaud = new JLabel("波特率:");JLabel lblData = new JLabel("数据位:");JLabel lblXor = new JLabel("校验位:");JLabel lblStop = new JLabel("停止位:");lblPort.setHorizontalAlignment(SwingConstants.RIGHT);lblBaud.setHorizontalAlignment(SwingConstants.RIGHT);lblData.setHorizontalAlignment(SwingConstants.RIGHT);lblXor.setHorizontalAlignment(SwingConstants.RIGHT);lblStop.setHorizontalAlignment(SwingConstants.RIGHT);//定义下拉列表框JComboBox cmbPort = new JComboBox(port);JComboBox cmbBaud = new JComboBox(baud);JComboBox cmbData = new JComboBox(data);JComboBox cmbXor = new JComboBox(xor);JComboBox cmbStop = new JComboBox(stop);//定义面板//将北部面板定义为网格布局为1行1列JPanel north = new JPanel();north.setLayout(new GridLayout(1, 1));//将定义左边的面板为网格布局为3行2列JPanel left = new JPanel();left.setOpaque(false);left.setLayout(new GridLayout(3, 2));//定义流布局1 FlowLayout.LEFT ——组件的左对齐方式组件的水平间距为10像素,垂直间距为5像素JPanel leftPane1 = new JPanel();leftPane1.setBackground(Color.RED);leftPane1.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 5));leftPane1.add(lblPort);leftPane1.add(cmbPort);//定义流布局2JPanel leftPane2 = new JPanel();leftPane2.setBackground(Color.GREEN);leftPane2.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 5));leftPane2.add(lblBaud);leftPane2.add(cmbBaud);//定义流布局3JPanel leftPane3 = new JPanel();leftPane3.setBackground(Color.YELLOW);leftPane3.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 5));leftPane3.add(lblData);leftPane3.add(cmbData);//将3个流布局的面板,添加到3*2网格布局面板上left.add(leftPane1);left.add(leftPane2);left.add(leftPane3);//定义右边的面板为网格布局为3行2列JPanel right = new JPanel();right.setBackground(Color.YELLOW);right.setOpaque(false);right.setLayout(new GridLayout(3, 2));//定义流布局1JPanel rightPane1 = new JPanel();rightPane1.setBackground(Color.YELLOW);rightPane1.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));rightPane1.add(lblXor);rightPane1.add(cmbXor);//定义流布2JPanel rightPane2 = new JPanel();rightPane2.setBackground(Color.RED);rightPane2.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));rightPane2.add(lblStop);rightPane2.add(cmbStop);//定义流布局3JPanel rightPane3 = new JPanel();rightPane3.setBackground(Color.GREEN);rightPane2.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));JButton btnOpen = new JButton("打开端口");JButton btnClose = new JButton("关闭端口");rightPane3.add(btnOpen);rightPane3.add(btnClose);//添加三个流布局面板到3*2网络面板上right.add(rightPane1);right.add(rightPane2);right.add(rightPane3);//将左右面板添加到北边的面板上north.add(left);north.add(right);//设置中间面板各组件JPanel center = new JPanel();center.setOpaque(false);center.setLayout(new GridLayout(2, 2));//定义流布局面板1JPanel centerPane1 = new JPanel();centerPane1.setBackground(Color.PINK);centerPane1.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 5));JTextField txtSend = new JTextField(90);JLabel lblSend = new JLabel("发送数据:");centerPane1.add(lblSend);centerPane1.add(txtSend);//定义流布局面板2JPanel centerPane2 = new JPanel();centerPane2.setBackground(Color.ORANGE);centerPane2.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 5));//创建一个20行90列的文本区域JTextArea txaRevied = new JTextArea(10,90);txaRevied.setLineWrap(true);    //设置多行文本框自动换行//txaRevied.setEditable(false);txaRevied.setBackground(new Color(255, 255, 255));JScrollPane scrollPane = new JScrollPane(txaRevied); JLabel lblRevied = new JLabel("接收数据:");centerPane2.add(lblRevied);centerPane2.add(scrollPane);center.add(centerPane1);center.add(centerPane2);//底部布局JPanel south = new JPanel();south.setLayout(new GridLayout(1, 2));south.setOpaque(false);//底部流布局JPanel southPane = new JPanel();southPane.setBackground(Color.CYAN);southPane.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));JButton btnOK = new JButton("确认");JButton btnExit = new JButton("退出");southPane.add(btnOK);southPane.add(btnExit);south.add(southPane);frmMain.setLayout(new BorderLayout());frmMain.add(north, BorderLayout.NORTH);frmMain.add(center, BorderLayout.CENTER);frmMain.add(south, BorderLayout.SOUTH);// 关闭窗体的时候,退出程序frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 让窗体变得可见frmMain.setVisible(true);}}

Java/Swing 图形界面范例相关推荐

  1. java swing图形界面开发 java.swing简介

    最近在看YouTube上面的视频的时候,虽然学着做了一点界面和一点可以运行的东西,但是里面用到的库文件我还是不明就里的.所以我打算在制作游戏之前,先花几天的时间大概地研究一下关于java.swing的 ...

  2. java swing 案例详解_《Java Swing图形界面开发与案例详解》PDF_IT教程网

    资源名称:<Java Swing图形界面开发与案例详解>PDF 内容简介: <Java Swing图形界面开发与案例详解>全书共20章,其中第1-2章主要介绍有关Swing的基 ...

  3. java swing 目录,java swing图形界面开发目录

    java swing图形界面开发目录,做swing图形开发要学习哪些知识,难不难呢?请看以下的目录你就知道要学习哪些了: 目录 第1章 Java Swing概述 1 1.1 什么是Java Swing ...

  4. Java Swing 图形界面开发(目录)

    本文链接: https://blog.csdn.net/xietansheng/article/details/72814492 0. JavaSwing 简介 Java Swing 图形界面开发简介 ...

  5. Java Swing 图形界面开发总结(完整版)

    最近在学习Java图像处理,发现还有好多不清除的知识点,在CSDN上查了好久,找到一篇前辈整理的关于Java Swing 图形界面开发的文章,感觉对自己的帮助非常大,在这里转载推荐一下,和大家一起学习 ...

  6. Java Swing 图形界面开发教程(目录)

    参考文章:Java Swing 图形界面开发(目录) 0. JavaSwing 简介 Java Swing 图形界面开发简介 1. JavaSwing 布局管理器 avaSwing_1.1: Flow ...

  7. java swing图形界面开发设计器windowbuilder安装步骤详解

    前言 WindowBuilder 是java swing的一款图形界面开发设计器,他可以大大增加开发项目的速度,对于eclipse这款开发工具,他是没有提供windowbuilder设计器的,如果要使 ...

  8. java swing图形界面开发与案例详解source code

    http://code1.okbase.net/codefile/mainframe.java_2012122219034_53.htm

  9. java swing 示例_JAVA简单Swing图形界面应用演示样例

    JAVA简单Swing图形界面应用演示样例 package org.rui.hello; import javax.swing.JFrame; /** * 简单的swing窗体 * @author l ...

最新文章

  1. 【腾讯面试题】SQL语句优化方法有哪些?
  2. ReviewForJob(2)算法分析
  3. Spring框架中的内容协商
  4. 【转】java字符串池和字符串堆内存分配
  5. Redis+Keepalived内存数据库集群配置
  6. html怎么用div从左到右,单独使用CSS,你怎么能有一个从右到左的边框底部渐变?...
  7. html修改颜色的代码大全,html代码大全(基础使用代码)(颜色代码完整版)
  8. 对数log、lg、ln
  9. 学习笔记 | 假设检验概念、小概率事件、P-Value与显著性水平、假设检验步骤
  10. 植物大战僵尸修改植物攻击力
  11. excel中使用VBA如何统计数据区域最后一行行号?
  12. 如何做产品的品牌推广?怎么推广自己的产品?品牌推广怎样做更好
  13. B站视频内容复利,品牌投放中小UP主的营销机遇在哪?
  14. 大数据学习——相关资源
  15. python积木编程软件下载_积木编程软件-积木编程官方版下载-红软网
  16. python scipy.stats.norm.cdf_python scipy stats.norm用法及代码示例
  17. Java基础(扩充中...)
  18. 新世纪福音战士剧场版破
  19. java new short_Java中的Java.Lang.Short类 - Break易站
  20. 博途v15模拟量转换_基于博途V15 西门子S7-1200 + 模拟量SM 1234 正反转变频调速实例...

热门文章

  1. 国密SM2前端加密,Java后台解密问题
  2. RVIZ界面没有显示joint publishe的GUI界面解决方法
  3. 江民杀毒 90天试用序列号申请
  4. Cisco交换机端口假死(err-disable)解决方法
  5. pandas获取数据集数据类型分布(更细粒度的分割)
  6. 73、Spark SQL之开窗函数以及top3销售额统计案例实战
  7. 2023年美赛ICM问题E:光污染 这题很好做啊!
  8. 如何实现与Teamcenter PLM单点登录(SSO)
  9. ADO 驱动 Microsoft Data Access Components (MDAC) 2.8 SP1
  10. 考注会会经常用计算机吗,注会机考系统计算器你会用吗?操作技巧抢先看!