gpt4 book ai didi

JFrame 中的 Java 多线程

转载 作者:行者123 更新时间:2023-11-30 08:19:56 25 4
gpt4 key购买 nike

我希望这段代码在扫描器工作时与更新 JProgressBarJTextArea 一起工作,但我不知道如何实现线程。可能吗?

这是我的代码:

更新:它现在是一个工作版本,具有“停止”功能。我添加了一个“breakPoint”变量以从 for 循环中跳出。

package main;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;

public class PortScanner extends javax.swing.JFrame {

private doSomeStuff taskPortScanner;
private boolean breakPoint;

public PortScanner() {
initComponents();
}

private void portScan() {

int currentPort = 1;

try {

String hostname = hostNameTextField.getText();
int timeOut = (Integer) timeOutSpinner.getValue();
int minPort = Integer.parseInt(portMinTextField.getText());
int maxPort = Integer.parseInt(portMaxTextField.getText());

//set min and max value of progress bar
jProgressBar1.setMinimum(minPort);
jProgressBar1.setMaximum(maxPort);

//print out the address
InetAddress theAddress = InetAddress.getByName(hostname);
resultTextArea.append("IP adress: " + theAddress + "\n\n");

//check if port is open
for (currentPort = minPort; currentPort <= maxPort; currentPort++) {

//stop for loop
if (breakPoint == true) {
System.out.println("Portscanning stopped.");
break;
}

try {

Socket socket = new Socket();
socket.connect(new InetSocketAddress(hostname, currentPort), timeOut);

//update textarea
resultTextArea.append("Service running on port " + currentPort + "\n");
socket.close();

} catch (Exception ex) {
System.out.println(currentPort);
}

//update progressbar
jProgressBar1.setValue(currentPort);
jProgressBar1.repaint();
}

} catch (UnknownHostException ex) {
JOptionPane.showMessageDialog(PortScanner.this, "Unknown hostname: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(PortScanner.this, "Invalid format. " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
} catch (Exception ex) {
JOptionPane.showMessageDialog(PortScanner.this, "Error: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}

private class doSomeStuff extends SwingWorker<Void, Void> {

@Override
public Void doInBackground() throws Exception {
portScan();
return null;
}

@Override
public void done() {
//if thread is done enable start and clear buttons
clearButton.setEnabled(true);
startButton.setEnabled(true);
}

}

@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
hostNameTextField = new javax.swing.JTextField();
portMinTextField = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
resultTextArea = new javax.swing.JTextArea();
startButton = new javax.swing.JButton();
clearButton = new javax.swing.JButton();
portMaxTextField = new javax.swing.JTextField();
jProgressBar1 = new javax.swing.JProgressBar();
timeOutSpinner = new javax.swing.JSpinner();
jLabel4 = new javax.swing.JLabel();
stopButton = new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Simple port scanner");
setResizable(false);

jLabel1.setText("Hostname");

jLabel2.setText("Timeout");

jLabel3.setText("Port range");

hostNameTextField.setToolTipText("Type a hostname like www.google.com");

portMinTextField.setText("1");

resultTextArea.setColumns(20);
resultTextArea.setRows(5);
jScrollPane1.setViewportView(resultTextArea);

startButton.setText("Scan");
startButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
startButtonActionPerformed(evt);
}
});

clearButton.setText("Clear");
clearButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
clearButtonActionPerformed(evt);
}
});

portMaxTextField.setText("1000");

jProgressBar1.setStringPainted(true);

timeOutSpinner.setModel(new javax.swing.SpinnerNumberModel(15, 0, 999999, 1));

jLabel4.setText("-");

stopButton.setText("Stop");
stopButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
stopButtonActionPerformed(evt);
}
});

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel1))
.addGap(21, 21, 21)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(hostNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(timeOutSpinner)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addGap(18, 18, 18)
.addComponent(portMinTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel4)
.addGap(12, 12, 12)
.addComponent(portMaxTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jProgressBar1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(startButton)
.addGap(18, 18, 18)
.addComponent(stopButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 46, Short.MAX_VALUE)
.addComponent(clearButton)
.addGap(32, 32, 32))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(hostNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(timeOutSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(portMinTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(portMaxTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 23, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(startButton)
.addComponent(clearButton)
.addComponent(stopButton))
.addContainerGap())
);

pack();
}// </editor-fold>

private void startButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
breakPoint = false;
taskPortScanner = new doSomeStuff();
taskPortScanner.execute();
startButton.setEnabled(false);
clearButton.setEnabled(false);
System.out.println("Starting portscanner...");

}

private void clearButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
resultTextArea.setText(null);
jProgressBar1.setValue(0);
System.out.println("Clearing results...");
}

private void stopButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
breakPoint = true;
startButton.setEnabled(true);
clearButton.setEnabled(true);
}

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(PortScanner.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(PortScanner.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(PortScanner.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(PortScanner.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>

/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new PortScanner().setVisible(true);
}
});
}

// Variables declaration - do not modify
private javax.swing.JButton clearButton;
private javax.swing.JTextField hostNameTextField;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JProgressBar jProgressBar1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField portMaxTextField;
private javax.swing.JTextField portMinTextField;
private javax.swing.JTextArea resultTextArea;
private javax.swing.JButton startButton;
private javax.swing.JButton stopButton;
private javax.swing.JSpinner timeOutSpinner;
// End of variables declaration
}

最佳答案

您需要考虑将长时间运行的扫描任务移出事件调度线程,以保持 UI 响应。看看使用 Swing Worker 来实现这一点。

http://en.wikipedia.org/wiki/SwingWorker#The_event_dispatching_thread_problem

http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html

关于JFrame 中的 Java 多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26449342/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com