第九天

今天我添加了选项卡窗口。话不多说,上代码:

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] = Double.toString(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);

            }

        });
        
        

    }

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

//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;// 操作完成,继续更新

            }

        });

        

    }

    
}
processApp

 

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(Double.valueOf(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/4438/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 void main(String[] args) throws Exception {
        //System.out.println(Getprocess());;
        //Killprocess("1239");
        //installTool("iotop");
         //killProcessTree("2887");
        findExePath("4438");
    }
}
process

 

posted @ 2019-06-01 08:47  我是一个粉刷匠^~^  阅读(162)  评论(0编辑  收藏  举报