0

The shown image is my window made using Swing.

How do I create an alert window when i click Submit button and the alert should display until the action performed is completed(alert+code should run in background) ?

Here is my code snippet :

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    //alert window should start here when button performed
    //and end based on the output i get
    DefaultHttpClient httpclient  = new DefaultHttpClient();
    jLabel3.setText("");
    try {
        httpclient.getCredentialsProvider().setCredentials(
            new AuthScope(getHost(), AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(getUser(), getPass()));                    
        HttpResponse response = null;
        HttpEntity entity = null;
        try {
            response = httpclient.execute(httpget);
            if(response.getStatusLine().getStatusCode()==500) {
                jLabel3.setText("Such Goods Movement does not exist / You do not have permssions for the entered.");
                //end here or 
            } else if(response.getStatusLine().getStatusCode()==401) {
                System.out.println(response);
                jLabel3.setText("Auth Failed");
                //end here or soon based on the event
            }
            entity = response.getEntity();
            System.out.println(entity);
            if (entity != null) {
                InputStream instream = entity.getContent();
                System.out.println(instream);
                BufferedReader reader = new BufferedReader(
                    new InputStreamReader(instream));
                String inputLine;
                String xmlText="";
                while ((inputLine = reader.readLine()) != null)
                    xmlText = xmlText+inputLine+"\n";
                System.out.println(xmlText);
                try {
                    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                    InputSource is = new InputSource();
                    is.setCharacterStream(new StringReader(xmlText));
                    DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
                    model.setRowCount(0);
                    Document doc = db.parse(is);
                    NodeList nodes = doc.getElementsByTagName("MaterialMgmtInternalMovementLine");
                    for (int i = 0; i < nodes.getLength(); i++) {
                        Element element = (Element) nodes.item(i);
                        getListGRNLine(element);
                    }
                } catch (SAXException ex) {
                    Logger.getLogger(GoodsReceipt.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ParserConfigurationException ex) {
                    Logger.getLogger(GoodsReceipt.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } catch(UnknownHostException e){
            jLabel3.setText("URL Not Found / Check Internet Connectivity");
        } catch(NoRouteToHostException f){
            jLabel3.setText("URL Not Found / Check Internet Connectivity");
        } catch (IOException ex) {
            Logger.getLogger(GoodsReceipt.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            EntityUtils.consume(entity);
        } catch (IOException ex) {
            Logger.getLogger(GoodsReceipt.class.getName()).log(Level.SEVERE, null, ex);
        }
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(GoodsReceipt.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

Image Window :

IMAGEWINDOW

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Mani Deep
  • 1,298
  • 2
  • 17
  • 33
  • http://i.imgur.com/sqSs9E1.png this is the link for my image (window) – Mani Deep Sep 07 '13 at 15:12
  • 1
    Please have a look at [SwingWorker](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html). At the place of the comment in the `actionPerformed()` method, put a `JDialog` to visible state with alert message, put rest of the code inside `doInBackground()` method of the `SwingWorker` and inside `done()` method, simply dispose of the `JDialog`. You have to place calls like `JLabel.setText()` on the `Event Dispatcher Thread`. If it is the result of some intermediate thingy, then simply call `publish()` and perform `JLabel.setText()` inside `process()` method. That is it :-) – nIcE cOw Sep 07 '13 at 16:25
  • Though, if you may provide a simple, short, compilable([SSCCE](http://sscce.org/)). That would be helpful, for us to provide a working example :-) – nIcE cOw Sep 07 '13 at 16:31
  • ok i will look into it. – Mani Deep Sep 07 '13 at 16:32
  • once I put a jDialog as in code there are many places that the background should stop. can u please provide me an example? – Mani Deep Sep 07 '13 at 16:34
  • @nIcEcOw ill be waiting for ur answer thank you in advance :) and also thank you for editing my post :) – Mani Deep Sep 07 '13 at 17:07

1 Answers1

2

Simply click START, and wait for the JDialog to close automatically. This might can give you, the slight idea, as to how to go about this thingy :-)

Please have a look at this example :

import java.awt.*;
import java.awt.event.*;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;

public class SwingWorkerExample {

    private JFrame frame;
    private JLabel statusLabel;
    private JTextArea tArea;
    private JButton startButton;
    private JButton stopButton;

    private MyDialog dialog;

    private BackgroundTask backgroundTask;

    private ActionListener buttonActions =
                            new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            JButton source = (JButton) ae.getSource();
            if (source == startButton) {
                startButton.setEnabled(false);
                stopButton.setEnabled(true);
                backgroundTask = new BackgroundTask();
                backgroundTask.execute();
                dialog = new MyDialog(frame, true);
                dialog.displayDialog();
            } else if (source == stopButton) {
                backgroundTask.cancel(true);
                stopButton.setEnabled(false);
                startButton.setEnabled(true);
            }
        }
    };

    private void displayGUI() {
        frame = new JFrame("Swing Worker Example");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        JPanel contentPane = new JPanel();
        contentPane.setBorder(
            BorderFactory.createEmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(5, 5));

        statusLabel = new JLabel("Status Bar", JLabel.CENTER);

        tArea = new JTextArea(20, 20);
        tArea.setWrapStyleWord(true);
        tArea.setLineWrap(true);
        tArea.setBorder(
            BorderFactory.createTitledBorder("Chat Area : "));
        JScrollPane chatScroller = new JScrollPane();
        chatScroller.setViewportView(tArea);

        startButton = new JButton("Start");
        startButton.addActionListener(buttonActions);
        stopButton = new JButton("Stop");
        stopButton.setEnabled(false);
        stopButton.addActionListener(buttonActions);
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(startButton);
        buttonPanel.add(stopButton);

        contentPane.add(statusLabel, BorderLayout.PAGE_START);
        contentPane.add(chatScroller, BorderLayout.CENTER);
        contentPane.add(buttonPanel, BorderLayout.PAGE_END);

        frame.setContentPane(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private class BackgroundTask extends SwingWorker<Void, String> {

        private String textInput;
        private int counter = 0, count = 0;

        private String[] arrNames = { "US Rates Strategy Cash",
            "Pavan Wadhwa(1-212) 844-4597", "Srini Ramaswamy(1-212) 844-4983",
            "Meera Chandan(1-212) 855-4555", "Kimberly Harano(1-212) 823-4996",
            "Feng Deng(1-212) 855-2555", "US Rates Strategy Derivatives",
            "Srini Ramaswamy(1-212) 811-4999",
            "Alberto Iglesias(1-212) 898-5442",
            "Praveen Korapaty(1-212) 812-3444", "Feng Deng(1-212) 812-2456",
            "US Rates Strategy Derivatives", "Srini Ramaswamy(1-212) 822-4999",
            "Alberto Iglesias(1-212) 822-5098",
            "Praveen Korapaty(1-212) 812-3655", "Feng Deng(1-212) 899-2222" };

        public BackgroundTask() {
            statusLabel.setText((this.getState()).toString());
            System.out.println(this.getState());
        }

        @Override
        protected Void doInBackground() {           
            System.out.println(this.getState());
            while (!isCancelled()) {
                counter %= arrNames.length;
                System.out.format("Count : %d%n", count);
                publish(arrNames[counter]);
                counter++;
                count++;
                if (count == 10000) {
                    this.cancel(true);
                }
            }
            System.out.println(this.getState());            
            return null;
        }

        @Override
        protected void process(java.util.List<String> messages) {
            statusLabel.setText((this.getState()).toString());
            for (String message : messages)
                tArea.append(message + "\n");
        }

        @Override
        protected void done() {
            System.out.println("DONE called");
            dialog.dispose();
        }
    }

    public static void main(String[] args) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                new SwingWorkerExample().displayGUI();
            }
        };
        EventQueue.invokeLater(runnable);
    }
}

class MyDialog extends JDialog {

    private JLabel alertLabel;
    private ImageIcon icon;

    public MyDialog(Frame owner, boolean isModal) {
        super(owner, isModal);
        try {
            icon = new ImageIcon(ImageIO.read(new URL(
                "http://i.imgur.com/Aoluk8n.gif")));        
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void displayDialog() {
        alertLabel = new JLabel("Alert Message", icon, JLabel.CENTER);
        JPanel contentPane = new JPanel();
        contentPane.add(alertLabel);

        setContentPane(contentPane);
        pack();
        setVisible(true);
    }
}
nIcE cOw
  • 24,468
  • 7
  • 50
  • 143
  • this "JDialog" window is starting and closing in just few seconds.. unable to understand it completely – Mani Deep Sep 07 '13 at 17:58
  • @ManiDeep : Inside the `while(isCancelled())` under if condition, use `count == 30000` (this is actually simulating a long running task that you are performing), if you want the dialog to remain for a long duration. Inside this `while` you will place all the code, that you have written, simply start the `SwingWorker` from the button, display the dialog and then close the `JDialog` when it seems fit to you, by calling `this.cancel(true)`. Remove my answer as the correct answer, until you understand the thingy, so that others can guide you as well :-) – nIcE cOw Sep 07 '13 at 18:11
  • unable to attach this to my program :( can i get an another solution.. so that it works for me – Mani Deep Sep 08 '13 at 06:17
  • @ManiDeep : Here is one another way of [closing a JDialog](http://stackoverflow.com/a/18107432/1057230), though again you have to find the logic to make it work for your case. You simply have to make a function and write everything what is written inside the `actionPerformed()` method, and simply call this method, when you need to close the `JDialog`. – nIcE cOw Sep 08 '13 at 14:56