java - 如何根据 USB 端口的连续扫描结果动态更新 JTextArea?
问题描述
我最近开始的一个项目几乎完成了。但是,我正在努力使用控制台输出的相同消息来更新 JTextArea:
“没有插入正确的设备。等待并重试。”
“没有插入任何设备。等待并重试。”
“可移动设备目录:” + 目录
“保存到:” + 目的地
等等
任何帮助深表感谢。
整个代码
/* ImageReaderGUI.java Copyright 2019
*
* Written by Noah Shaw
*
*/
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.*;
import net.samuelcampos.usbdrivedetector.USBDeviceDetectorManager; // Special thanks to this guy!
import net.samuelcampos.usbdrivedetector.USBStorageDevice;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class ImageReader {
private JFrame frame;
private JTextArea textArea;
static USBStorageDevice main = null;
/*
* Launch the application
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
ImageReader window = new ImageReader();
window.frame.setVisible(true);
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
}
/*
* Create the application
*/
public ImageReader()
{
initialize();
}
/*
* Initialize the contents of the frame
*/
private void initialize()
{
frame = new JFrame();
frame.setBounds(100, 100, 440, 560);
frame.setResizable(false);
frame.setTitle("Image Reader");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(12, 13, 398, 499);
frame.getContentPane().add(panel);
panel.setLayout(null);
JButton startBtn = new JButton("Start");
startBtn.setForeground(Color.BLACK);
startBtn.setBackground(Color.LIGHT_GRAY);
startBtn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
frame.setState(Frame.ICONIFIED);
poll();
execute();
}
});
startBtn.setFont(new Font("Tahoma", Font.BOLD, 16));
startBtn.setBounds(12, 462, 374, 24);
panel.add(startBtn);
textArea = new JTextArea();
textArea.setBounds(12, 13, 374, 436);
textArea.setEditable(false);
panel.add(textArea);
setUIAppearance();
}
/*
* Set the look and feel of the application to the system's look and feel
*/
private void setUIAppearance()
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
catch(InstantiationException e)
{
e.printStackTrace();
}
catch(IllegalAccessException e)
{
e.printStackTrace();
}
catch(UnsupportedLookAndFeelException e)
{
e.printStackTrace();
}
}
/*
* Polls the USB ports on the computer until the correct removable storage device is plugged in
*/
private void poll()
{
boolean scanning = true;
while(scanning)
{
USBDeviceDetectorManager manager = new USBDeviceDetectorManager();
List<USBStorageDevice> usbStorageDevices = manager.getRemovableDevices();
if(usbStorageDevices.size() >= 1)
{
for(USBStorageDevice device : usbStorageDevices)
{
if(device.getDeviceName().equals("F")) // Will need the name of SD card
{
scanning = false;
main = device;
}
else
{
System.out.println("Correct device is not plugged in. Waiting and trying again." + Thread.currentThread().getName());
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textArea.append("Correct device is not plugged in. Waiting and trying again.");
}
});
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
else
{
System.out.println("No devices are plugged in. Waiting and trying again.");
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
/*
* Initialize the JFileChooser
*/
private void execute()
{
// Set the current directory to the root directory of the removable device and the title of the file chooser window
File directory = main.getRootDirectory();
// Get the current directory and print it to the console
System.out.println("Removable Device Directory: " + directory);
final String[] EXTENSIONS = new String[] {"png", "jpg", "jpeg"}; // Acceptable file extensions
final FilenameFilter IMAGE_FILTER = new FilenameFilter() // Filter all files that have an acceptable file extension
{
public boolean accept(final File directory, final String name)
{
for(final String ext : EXTENSIONS)
{
if(name.endsWith("." + ext))
{
return true;
}
}
return false;
}
};
saveAndPrint(directory, IMAGE_FILTER);
}
/*
* Save and print each image
*/
private void saveAndPrint(File aDirectory, FilenameFilter aFilenameFilter)
{
String saveDirectory = null;
int count = 0;
// If the directory is a directory, begin the save
if(aDirectory.isDirectory())
{
save(aDirectory, aFilenameFilter, saveDirectory, count);
print(aDirectory, aFilenameFilter);
}
// No selection was made in the file chooser
else
{
System.out.println("No Selection");
}
}
/*
* Save each image
*/
private void save(File aDirectory, FilenameFilter aFilenameFilter, String aSaveDirectory, int aCount)
{
for(final File f : aDirectory.listFiles(aFilenameFilter))
{
try
{
// Create a buffered image of the file
BufferedImage img = ImageIO.read(f);
// Format the date that the image was last modified in dd_MM_yyyy format
DateFormat dateFormat = new SimpleDateFormat("dd_MM_yyyy");
String lastModified = dateFormat.format(f.lastModified());
// Save the image in a new destination with the last modified date appended to the front of the name of the file
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home") + "\\Pictures"));
fileChooser.setDialogTitle("Save");
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fileChooser.setAcceptAllFileFilterUsed(false);
if(aCount == 0 && fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION)
{
aSaveDirectory = fileChooser.getSelectedFile().getAbsolutePath();
aCount = -1;
}
System.out.println(aSaveDirectory);
File destination = new File(aSaveDirectory + "\\" + lastModified + "_" + f.getName());
// Print to the console where the image was saved
System.out.println("SAVED TO: " + destination);
ImageIO.write(img, f.getName().substring(f.getName().lastIndexOf(".") + 1), destination);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
/*
* Print each image to the default printer
*/
private void print(File aDirectory, FilenameFilter aFilenameFilter)
{
for(final File f : aDirectory.listFiles(aFilenameFilter))
{
try
{
// Create a buffered image of the file
BufferedImage img = ImageIO.read(f);
// Create the print job
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintable(new Printable()
{
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException
{
pageFormat = printJob.defaultPage();
pageFormat.setOrientation(PageFormat.PORTRAIT); // Portrait orientation
Paper paper = pageFormat.getPaper();
paper.setImageableArea(0, 0, paper.getWidth(), paper.getHeight());
pageFormat.setPaper(paper);
// No page
if(pageIndex != 0)
{
return NO_SUCH_PAGE;
}
// Translate the image to (0,0)
graphics.translate((int)pageFormat.getImageableX(), (int)pageFormat.getImageableY());
// Center the image on the page
graphics.drawImage(img, ((int)pageFormat.getImageableWidth() / 2) - (img.getWidth() / 2), ((int)pageFormat.getImageableHeight() / 2) - (img.getHeight() / 2), img.getWidth(), img.getHeight(), null);
return PAGE_EXISTS;
}
});
// Print each image to the default printer
try
{
printJob.print();
}
catch(PrinterException printException)
{
printException.printStackTrace();
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
}
我目前正在使用一个线程,但我认为它不正确:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textArea.append("Correct device is not plugged in. Waiting and trying again.");
}
});
解决方案
推荐阅读
- python - Can't install requirements using pip and python 3.8.5 on a Ubuntu 20.04 server
- html - 按下回车键或单击搜索按钮时如何显示或隐藏表格
- awk - 根据bash中的两列以上计算唯一值的数量
- powershell - Using copy-item in powershell to transfer file on a shared drive
- node.js - Frequent timeout error on Node.js when connecting to an SQL Server instance through mssql
- gitlab-ci - Trigger pipeline/job when merge request state changes (WIP to "ready")
- security - Service account with org viewer role not able to perform any actions
- c++ - boost::asio::async_write_some - sequential function call
- sql - SQL Need days of selected week as columns
- javascript - 从 UInt8Array (react-pdf) 在 React 中显示 PDF 的问题