corner imagecorner image
FeaturesPluginsDocs & SupportCommunityPartners

Serviço Web passando dados binários, parte 6: Criando o cliente Swing

Baixe a amostra

O objeto deste exercício é criar um cliente p;ara o serviço Web criado e implantado anteriormente e, em seguida, adicionar uma interface de GUI a esse cliente. A interface exibe as imagens que o serviço Web passa como dados binários.

Tutoriais desta trilha

 O conteúdo desta página se aplica ao IDE NetBeans 6.1
  1. Visão geral
  2. Criando o módulo EJB
  3. Criando o serviço Web
  4. Testando o serviço Web
  5. Modificando o esquema e os arquivos WSDL para passar dados binários
  6. => Criando o cliente Swing
  7. Registrando e otimizando o serviço Web

Criando o cliente Swing

No procedimento seguinte, você cria uma aplicação Web. Nessa aplicação, você cria um cliente que consome o serviço Web criado e modificado em tutoriais anteriores. Em seguida, você adiciona um JFrame à aplicação Web e cria uma interface GUI nele, usando componentes Swing. Finalmente, você vincula os componentes Swing ao código do cliente de serviço Web.

Para criar o cliente Swing :

  1. Escolha Arquivo > Novo projeto (Ctrl-Shift-N). É exibido o assistente para Novo projeto. Selecione Aplicativo Java na categoria Java. Clique em Próximo. O assistente para Novo aplicativo Java se abre. Digite FlowerClient em Nome do projeto e clique em Terminar. O IDE cria um novo projeto de aplicativo Java.
  2. Clique com o botão direito do mouse no nó do projeto FlowerClient e escolha Novo > Cliente de serviço Web no menu de contexto. O assistente para Novo cliente de serviço Web se abre. Selecione o botão de opção URL WSDL e cole a URL do arquivo WSDL nesse campo. Por padrão, a URL é http://localhost:8080/FlowerService/FlowerService?WSDL. Clique em Terminar. O IDE baixa o arquivo WSDL, adiciona stubs de cliente para interagir com o serviço Web, e adiciona nós à janela Projetos no projeto de aplicativo Java, como mostrado abaixo:


    Visualizaçao Projetos mostrando o cliente de serviço Web

  3. Clique com o botão direito do mouse no nó FlowerClient e selecione Novo > JFrame. Chame o quadro de FlowerFrame.
  4. Adicione o JPanel ao FlowerFrame. Expanda-o para preencher o FlowerFrame inteiro. Chame o painel de gardenFlowersPanel.
  5. Adicione os seguintes componentes Swing ao gardenFlowersPanel, começando do início do painel. (Para um tutorial sobre componentes Swing, consulte Criando uma GUI Swing no NetBeans IDE):
    • Label. nome da variável: titleLabel, texto: Garden Flowers, posição: Centralizado no início. Talvez você queira colocar o texto em negrito e/ou aumentar o tamanho da fonte.
    • ButtonGroup. nome da variável: buttonGroup1.
    • Adicione os quatro botões de opção seguintes em uma linha horizontal abaixo de titleLabel. Nas propriedades de cada botão, defina-o como um membro de buttonGroup1. Botões de opção em buttonGroup1
      Nome da variável Selecionado Texto
      asterRadioButton true Aster
      honeysuckleRadioButton false Honeysuckle
      roseRadioButton false Rose
      sunflowerRadioButton false Sunflower
    • JScrollPane. nome da variável: mainScrollPane. posição: abaixo dos botões de opção, preenchendo o espaço horizontal e sobre dois terços do espaço vertical restantes.
      • JPanel. nome da variável: mainPanel. layout: Borda. posição: preenchendo o mainScrollPane.
      • JButton. nome da variável: mainPictureButton. texto: Esperando pela imagem... posição: em mainPanel (Devido ao layout Borda do painel, o botão preencherá automaticamente o espaço inteiro.)
    • JScrollPane. nome da variável: thumbnailScrollPane. posição: abaixo dos botões de opção, preenchendo o espaço horizontal e todo o espaço vertical restante.
      • JPanel. nome da variável: thumbnailPanel. layout: Grade. posição: preenchendo o thumbnailScrollPane. O layout Grade significa que os quatro botões seguintes serão do mesmo tamanho e preencherão completamente o thumbnailPanel. Botões no thumbnailPanel
        Nome da variável Texto
        asterButton Esperando...
        honeysuckleButton Esperando...
        roseButton Esperando
        sunflowerButton Esperando...

    Nesse ponto, o FlowerFrame deve ter a seguinte aparência:
    Quadro Flower concluído mostrando os textos do botão em vez de imagens

  6. No editor de código-fonte, inicialize FlowerFrame da seguinte forma:">
  7. No editor de código-fonte, inicialize FlowerFrame da seguinte forma:
    public static final String[] FLOWERS = {"aster", "honeysuckle", "rose", "sunflower"};
    private Map<String, Image> flowers;
    
    public FlowerFrame(Map<String, Image> flowers) {
    
        this.flowers = flowers;
        for (String flower:FLOWERS) {
            flowers.put(flower,null);
        }
    
        initComponents();
    
        setTitle("Garden Flowers [waiting for picture]");
    
        ItemListener rbListener = new RBListener();
        asterRadiobutton.addItemListener(rbListener);
        honeysuckleRadiobutton.addItemListener(rbListener);
        roseRadiobutton.addItemListener(rbListener);
        sunflowerRadiobutton.addItemListener(rbListener);
    
        ActionListener bListener = new ButtonListener();
        asterButton.addActionListener(bListener);
        honeysuckleButton.addActionListener(bListener);
        roseButton.addActionListener(bListener);
        sunflowerButton.addActionListener(bListener);
    
                } 
  8. Quando um JRadioButton é clicado, queremos mostrar uma nova imagem no botão principal:
    private class RBListener implements ItemListener {
    
        public void itemStateChanged(ItemEvent e) {
            showFlower();
        }
    
    }
    
    void showFlower() {
        Image img = null;
        if (asterRadiobutton.isSelected()) {
            img = flowers.get("aster");
            if (img != null) {
                mainPictureButton.setIcon(new ImageIcon(img));
                setTitle("Garden Flowers [Aster]");
            }
        } else if (honeysuckleRadiobutton.isSelected()) {
            img = flowers.get("honeysuckle");
            if (img != null) {
                mainPictureButton.setIcon(new ImageIcon(img));
                setTitle("Garden Flowers [Honeysuckle]");
            }
    
        } else if (roseRadiobutton.isSelected()) {
            img = flowers.get("rose");
            if (img != null) {
                mainPictureButton.setIcon(new ImageIcon(img));
                setTitle("Garden Flowers [Rose]");
            }
        } else if (sunflowerRadiobutton.isSelected()) {
            img = flowers.get("sunflower");
            if (img != null) {
                mainPictureButton.setIcon(new ImageIcon(img));
                setTitle("Garden Flowers [Sunflower]");
            }
        }
        if (img == null) {
            mainPictureButton.setIcon(null);
            setTitle("Garden Flowers [waiting for picture]");
        } else mainPictureButton.setText("");
                }
  9. Quando um JButton é clicado, selecionamos o JRadioButton relacionado:
    private class ButtonListener implements ActionListener {
    
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == asterButton) asterRadiobutton.setSelected(true);
            else if (e.getSource() == honeysuckleButton) honeysuckleRadiobutton.setSelected(true);
            else if (e.getSource() == roseButton) roseRadiobutton.setSelected(true);
            else if (e.getSource() == sunflowerButton) sunflowerRadiobutton.setSelected(true);
        }
                }
  10. Na classe Main, o método setThumbnails será chamado, que está no FlowerFrame:
    void setThumbnails(Map<String, Image> thumbs) {
        Image img = thumbs.get("aster");
        if (img != null) {
            asterButton.setIcon(new ImageIcon(img));
            asterButton.setText("");
        }
        img = thumbs.get("honeysuckle");
        if (img != null) {
            honeysuckleButton.setIcon(new ImageIcon(img));
            honeysuckleButton.setText("");
        }
        img = thumbs.get("rose");
        if (img != null) {
            roseButton.setIcon(new ImageIcon(img));
            roseButton.setText("");
        }
        img = thumbs.get("sunflower");
        if (img != null) {
            sunflowerButton.setIcon(new ImageIcon(img));
            sunflowerButton.setText("");
        }
                }
  11. Corrija as importações em FlowerFrame.
  12. Preencha a classe Main.java da seguinte forma:
    public class Main {
    
         private static int downloadedPictures;
    
         public static void main(String[] args) {
    
            final Map<String,Image> flowers = new HashMap<String,Image>(4);
            final Map<String,Image> thumbs = new HashMap<String,Image>(4);
    
            // Show the FlowerFrame:
            final FlowerFrame frame = new FlowerFrame(flowers);
            frame.setVisible(true);
    
            // The client connects to the service with this code:
            FlowerService_Service service = new FlowerService_Service();
            final FlowerService port = service.getFlowerServicePort();
    
            Runnable[] tasks = new Runnable[4];
    
            // The web service getFlower operation
            // is called 4 times, each in a separate thread.
            // When the operation finishes the picture is shown in
            // a specific button.
            for (int i=0; i<4;i++) {
                final int index = i;
                tasks[i] = new Runnable() {
                    public void run() {
                        try {
    
                            // Call the getFlower operation
                            // on the web service:
                            Image img = port.getFlower(FlowerFrame.FLOWERS[index]);
                            System.out.println("picture downloaded: "+FlowerFrame.FLOWERS[index]);
    
                            // Add strings to the hashmap:
                            flowers.put(FlowerFrame.FLOWERS[index],img);
    
                            // Call the showFlower operation
                            // on the FlowerFrame:
                            frame.showFlower();
    
                        } catch (IOException_Exception ex) {
                            ex.printStackTrace();
                        }
                        downloadedPictures++;
                    }
                };
                new Thread(tasks[i]).start();
            }
            // The web service getThumbnails operation is called
            // in a separate thread, just after the previous four threads finish.
            // When the images are downloaded, the thumbnails are shown at
            // the bottom of the frame.
            Runnable thumbsTask = new Runnable() {
                public void run() {
                    try {
                        while (downloadedPictures < 4) {
                            try {Thread.sleep(100);} catch (InterruptedException ex) {}
                        }
    
                        // Call the getThumbnails operation
                        // on the web service:
                        List<Image> images = port.getThumbnails();
                        System.out.println("thumbs downloaded");
    
                        if (images != null && images.size() == 4) {
                            for (int i=0;i<4;i++) {
                                thumbs.put(FlowerFrame.FLOWERS[i],images.get(i));
                            }
                            frame.setThumbnails(thumbs);
                        }
                    } catch (IOException_Exception ex) {
                        ex.printStackTrace();
                    }
                }
            };
            new Thread(thumbsTask).start();
        }
    
                }
  13. Corrija as importações em Main.java.
  14. Remova o método main existente na classe FlowerFrame.

O serviço Web agora está completo, com o código que interage com o serviço Web que delega para o módulo EJB para expor suas imagens. Clique com o botão direito do mouse no cliente e em Executar. O aplicativo Swing deve ser iniciado e, depois de um tempo, é preenchido com as imagens recebidas do serviço Web.

Próxima etapa:

Registrando e otimizando o serviço

Para enviar comentários e sugestões, obter suporte e se manter informado sobre os mais recentes desenvolvimentos dos recursos de desenvolvimento de Java EE do NetBeans IDE, inscreva-se na lista de endereçamento de .