第十天

今天,我添加了查看进程属性的功能。至此进程的模块功能完成。今天特别麻烦,因为要从原来的窗口中打开新窗口,但是新窗口要加载组件。原来我为了方便,类里面的变量都尽可能设置成静态变量。但是今天我将组件设置成静态变量后,只能打开一个进程的属性窗口,或者是一个属性窗口加载了几个进程的属性。感觉今天在静态变量,类变量,全局变量,局部变量上面走了不少弯路。最后还发现运行进程这个模块程序有时报错,有一个无效的变量。但是最后也没解决。

package wl;

import java.awt.BorderLayout;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

public class mainApp {
    public static void main(String[] args) {
        p.initMenu();
        p.initPane();
        p.initProcess();
    }
    static JFrame f = new JFrame("Process");
    private static mainApp p = new mainApp();
    static JPanel p1 = new JPanel();
    static JPanel p2 = new JPanel();
    static JPanel p3 = new JPanel();
    static JPanel p4 = new JPanel(); // 创建多个容器
    static JPanel p5 = new JPanel();
    void initPane() {
        JTabbedPane jp = new JTabbedPane(JTabbedPane.TOP); // 设置选项卡在坐标
        
        jp.add("进程", p1);
        jp.add("性能", p2);
        jp.add("应用", p3);
        jp.add("联网", p4); // 添加子容器 并且为选项卡添加名字
        jp.add("用户", p5); // 添加子容器 并且为选项卡添加名字
        f.add(jp, BorderLayout.CENTER); // 将选项卡窗体添加到 主窗体上去
    }

    mainApp() {// init frame
        f.setVisible(true);
        f.setSize(1000, 800);
        f.setLayout(new BorderLayout());

    }

