2

I want this code work with update JProgressBar and JTextArea while scanner is working, but I don't know how implement Threading. Is it possible?

This is my code:

UPDATED: It's a working version now, with "Stop" function. I added a "breakPoint" variable to break out from the for loop.

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 } 
13
  • Your code should be posted here, in your question. Not at pastebin. Commented Oct 19, 2014 at 9:57
  • Can't post the code because I got an error: "It looks like your post is mostly code... " Commented Oct 19, 2014 at 10:03
  • @NorbertKlár what's the problem you get when run this? Commented Oct 19, 2014 at 10:09
  • 1
    @trashgod I don't know how use it in this code. Commented Oct 19, 2014 at 15:57
  • 1
    There are examples in the API and in the swingworker tag Commented Oct 20, 2014 at 2:08

1 Answer 1

3

You need to look at moving the long running scan task out of the Event dispatching thread to keep the UI responsive. Look at using a Swing Worker to achieve this.

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

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.