当提到Java时,让我一天天的待在教室里学习的就是当学习到GUI的时候,因为终于不只在控制台活动啦,终于可以用户交互啦,话不多说,直接开始。
先上图
如上图,是一些常用的组件,还有一个重要的组成部分为布局,我的习惯是先布局后加组件。
给大家介绍一些常用的,JFrame这个组件叫做窗体所有的交互都从这开始,一般在上边放置布局或者面板,JPanel叫做面板主要是在上边放置各种组件包括布局。
下面用两个小例子(阅读器)给大家介绍一下GUI
先上图
上代码
import javax.swing.*; import javax.swing.event.MenuEvent; import javax.swing.event.MenuListener; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.*; import java.util.ArrayList; /** * Created by lenovo on 2017/10/18. */ public class GUITest { //记录当前页 private static int nowPage = 1; private static double WIDTH = 0; private static double HEIGHT = 0; private static String article = ""; //每页字数为1428 private static int pageSize = 1428; //获得页数 private static int maxPageNumber = 0; //文字显示 private static JLabel right = null; //打开的窗体的集合 private static java.util.List
jDialogs = null; public static void main(String args[]) { jDialogs = new ArrayList<>(); //获得屏幕的宽高 Toolkit toolkit = Toolkit.getDefaultToolkit(); WIDTH = toolkit.getScreenSize().getWidth(); HEIGHT = toolkit.getScreenSize().getHeight(); JFrame jFrame = new JFrame("GUI测试"); JMenuBar jMenuBar = new JMenuBar(); JMenu jMenu1 = new JMenu("目录选取文件"); jMenu1.addMenuListener(new MenuListener() { @Override public void menuSelected(MenuEvent e) { File[] files = getRootFir(); showDialog(files); } @Override public void menuDeselected(MenuEvent e) { } @Override public void menuCanceled(MenuEvent e) { } }); JMenu jMenu2 = new JMenu("输入目录选取文件"); jMenu2.addMenuListener(new MenuListener() { @Override public void menuSelected(MenuEvent e) { JDialog jDialog = new JDialog(); //面板容器 Panel panel = new Panel(); panel.setLayout(new FlowLayout()); //存放路径的文本框 JTextArea jtext = new JTextArea(1, 50); panel.add(jtext); //搜索 JButton jBtn = new JButton("打开"); jBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //开始阅读 try { File file = new File(jtext.getText()); String fileName = file.getName(); String fileType = fileName.substring(fileName.indexOf('.') + 1, fileName.length()); if (fileType.equals("txt")) { article = getText(file); maxPageNumber = article.length() / pageSize + (article.length() % pageSize == 0 ? 0 : 1); right.setText("" + article.substring(0, pageSize > article.length() ? article.length() : pageSize) + ""); nowPage = 1; jDialog.dispose(); //关闭打开的窗体 for (int i = 0; i < jDialogs.size(); i++) { jDialogs.get(i).dispose(); } } else { jtext.setText("没有找到该文件"); } } catch (Exception ex) { jtext.setText("没有找到该文件"); } } }); panel.add(jBtn); jDialog.add(panel); //使窗口成为最佳大小 jDialog.pack(); //使窗体位于屏幕中央 int x = (int) (WIDTH - jDialog.getWidth()) / 2; int y = (int) (HEIGHT - jDialog.getHeight()) / 2; //设置窗体位置 jDialog.setLocation(x, y); //设置窗体可见 jDialog.setVisible(true); //设置窗体在最前边 jDialog.setAlwaysOnTop(true); } @Override public void menuDeselected(MenuEvent e) { } @Override public void menuCanceled(MenuEvent e) { } }); jMenuBar.add(jMenu1); jMenuBar.add(jMenu2); jFrame.setJMenuBar(jMenuBar); //创建布局 BorderLayout borderLayout = new BorderLayout(); //给窗体设置布局 jFrame.setLayout(borderLayout); //设置窗体可见 jFrame.setVisible(true); //功能模块 Panel type = new Panel(); //Dimension的作用是随着窗口的大小改变type会跟着变 type.setPreferredSize(new Dimension(150, 800)); JButton yjms = new JButton("夜间模式"); yjms.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { type.setBackground(Color.BLACK); type.setForeground(Color.WHITE); right.setBackground(Color.BLACK); right.setForeground(Color.WHITE); } }); type.add(yjms); JButton moms = new JButton("默认模式"); moms.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { type.setBackground(Color.WHITE); type.setForeground(Color.BLACK); right.setBackground(Color.WHITE); right.setForeground(Color.BLACK); } }); type.add(moms); jFrame.add(type, BorderLayout.WEST); Panel content = new Panel(); content.setLayout(new BorderLayout()); right = new JLabel("欢迎来到Java简易阅读室,希望大家在这里能为自己的梦想插上一双翅膀!!!"); right.setFont(new Font("Dialog", 1, 15)); content.add(right, BorderLayout.CENTER); Panel pageNumber = new Panel(); JTextArea jTextArea = new JTextArea(); jTextArea.setColumns(5); JButton syy = new JButton("上一页"); syy.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { nowPage--; if (nowPage > 0) right.setText("" + article.substring((nowPage - 1) * pageSize, nowPage * pageSize) + ""); else nowPage = 1; } }); pageNumber.add(syy); JButton xyy = new JButton("下一页"); xyy.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { nowPage++; if (nowPage <= maxPageNumber) right.setText("" + article.substring((nowPage - 1) * pageSize, (nowPage * pageSize) >= article.length() ? article.length() : (nowPage * pageSize)) + ""); else nowPage = maxPageNumber; } }); pageNumber.add(xyy); pageNumber.add(jTextArea); JButton ym = new JButton("跳转"); ym.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { int newPager = Integer.parseInt(jTextArea.getText().trim()); if (newPager > 0 && newPager <= maxPageNumber) { nowPage = Integer.parseInt(jTextArea.getText().trim()); right.setText("" + article.substring((nowPage - 1) * pageSize, (nowPage * pageSize) >= article.length() ? article.length() : (nowPage * pageSize)) + ""); } else { System.out.print("输入范围有误"); } } }); pageNumber.add(ym); content.add(pageNumber, BorderLayout.SOUTH); jFrame.add(content, BorderLayout.CENTER); //使窗口成为最佳大小 jFrame.pack(); //设置窗体大小 jFrame.setSize(800, 800); //使窗体位于屏幕中央 // jFrame.setLocationRelativeTo(null); //使窗体位于屏幕中央 int x = (int) (WIDTH - jFrame.getWidth()) / 2; int y = (int) (HEIGHT - jFrame.getHeight()) / 2; // //设置窗体位置 jFrame.setLocation(x, y); //窗口大小不可调 jFrame.setResizable(false); } private static void showDialog(File[] files) { JDialog jDialog = new JDialog(); int len = 0; for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { len++; } else if (files[i].isFile()) { String fileName = files[i].getName(); String fileType = fileName.substring(fileName.indexOf('.') + 1, fileName.length()); if (fileType.equals("txt")) len++; } } jDialog.setLayout(new GridLayout(len, 1)); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) jDialog.add(getJButton(files[i], true)); } for (int i = 0; i < files.length; i++) { //只显示txt类型的文件 if (files[i].isFile()) { String fileName = files[i].getName(); String fileType = fileName.substring(fileName.indexOf('.') + 1, fileName.length()); if (fileType.equals("txt")) jDialog.add(getJButton(files[i], false)); } } //使窗口成为最佳大小 jDialog.pack(); //使窗体位于屏幕中央 int x = (int) (WIDTH - jDialog.getWidth()) / 2; int y = (int) (HEIGHT - jDialog.getHeight()) / 2; //设置窗体位置 jDialog.setLocation(x, y); //设置窗体可见 jDialog.setVisible(true); //设置窗体在最前边 jDialog.setAlwaysOnTop(true); //将打开的窗体放入集合中 jDialogs.add(jDialog); } //读取文件中的文字 public static String getText(File file) { // java.util.List lines = new ArrayList<>(); // try { // BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8")); // String line = null; // while ((line = br.readLine()) != null) { // lines.add(line); // } // br.close(); // System.out.print(lines.get(0)); // return lines.get(0); // } catch (Exception e) { // } // return ""; try { FileReader fileReader = new FileReader(file); StringBuffer stringBuffer = new StringBuffer(); char[] c = new char[1024]; int len = 0; while ((len = fileReader.read(c)) != -1) { stringBuffer.append(c, 0, len); } fileReader.close(); // System.out.print(stringBuffer.toString()); return stringBuffer.toString(); } catch (Exception e) { } return ""; } //获得所有盘符 public static File[] getRootFir() { // FileSystemView sys = FileSystemView.getFileSystemView(); File[] files = File.listRoots(); //获得盘符类型 // for(int i = 0; i < files.length; i++) { // System.out.println(files[i] + " -- " + sys.getSystemTypeDescription(files[i])); // } return files; } //获得指定目录下的目录 public static File[] getFir(File file) { return file.listFiles(); } public static JButton getJButton(File file, boolean type) { JButton jButton = new JButton(); jButton.setHorizontalTextPosition(AbstractButton.LEFT); jButton.setHorizontalAlignment(AbstractButton.LEFT); jButton.setText(type ? "[文件夹]" + (file.getName().equals("") ? file : file.getName()) : "[文件]" + (file.getName().equals("") ? file : file.getName())); jButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) { if (file.isFile()) { //关闭打开的窗体 for (int i = 0; i < jDialogs.size(); i++) { jDialogs.get(i).dispose(); } //开始阅读 article = getText(file); maxPageNumber = article.length() / pageSize + (article.length() % pageSize == 0 ? 0 : 1); right.setText("" + article.substring(0, pageSize > article.length() ? article.length() : pageSize) + ""); nowPage = 1; } else { File[] files = getFir(file); showDialog(files); } } super.mousePressed(e); } }); return jButton; } } 再上图
上代码
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by lenovo on 2017/10/19. */ public class GUIDemo extends JFrame { public static void main(String[] args) { GUIDemo myWin = new GUIDemo(); //创建面板 Panel basePanel=new Panel(); //为面板设置布局 BorderLayout borderLayout=new BorderLayout(); basePanel.setLayout(borderLayout); //创建内容面板---内容面板放置聊天内容应该使用JScrollPane JList list=new JList(); list.setBorder(BorderFactory.createTitledBorder("聊天内容")); //一次只能选择一项 // list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); //可以按住Ctrl或者Shift键多选 // list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); //可以按住Ctrl或者Shift键多选,但是当按住Ctrl选择时只能选相邻的 // list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); JScrollPane contextPanel=new JScrollPane(list); //将内容面板添加到根面板(basePanel)上 basePanel.add(contextPanel,BorderLayout.CENTER); //创建文字输入面板 Panel textPanel=new Panel(); //为textPanel面板设置布局 BorderLayout text_borderLayout=new BorderLayout(); textPanel.setLayout(text_borderLayout); //创建文本输入框 TextField text=new TextField(); //将输入框添加到textPanel面板 textPanel.add(text,BorderLayout.CENTER); //创建发送按钮 JButton send=new JButton("发送"); //将send按钮添加到textPanel面板 textPanel.add(send,BorderLayout.EAST); //将文字输入面板添加到根面板(basePanel)上 basePanel.add(textPanel,BorderLayout.SOUTH); //将basePanel面板添加到窗体中 myWin.add(basePanel); //设置窗体标题 myWin.setTitle("本地对话"); //设置窗体大小 myWin.setSize(800,800); //使窗体位于屏幕中央 myWin.setLocationRelativeTo(null); myWin.setVisible(true); myWin.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); send.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //当JList的项集合为空时 Date currentTime = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String dateString = formatter.format(currentTime); if(0 == list.getModel().getSize()) { //新建一个默认项集合 DefaultListModel listModel = new DefaultListModel(); //操作这个集合 listModel.add(0, dateString +": "+ text.getText()); //将这个集合添加到JList中 list.setModel(listModel); } //JList的项不为空时 else { //从JList中获得这个集合,转换为默认项集合类型 DefaultListModel listModel= (DefaultListModel) list.getModel(); //追加元素 listModel.add(listModel.getSize(), dateString +": "+ text.getText()); //将这个集合添加到JList中 list.setModel(listModel); } text.setText(""); } }); } }
想了解布局请点击此链接,推荐文章,更详细的GUI教程,请点击此链接
OK,希望对大家有帮组。