    void initMenu() {// init menu
        JMenuBar menubar = new JMenuBar();
        JMenu[] menus = new JMenu[] { new JMenu("文件"), new JMenu("选项"), new JMenu("查看") };
        for (int i = 0; i < menus.length; i++) {
            menubar.add(menus[i]);
        }
        f.setJMenuBar(menubar);
    }
    
    
    void initProcess() {
        ProcessApp pa=new ProcessApp();
        p1.add(pa.panel);
        pa.initTable();
        pa.setTable();
        pa.setScrollPane();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Boolean result = false;
        int count = 0;
        while (!result) {
            try {
                Thread.sleep(10000); // 设置暂停的时间 5 秒
                if (pa.isUpdate == true) {
                    count++;
                    pa.setTable();
                    System.out.println(sdf.format(new Date()) + "--循环执行第" + count + "");
                     
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("finish");
    }

}
mainApp
package wl;

import java.awt.BorderLayout;
import java.awt.Choice;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Frame;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.ButtonGroup;
import javax.swing.ComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButton;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.RowSorter;
import javax.swing.border.Border;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

public class ProcessApp extends JFrame {
    static JPopupMenu m_popupMenu;// 弹出式菜单、右键菜单
    static Object[][] cellData = { { "名称", "PID", "优先级", "状态", "用户名", "cpu", "内存", "描述" } };
    static String[] columnNames = { "col1", "col2", "col3", "col4", "col5", "col6", "col7", "col8" };
    static JTable table = new JTable(cellData, columnNames);
    static int focusedRowIndex = -1;// table mouse row number
    static List<processModel> processs = new ArrayList<processModel>();
    static boolean isUpdate = true;// 是否更新:当鼠标左键按下后不再更新进程,当过去5秒后继续更新
    static boolean isbai=true;
    private static ProcessApp p = new ProcessApp();
    static JPanel panel = new JPanel();

    
    
    
    void initTable() {
         // (1)名称,优先级,cpu,内存,磁盘,网络,GPU的使用情况,端口,用户名,状态,描述

        table.setSize((int) (panel.getWidth() * 0.2), 40);   
        table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        String[] headers = { "名称", "PID", "优先级", "状态", "用户名", "cpu", "内存", "描述" };
        DefaultTableModel model = new DefaultTableModel(cellData, headers) {
            public boolean isCellEditable(int row, int column) {
                if(row==2){
                    return true;//返回true则表明单元格可编辑
                }
                else{
                    return false;
                }
            }
        };
        
        table = new JTable(model);
        RowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);  
        table.setRowSorter(sorter); 
        panel.add(table);
        
        createPopupMenu();// 创建鼠标点击事件

    }

    void setTable() {
        TableModel tableModel = table.getModel();
        int rows = table.getRowCount();// get table rows
        while (rows >= 1) {// if update not update finish,continue delete rows
            ((DefaultTableModel) tableModel).removeRow(0);// rowIndex是要删除的行序号
            rows = table.getRowCount();// get table rows
        }

        // "名称","PID","优先级","状态","用户名","cpu","内存","描述"
        processs = process.Getprocess();
        int i = 0;
        for (processModel p : processs) {
            String[] arr = new String[8];
            arr[0] = p.getName();
            arr[1] = p.getPID();
            arr[2] = p.getPrio();
            arr[3] = p.getState();
            arr[4] = p.getUser();
            arr[5] = Double.toString(p.getB_cpu())+"%";
            if(isbai==true) {
                arr[6] = Double.toString(p.getB_memory())+"%";
            }
            else {
                arr[6] = p.getMemory();
            }
            
            // arr[7] = p.getDescribe();
            arr[7] = String.valueOf(i);
            i++;
            // 添加数据到表格
            ((DefaultTableModel) tableModel).addRow(arr);

        }
        // 更新表格
        table.invalidate();
        table.setSize(mainApp.p1.getWidth() - 20, mainApp.p1.getHeight());

        // JTable对象添加点击事件
        table.addMouseListener(new java.awt.event.MouseAdapter() {

            public void mouseClicked(java.awt.event.MouseEvent evt) {
                isUpdate = false;
                jTable1MouseClicked(evt);

            }

        });
        
        

    }

    

//table点击事件

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {

        mouseRightButtonClick(evt);

    }

//鼠标右键点击事件

    private void mouseRightButtonClick(java.awt.event.MouseEvent evt) {

        // 判断是否为鼠标的BUTTON3按钮,BUTTON3为鼠标右键

        if (evt.getButton() == java.awt.event.MouseEvent.BUTTON3) {

            // 通过点击位置找到点击为表格中的行

            focusedRowIndex = table.rowAtPoint(evt.getPoint());

            if (focusedRowIndex == -1) {

                //System.out.println(focusedRowIndex);

            }

            // 将表格所选项设为当前右键点击的行

            table.setRowSelectionInterval(focusedRowIndex, focusedRowIndex);
        

            // 弹出菜单

            m_popupMenu.show(table, evt.getX(), evt.getY());

        }

    }

    public void mousePressed(MouseEvent e) {
        if (e.getButton() == MouseEvent.BUTTON3) {
            int selIndex = table.rowAtPoint(e.getPoint());
            
        }
    }

//创建鼠标点击事件
    private static void createPopupMenu() {

        m_popupMenu = new JPopupMenu();

        JMenuItem MenuItem0= new JMenuItem();
        MenuItem0.setText("  结束进程  ");
        JMenuItem MenuItem1= new JMenuItem();
        MenuItem1.setText("  结束进程树  ");
        JMenu MenuItem2 = new JMenu();
        
        /***设置优先级***/
        MenuItem2.setText("  设置优先级  ");//Linux系统进程的优先级取值:-20 到 19,数越大优先级越低。
        JMenuItem m3 = new JMenuItem();
        JMenuItem m4 = new JMenuItem();
        JMenuItem m5 = new JMenuItem();
        JLabel showVal = new JLabel();  
         //定义一个监听器,用于监听所有滑动条  
        ChangeListener listener; 
        listener = new ChangeListener()  
        {    
            public void stateChanged(ChangeEvent event)  
            { 
                
                
                //取出滑动条的值,并在文本中显示出来  
                JSlider source = (JSlider) event.getSource();   
                String prio = processs.get(focusedRowIndex - 1).getPrio();
                source.setValue(Integer.valueOf(prio));
                showVal.setText("当前的值为:" + source.getValue());  
                String pid = processs.get(focusedRowIndex - 1).getPID();
                process.updatePrio(pid, source.getValue());
                isUpdate = true;// 操作完成,继续更新
            }

         
        };  
       
        
        JSlider slider = new JSlider(-20,19);  
        
            //设置绘制刻度  
            slider.setPaintTicks(true);  
            //设置主、次刻度的间距  
            slider.setMajorTickSpacing(5);  
            slider.setMinorTickSpacing(1);  
            //设置绘制刻度标签,默认绘制数值刻度标签  
            slider.setPaintLabels(true);
            
            slider.addChangeListener(listener); 
            m3.add(new JLabel("值越大,优先级越低,值越小,优先级越大")); 
            m4.add(slider);
            m4.setPreferredSize(new Dimension(300,60));
            showVal.setText("当前的值为:" ); 
           
            showVal.setVisible(true);
            m5.add(showVal);
            MenuItem2.add(m3); 
            MenuItem2.add(m4); 
            MenuItem2.add(m5); 
           
         
            
        /***设置优先级 end***/
        /***设置设置资源***/
            JRadioButtonMenuItem j1=new JRadioButtonMenuItem();
            j1.setText("");
            JRadioButtonMenuItem j2=new JRadioButtonMenuItem();
            j2.setText("百分比");
            if(isbai==true) {
                j2.setSelected(true);
            }
            else {
                j1.setSelected(true);
            }
         //定义一个监听器,用于监听所有滑动条  
            ChangeListener listener2; 
            listener2 = new ChangeListener()  
            {    
                public void stateChanged(ChangeEvent event)  
                { 
                    
                    
                    //取出滑动条的值,并在文本中显示出来  

                   if(event.getSource()==j1) {
                       j2.setSelected(false);
                       isbai=false;
                       p.setTable();
                       isUpdate = true;// 操作完成,继续更新
                       
                   }
                   else {
                       j1.setSelected(false);
                       isbai=true;
                       p.setTable();
                       isUpdate = true;// 操作完成,继续更新
                       
                   }
                }

             
            };  
        JMenu MenuItem3 = new JMenu("  内存  ");
        
        MenuItem3.add(j1);
        MenuItem3.add(j2);
         j1.addChangeListener(listener2); 
         j2.addChangeListener(listener2);
        /***设置设置资源 end***/
        JMenuItem MenuItem5= new JMenuItem();
        MenuItem5.setText("  打开文件所在位置  ");
        JMenuItem MenuItem6= new JMenuItem();
        MenuItem6.setText("  属性  ");
        m_popupMenu.add(MenuItem0);
        m_popupMenu.add(MenuItem1);
        m_popupMenu.add(MenuItem2);
        m_popupMenu.add(MenuItem3);
        m_popupMenu.add(MenuItem5);
        m_popupMenu.add(MenuItem6);

        MenuItem0.addActionListener(new java.awt.event.ActionListener() {// 结束进程 

            public void actionPerformed(java.awt.event.ActionEvent evt) {

                // 该操作需要做的事
                String pid = processs.get(focusedRowIndex - 1).getPID();
                process.Killprocess(pid);
                p.setTable();
                isUpdate = true;// 操作完成,继续更新

            }

        });
        MenuItem1.addActionListener(new java.awt.event.ActionListener() {//结束进程树 

            public void actionPerformed(java.awt.event.ActionEvent evt) {

                // 该操作需要做的事
                String pid = processs.get(focusedRowIndex - 1).getPID();
                process.killProcessTree(pid);
                p.setTable();
                isUpdate = true;// 操作完成,继续更新

            }

        });
        MenuItem2.addActionListener(new java.awt.event.ActionListener() {//结束进程树 

            public void actionPerformed(java.awt.event.ActionEvent evt) {

                // 该操作需要做的事
                String prio = processs.get(focusedRowIndex - 1).getPrio();
                slider.setValue(Integer.valueOf(prio));
                p.setTable();
                isUpdate = true;// 操作完成,继续更新

            }

        });
        
        MenuItem5.addActionListener(new java.awt.event.ActionListener() {//结束进程树 

            public void actionPerformed(java.awt.event.ActionEvent evt) {

                // 该操作需要做的事
                String pid = processs.get(focusedRowIndex - 1).getPID();
                String path=process.findExePath(pid);
                System.out.println(path);
                File file=new File(path); 
                
                try {
                java.awt.Desktop.getDesktop().open(file.getParentFile());
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                p.setTable();
                isUpdate = true;// 操作完成,继续更新

            }

        });
        
        MenuItem6.addActionListener(new java.awt.event.ActionListener() {//结束进程树 

            public void actionPerformed(java.awt.event.ActionEvent evt) {

                // 该操作需要做的事
                String pid = processs.get(focusedRowIndex - 1).getPID();
                String name=processs.get(focusedRowIndex - 1).getName();
                
                JFrame properties= new processPropertiesApp(name,pid);
                properties.setVisible(true);//设置界面为可以显示
               
                isUpdate = true;// 操作完成,继续更新

            }

        });

        

    }

    // 设置滚动条
        void setScrollPane() {
            JScrollPane jsp;
            jsp = new JScrollPane(table);
            panel.add(jsp);
        }
    
}
processApp
package wl;

import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

public class processPropertiesApp extends JFrame{
     JPanel panel = new JPanel();
     String pid;
     String name;
     processPropertiesModel pp;

    
    
    processPropertiesApp(String name,String pid) {
        this.setVisible(true);
        this.setSize(500, 300);
        this.setLayout(new BorderLayout());
        this.pid=pid;
        this.name=name;
        this.pp=process.getProcessPropeties(pid);
        this.init();
        
    }
    
    void init() {
        this.initPanel();
        this.initString(name, pid);
        this.initTable();
        //this.setScrollPane(table);//添加滑块,不对,去掉滑块就对了
    }
    void initPanel() {
        this.getContentPane().add(panel, BorderLayout.CENTER);
    }
    
    void initString(String name,String pid) {
        JLabel tf=new JLabel("进程 '"+name+"'(PID "+pid+")的属性:");
        tf.setAlignmentX((float) 0.5);
        this.add(tf,"North");
        
    }
    
    // 设置滚动条
        void setScrollPane(JTable table) {
            JScrollPane jsp;
            jsp = new JScrollPane(table);
            panel.add(jsp);
        }
    
    void initTable() {
         Object[][] cellData = {
                    {"开始时间",pp.getStartTime()},
                    {"使用用户",pp.getUser()},
                    {"运行任务数",pp.getRunTask()},
                    {"用户空间占用CPU",pp.getB_userCPU()},
                    {"内核空间占用CPU",pp.getB_systemCPU()},
                    {"空闲CPU",pp.getB_freeCPU()},
                    {"物理内存总量",pp.getTotalMemary()},
                    {"使用内存",pp.getUsedMemary()},
                    {"空闲内存",pp.getFreeMemeary()},
                    {"共享内存",pp.getShareMemary()},
                    {"虚拟内存总量",pp.getTotalVirtMemry()},
                    {"优先级",pp.getPrio()},
                    {"文件路径",pp.getPath()}
                    };
          String[] columnNames = {"属性","   "};
          JTable table= new JTable(cellData, columnNames);
           table.setEnabled(false);//设置表格不可编辑
           panel.add(table,BorderLayout.CENTER);
           System.out.println(pp.getUser());
       
        
    }
}
processPropertiesApp
package wl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class process {

    // 结束进程树
    // 结束进程树的特性就是在结束一个进程的同时结束由该进程直接或间接创建的子进程
    // pstree -p pid 查看子进程
    // 返回子进程和父进程的id
    public static List<String> killProcessTree(String pid) {

        Runtime runtime = Runtime.getRuntime();
        List<String> tasklist = new ArrayList<String>();
        java.lang.Process process = null;
        List<processModel> processs = new ArrayList<processModel>();
        int count = 0; // 统计进程数
        try {
            /*
             * 
             * 自适应执行查询进程列表命令
             * 
             */
            Properties prop = System.getProperties();
            // 获取操作系统名称
            boolean is = false;
            String os = prop.getProperty("os.name");
            if (os != null && os.toLowerCase().indexOf("linux") > -1) {
                // 1.适应与linux
                BufferedReader reader = null;
                // 查询子进程
                process = Runtime.getRuntime().exec("pstree  -p " + pid);
                reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                List<String> pids = new ArrayList<String>();
                String line = null;

                while ((line = reader.readLine()) != null) {
                    // System.out.println(line);
                    int length = line.length() - 1;
                    String id = line.substring(length - 4, length);
                    pids.add(id);
                    Killprocess(id);
                }

            }

        } catch (Exception e) {
            e.printStackTrace();

        }
        return null;

    }

//修改进程优先级    
    public static void updatePrio(String pid, int prio) {
        Runtime runtime = Runtime.getRuntime();
        List<String> tasklist = new ArrayList<String>();
        java.lang.Process process = null;
        try {
            /*
             * 
             * 自适应执行查询进程列表命令
             * 
             */
            Properties prop = System.getProperties();
            // 获取操作系统名称
            boolean is = false;
            String os = prop.getProperty("os.name");
            if (os != null && os.toLowerCase().indexOf("linux") > -1) {
                // 1.适应与linux

                BufferedReader reader = null;

                process = Runtime.getRuntime().exec("renice " + prio + "  " + pid);
                System.out.println("renice " + prio + "  " + pid);

            }

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

//kill -9 [PID]   结束进程
    public static void Killprocess(String pid) {

        Runtime runtime = Runtime.getRuntime();
        List<String> tasklist = new ArrayList<String>();
        java.lang.Process process = null;
        try {
            /*
             * 
             * 自适应执行查询进程列表命令
             * 
             */
            Properties prop = System.getProperties();
            // 获取操作系统名称
            boolean is = false;
            String os = prop.getProperty("os.name");
            if (os != null && os.toLowerCase().indexOf("linux") > -1) {
                // 1.适应与linux

                BufferedReader reader = null;
                // 显示所有进程
                // "名称","PID","优先级","状态","用户名","cpu","内存","磁盘","网络","描述"
                process = Runtime.getRuntime().exec("kill -9 " + pid);
                System.out.println("kill process:" + pid);

            }

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

    // get process infomation
    public static List<processModel> Getprocess() {

        Runtime runtime = Runtime.getRuntime();
        List<String> tasklist = new ArrayList<String>();
        java.lang.Process process = null;
        List<processModel> processs = new ArrayList<processModel>();
        int count = 0; // 统计进程数
        try {
            /*
             * 
             * 自适应执行查询进程列表命令
             * 
             */
            Properties prop = System.getProperties();
            // 获取操作系统名称
            boolean is = false;
            String os = prop.getProperty("os.name");
            if (os != null && os.toLowerCase().indexOf("linux") > -1) {
                // 1.适应与linux

                BufferedReader reader = null;
                // 显示所有进程
                // "名称","PID","优先级","状态","用户名","cpu","内存","磁盘","网络","描述"
                process = Runtime.getRuntime().exec("top -b -n 1");
                reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

                String line = null;

                while ((line = reader.readLine()) != null) {

                    if (line.startsWith("   PID")) {
                        is = true;
                        line = reader.readLine();
                    }
                    if (is == true) {

                        Pattern p = Pattern.compile("\s+");
                        Matcher m = p.matcher(line);
                        line = m.replaceAll(",");

                        String[] strs = line.split(",");

                        processModel pro = new processModel();
                        pro.setPID(strs[1]);
                        pro.setUser(strs[2]);
                        pro.setPrio(strs[4]);
                    
                        pro.setMemory(strs[6]);
                        pro.setState(strs[8]);
                        pro.setB_cpu(Double.valueOf(strs[9]));
                        pro.setB_memory(Double.valueOf(strs[10]));
                        pro.setName(strs[12]);
                        processs.add(pro);
                    }
                }

            }

        } catch (Exception e) {

            e.printStackTrace();

        }
        return processs;

    }

    public static String findExePath(String pid) {
        Runtime runtime = Runtime.getRuntime();
        List<String> tasklist = new ArrayList<String>();
        java.lang.Process process = null;
        String path = "";
        try {
            /*
             * 
             * 自适应执行查询进程列表命令
             * 
             */
            Properties prop = System.getProperties();
            // 获取操作系统名称
            boolean is = false;
            String os = prop.getProperty("os.name");
            if (os != null && os.toLowerCase().indexOf("linux") > -1) {
                // 1.适应与linux

                BufferedReader reader = null;

                process = Runtime.getRuntime().exec("ls -ail /proc/" + pid + "/exe");
                reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

                String line = null;

                while ((line = reader.readLine()) != null) {

                    int first = line.indexOf(">");
                    path = line.substring(first + 2, line.length());

                }

            }

        } catch (Exception e) {

            e.printStackTrace();

        }
        return path;
    }

    public static processPropertiesModel getProcessPropeties(String pid) {

        Runtime runtime = Runtime.getRuntime();
        List<String> tasklist = new ArrayList<String>();
        java.lang.Process process = null;
        List<processModel> processs = new ArrayList<processModel>();

        processPropertiesModel p = new processPropertiesModel();
        try {
            /*
             * 
             * 自适应执行查询进程列表命令
             * 
             */
            Properties prop = System.getProperties();
            // 获取操作系统名称
            boolean is = false;
            String os = prop.getProperty("os.name");
            if (os != null && os.toLowerCase().indexOf("linux") > -1) {
                // 1.适应与linux

                BufferedReader reader = null;

                process = Runtime.getRuntime().exec("top -p  " + pid + "  -b -n 1");
                reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

                String line = null;

                int i = 0;

                while ((line = reader.readLine()) != null) {

                    if (i == 0) {
                        int index = line.indexOf("u");
                        p.setStartTime(line.substring(index - 9, index).trim());
                    } else if (i == 1) {
                        String[] arr = line.split(",");
                        int index = arr[1].indexOf("r");
                        p.setRunTask(arr[1].substring(0, index).trim());
                    } else if (i == 2) {
                        line = line.substring(line.indexOf(":") + 1);
                        String[] arr = line.split(",");
                        int index = arr[0].indexOf("u");
                        p.setB_userCPU(arr[0].substring(0, index).trim());
                        index = arr[1].indexOf("s");
                        p.setB_systemCPU(arr[1].substring(0, index).trim());
                        index = arr[3].indexOf("i");
                        p.setB_freeCPU(arr[3].substring(0, index).trim());

                    } else if (i == 3) {
                        String[] arr = line.split(",");
                        int index = arr[0].indexOf("t");
                        int index2 = arr[0].indexOf(":");
                        p.setTotalMemary(arr[0].substring(index2 + 1, index).trim());
                        index = arr[1].indexOf("u");
                        p.setUsedMemary(arr[1].substring(0, index).trim());
                        index = arr[2].indexOf("f");
                        p.setFreeMemeary(arr[2].substring(0, index).trim());

                    } else if (i == 4) {
                        String[] arr = line.split(",");
                        int index = arr[0].indexOf("t");
                        int index2 = arr[0].indexOf(":");
                        p.setTotalVirtMemry(arr[0].substring(index2 + 1, index).trim());
                    } else if (i == 7) {
                        Pattern p1 = Pattern.compile("\s+");
                        Matcher m = p1.matcher(line);
                        line = m.replaceAll(",");
                        String[] arr = line.split(",");
                        p.setShareMemary(arr[7].trim());
                        p.setPrio(arr[3].trim());
                        p.setUser(arr[2].trim());
                    }

                    i++;
                }

                p.setPath(findExePath(pid));

            }

        } catch (Exception e) {

            e.printStackTrace();

        }
        return p;

    }

    public static void main(String[] args) throws Exception {
        // System.out.println(Getprocess());;
        // Killprocess("1239");
        // installTool("iotop");
        // killProcessTree("2887");
        // findExePath("4438");
        getProcessPropeties("2911");
    }
}
process
package wl;

public class processModel {
   // "名称","PID","状态","用户名","cpu","内存","磁盘","网络","描述"
   private String name;//"名称
   private String PID;// 进程id
   private String state;//进程状态。D=不可中断的睡眠状态 R=运行 S=睡眠 T=跟踪/停止 Z=僵尸进程
   private String user;//进程所有者
   private double b_cpu;//进程所有者
   private double b_memory;//进程使用的物理内存百分比
   private String memory;//进程使用的、未被换出的物理内存大小,单位kb。RES=CODE+DATA
 
   private String describe;
   private String  prio;
   
public String getPrio() {
    return prio;
}
public void setPrio(String prio) {
    this.prio = prio;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getPID() {
    return PID;
}
public void setPID(String pID) {
    PID = pID;
}
public String getState() {
    return state;
}
public void setState(String state) {
    this.state = state;
}
public String getUser() {
    return user;
}
public void setUser(String user) {
    this.user = user;
}

public String getMemory() {
    return memory;
}
public void setMemory(String memory) {
    this.memory = memory;
}

public String getDescribe() {
    return describe;
}
public void setDescribe(String describe) {
    this.describe = describe;
}
public double getB_cpu() {
    return b_cpu;
}
public void setB_cpu(double b_cpu) {
    this.b_cpu = b_cpu;
}
public double getB_memory() {
    return b_memory;
}
public void setB_memory(double b_memory) {
    this.b_memory = b_memory;
}
@Override
public String toString() {
    return "processModel [name=" + name + ", PID=" + PID + ", state=" + state + ", user=" + user + ", b_cpu=" + b_cpu
            + ", b_memory=" + b_memory + ", memory=" + memory + ", describe=" + describe + ", prio=" + prio + "]";
}



   
}
processModel
package wl;

public class processPropertiesModel {
    private String startTime;
    private String user;
    private String runTask;
    private String b_userCPU;
    private String b_systemCPU;
    private String b_freeCPU;
    private String totalMemary;
    private String usedMemary;
    private String freeMemeary;
    private String prio;
    private String shareMemary;
    private String totalVirtMemry;
    private String path;
    @Override
    public String toString() {
        return "processPropertiesModel [startTime=" + startTime + ", user=" + user + ", runTask=" + runTask
                + ", b_userCPU=" + b_userCPU + ", b_systemCPU=" + b_systemCPU + ", b_freeCPU=" + b_freeCPU
                + ", totalMemary=" + totalMemary + ", usedMemary=" + usedMemary + ", freeMemeary=" + freeMemeary
                + ", prio=" + prio + ", shareMemary=" + shareMemary + ", totalVirtMemry=" + totalVirtMemry + ", path="
                + path + "]";
    }
    public String getStartTime() {
        return startTime;
    }
    public void setStartTime(String startTime) {
        this.startTime = startTime;
    }
    public String getUser() {
        return user;
    }
    public void setUser(String user) {
        this.user = user;
    }
    public String getRunTask() {
        return runTask;
    }
    public void setRunTask(String runTask) {
        this.runTask = runTask;
    }
    public String getB_userCPU() {
        return b_userCPU;
    }
    public void setB_userCPU(String b_userCPU) {
        this.b_userCPU = b_userCPU;
    }
    public String getB_systemCPU() {
        return b_systemCPU;
    }
    public void setB_systemCPU(String b_systemCPU) {
        this.b_systemCPU = b_systemCPU;
    }
    public String getB_freeCPU() {
        return b_freeCPU;
    }
    public void setB_freeCPU(String b_freeCPU) {
        this.b_freeCPU = b_freeCPU;
    }
    public String getTotalMemary() {
        return totalMemary;
    }
    public void setTotalMemary(String totalMemary) {
        this.totalMemary = totalMemary;
    }
    public String getUsedMemary() {
        return usedMemary;
    }
    public void setUsedMemary(String usedMemary) {
        this.usedMemary = usedMemary;
    }
    public String getFreeMemeary() {
        return freeMemeary;
    }
    public void setFreeMemeary(String freeMemeary) {
        this.freeMemeary = freeMemeary;
    }
    public String getPrio() {
        return prio;
    }
    public void setPrio(String prio) {
        this.prio = prio;
    }
    public String getShareMemary() {
        return shareMemary;
    }
    public void setShareMemary(String shareMemary) {
        this.shareMemary = shareMemary;
    }
    public String getTotalVirtMemry() {
        return totalVirtMemry;
    }
    public void setTotalVirtMemry(String totalVirtMemry) {
        this.totalVirtMemry = totalVirtMemry;
    }
    public String getPath() {
        return path;
    }
    public void setPath(String path) {
        this.path = path;
    }

}
processPropertiesModel

报错:

Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Invalid index
    at javax.swing.DefaultRowSorter.convertRowIndexToModel(DefaultRowSorter.java:514)
    at javax.swing.JTable.convertRowIndexToModel(JTable.java:2645)
    at javax.swing.JTable.getValueAt(JTable.java:2720)
    at javax.swing.JTable.prepareRenderer(JTable.java:5712)
    at javax.swing.plaf.basic.BasicTableUI.paintCell(BasicTableUI.java:2114)
    at javax.swing.plaf.basic.BasicTableUI.paintCells(BasicTableUI.java:2016)
    at javax.swing.plaf.basic.BasicTableUI.paint(BasicTableUI.java:1812)
    at javax.swing.plaf.ComponentUI.update(ComponentUI.java:161)
    at javax.swing.JComponent.paintComponent(JComponent.java:780)
    at javax.swing.JComponent.paint(JComponent.java:1056)
    at javax.swing.JComponent.paintChildren(JComponent.java:889)
    at javax.swing.JComponent.paint(JComponent.java:1065)
    at javax.swing.JViewport.paint(JViewport.java:728)
    at javax.swing.JComponent.paintChildren(JComponent.java:889)
    at javax.swing.JComponent.paint(JComponent.java:1065)
    at javax.swing.JComponent.paintToOffscreen(JComponent.java:5210)
    at javax.swing.BufferStrategyPaintManager.paint(BufferStrategyPaintManager.java:290)
    at javax.swing.RepaintManager.paint(RepaintManager.java:1272)
    at javax.swing.JComponent._paintImmediately(JComponent.java:5158)
    at javax.swing.JComponent.paintImmediately(JComponent.java:4969)
    at javax.swing.RepaintManager$4.run(RepaintManager.java:831)
    at javax.swing.RepaintManager$4.run(RepaintManager.java:814)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
    at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:814)
    at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:789)
    at javax.swing.RepaintManager.prePaintDirtyRegions(RepaintManager.java:738)
    at javax.swing.RepaintManager.access$1200(RepaintManager.java:64)
    at javax.swing.RepaintManager$ProcessingRunnable.run(RepaintManager.java:1732)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
原文地址:https://www.cnblogs.com/wl2017/p/10960459.html