View Javadoc
1   /*
2    * Copyright 2020-2022 The OSHI Project Contributors
3    * SPDX-License-Identifier: MIT
4    */
5   package oshi.demo.gui;
6   
7   import java.awt.BorderLayout;
8   
9   import javax.swing.JLabel;
10  import javax.swing.JScrollPane;
11  import javax.swing.JTextArea;
12  import javax.swing.ScrollPaneConstants;
13  import javax.swing.Timer;
14  import javax.swing.text.DefaultCaret;
15  
16  import oshi.SystemInfo;
17  import oshi.hardware.HardwareAbstractionLayer;
18  import oshi.hardware.UsbDevice;
19  
20  /**
21   * Shows USB devices. Simply prints OSHI's output in a scrollable pane.
22   */
23  public class UsbPanel extends OshiJPanel { // NOSONAR squid:S110
24  
25      private static final long serialVersionUID = 1L;
26  
27      private static final String USB_DEVICES = "USB Devices";
28  
29      public UsbPanel(SystemInfo si) {
30          super();
31          init(si.getHardware());
32      }
33  
34      private void init(HardwareAbstractionLayer hal) {
35  
36          JLabel usb = new JLabel(USB_DEVICES);
37          add(usb, BorderLayout.NORTH);
38          JTextArea usbArea = new JTextArea(60, 20);
39          JScrollPane scrollV = new JScrollPane(usbArea);
40          scrollV.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
41          DefaultCaret caret = (DefaultCaret) usbArea.getCaret();
42          caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
43  
44          usbArea.setText(getUsbString(hal));
45          add(scrollV, BorderLayout.CENTER);
46  
47          Timer timer = new Timer(Config.REFRESH_SLOW, e -> usbArea.setText(getUsbString(hal)));
48          timer.start();
49      }
50  
51      private static String getUsbString(HardwareAbstractionLayer hal) {
52          StringBuilder sb = new StringBuilder();
53          boolean first = true;
54          for (UsbDevice usbDevice : hal.getUsbDevices(true)) {
55              if (first) {
56                  first = false;
57              } else {
58                  sb.append('\n');
59              }
60              sb.append(String.valueOf(usbDevice));
61          }
62          return sb.toString();
63      }
64  
65  }