java - 警告窗口,直到方法在 Swing 中完成执行

标签 java swing background alert execution

显示的图像是我使用 Swing 制作的窗口。

当我单击提交按钮时,如何创建警报窗口,并且警报应该显示,直到执行的操作完成(警报+代码应该在后台运行)?

这是我的代码片段:

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();
    }
}

图像窗口:

IMAGEWINDOW

最佳答案

只需单击开始,然后等待JDialog自动关闭。这可能会给你一个关于如何处理这件事的轻微想法:-)

请看一下这个例子:

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);
    }
}

关于java - 警告窗口,直到方法在 Swing 中完成执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18674723/

相关文章:

java - GWT RichTextArea 在 Chome/Safari iOS 上得到扩展

iOS 区域监控 : Is my app crashing or is this expected?

java - 在饼图切片中间绘制带三角形的饼图

Java布局忽略属性文档

javascript - 如何在嵌入式样式表中使用 javascript 变量作为背景?

algorithm - 我如何获得洪水填充算法来应对封闭的圆圈?

java - 从 HTMLDocument 中获取单个元素的文本内容

Java 问题 : Is it possible to have a switch statement within another one?

java - 错误捕获/异常处理

java - 当鼠标在 JFrame 内移动时,Swing Timer 停止调用 actionPerformed()