POO - II PROF.: JEAN CARLO MENDES [email protected] HTTP://.
Transcript of POO - II PROF.: JEAN CARLO MENDES [email protected] HTTP://.
![Page 2: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/2.jpg)
Interface Gráfica Elementos básicos para se criar uma GUI estão
em dois pacotes
Java.awt: Abstract Window Toolkit (classes básicas) Javax.swing: Swing componentes – fornece
alternativas para os componentes da awt e possuem correspondentes (ex. Button e Jbutton).
Swing é implementada toda em Java
![Page 3: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/3.jpg)
Interface Gráfica Swing é parte de um conjunto mais genérico
chamado JFC (Java Foundation Class)
JFC Coleção de pacotes para criação de aplicações completas para desktop Interface gráfica (GUI) Funcionalidades e interatividade
![Page 4: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/4.jpg)
JFC - Características Componentes GUI Swing Suporte a “Look and Feel” LaF API para acessibilidade API Java 2D Suporte a Drag and Drop Internacionalização
![Page 5: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/5.jpg)
Um pouco da história Quando o java 1.0 foi lançado continha apenas
a AWT Lida com elementos de interface delegando a criação e o
comportamento desses elementos ao conjunto de ferramentas GUI nativo da plataforma
Problema:Difícil de escrever uma biblioteca gráfica
portátil de qualidade!
![Page 6: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/6.jpg)
Um pouco da história Em 1996 a Netscape criou uma biblioteca de
GUI chamada IFC (Internet Foundation Classes)
Elementos da interface com o usuário eram pintados em janelas em branco
Comportamento idênticos
A Sun trabalhou com a Netscape para aperfeiçoar essa abordagem, criando uma biblioteca chamada “Swing”
![Page 7: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/7.jpg)
Swing javax.swing.* Biblioteca oficial da Java GUI Todo programa que usa Swing deve ter pelo
menos um componente do tipo container. Principais Características:
Independente de plataforma Personalizável Extensível Configurável Leve
![Page 8: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/8.jpg)
![Page 9: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/9.jpg)
Containers e componentes Uma interface gráfica em Java é baseada em dois
elementos: containers: servem para agrupar e exibir outros
componentes componentes: botões, labels, scrollbars, etc. Dessa forma, todo programa que ofereça uma interface vai
possuir pelo menos um container, que pode ser: – JFrame: janela principal do programa – JDialog: janela para diálogos – JApplet: janela para Applets
![Page 10: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/10.jpg)
Container Descendentes da classe java.awt.Container Componentes que podem conter outros componentes Oferece suporte para desenho e tratamento de eventos
![Page 11: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/11.jpg)
Containers e componentes • Para construirmos uma interface gráfica em JAVA,
adicionamos componentes (Botões, Menus, Textos, Tabelas, Listas, etc.) sobre a área da janela.
• Por essa razão a área da janela é um container, ou seja, um elemento capaz de armazenar uma lista de componentes.
![Page 12: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/12.jpg)
Containers top level Provê o suporte que os componentes swing necessitam
para realizar o desenho da tela e o tratamento de eventos.
– JFrame: Objeto que implementa janela principal – JDialog: Objeto que implementa janela secundária – JApplet: Objeto que implementa uma área de visualização
de applets em browsers;
![Page 13: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/13.jpg)
Containers - Exemplo
![Page 14: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/14.jpg)
Testar... Redimensione interativamente a janela da aplicação e
observe o comportamento dos botões da interface. Troque o argumento de FlowLayout(), para FlowLayout
(FlowLayout.LEFT) e observe. Adicione no programa acima, os seguintes componentes:
JLabel label = new JLabel("Exemplo de texto:");caixa.add(label); JTextField campo = new JTextField(15);caixa.add(campo); janela.pack(); // Redimensiona a janela
![Page 15: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/15.jpg)
Criando uma janela Uma janela em Java é representada por um objeto da
classe Window.
![Page 16: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/16.jpg)
Criando uma janela
![Page 17: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/17.jpg)
JFrame Um frame é uma janela que, por default, tem decorações
tais como:– Uma borda– Um título– Botões para minimizar e fechar a janela
Aplicações com uma GUI usam, tipicamente, pelo menos um frame.
![Page 18: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/18.jpg)
JFrame
![Page 19: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/19.jpg)
JFrame
![Page 20: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/20.jpg)
Component e container Desde que a classe Container é uma sub-classe da
classe Component, todo objeto container é também um Componente.
A diferença básica entre um objeto JFrame e um objeto Window é que o JFrame representa a janela principal de uma aplicação.
Antes de criar um objeto Window, é preciso criar um objeto JFrame.
Como a classe JDialog deriva diretamente da classe Window, pode-se criar objetos JDialog somente no contexto de um objeto JFrame.
![Page 21: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/21.jpg)
Component e container JFrame: Um objeto desta classe possui uma barra de título e
características para receber menus e outros componentes.
JDialog: Usada para definir janelas de diálogo para entrada de dados. Normalmente usada em resposta a uma opção de menu selecionada. Definida em função de um objeto JFrame.
JApplet: Classe base para applets Java. É possível desenhar e adicionar menus e outros componentes em um JApplet.
JComponent: As subclasses de JComponent definem um conjunto de componentes standard (menus, botões, checkboxes, etc.)
![Page 22: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/22.jpg)
Component e container Outros componentes:
Button (JButton) Menu (JMenu) Text Component (JTextComponent) List (JList) Table (JTable)
![Page 23: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/23.jpg)
Testar...
![Page 24: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/24.jpg)
Testar...
![Page 25: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/25.jpg)
E agora??
Como “organizar” os componentes no Jpanel?
Java oferente diversos “layouts” para a estruturação dos componentes
Para o JPanel temos, por exemplo, o FlowLayout que distribui os componentes na horizontal
![Page 26: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/26.jpg)
Layouts Já foi visto que interfaces em JAVA são
construídas na medida em que adicionamos Components a Containers.
Os Containers são responsáveis então por manter os componentes visíveis, repassar os eventos, etc.
![Page 27: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/27.jpg)
Layouts Como a filosofia da linguagem JAVA é de que os
programas sejam extremamente portáveis, a filosofia da interface visa também ser extremamente adaptável.
Por essa razão a disposição dos Components sobre o Container não é indicada por um par ordenado (x,y) como na maioria das bibliotecas de construção de interface com o usuário (MFC - Microsoft, OWL - Borland etc).
![Page 28: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/28.jpg)
LayoutsÉ possível definir seus próprios Layouts,
mas a linguagem oferece um conjunto de Layouts básicos que simplificam o trabalho.
O arranjo dos componentes no container é gerenciado por um LayoutManager
![Page 29: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/29.jpg)
LayoutsA vantagem da existência de um
LayoutManager é que a apresentação dos componentes se adapta quando do redimensionamento da janela
A desvantagem é o pouco domínio que o programador tem da posição dos componentes com alguns LayoutManagers
![Page 30: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/30.jpg)
Flow LayoutComponentes distribuídos sequencialmente da
esquerda para a direita e de cima para baixo;Respeita o tamanho dos componentes mesmo que
não haja espaço no ContainerPercebam a diferença de aparência entre os botões
“dois” e “três”
![Page 31: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/31.jpg)
![Page 32: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/32.jpg)
Grid LayoutSimilar ao FlowLayout, mas cada
componente é alocado em uma célula de igual tamanho.
Pode-se definir um vetor ou matriz de células nas quais os componentes são alocados
Divide a área em uma gradeDispõe os elementos da esquerda para a
direita e de coma para baixoTodas as células de igual tamanho
![Page 33: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/33.jpg)
![Page 34: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/34.jpg)
Outro Exemplo de Grid
![Page 35: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/35.jpg)
![Page 36: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/36.jpg)
![Page 37: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/37.jpg)
GridBagLayoutSemelhante ao GridLayout, porém as divisões podem
ter tamanhos diferentes
Utiliza a classe GridBagConstraints para dimensionar e posicionar os componentes
É flexível, porém complicado de usar. Sendo assim é escolhido somente quando os outros tipos não se encaixam na necessidade
![Page 38: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/38.jpg)
BorderLayout Layout padrão para a maioria das aplicações
Componentes são adicionados especificando a área que irá ocupar.
Divide o Container em cinco regiões: BorderLayout.CENTER BorderLayout.NORTH BorderLayout.EAST BorderLayout.SOUTH BorderLayout.WEST
![Page 39: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/39.jpg)
BorderLayout
![Page 40: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/40.jpg)
BoxLayoutRespeita o tamanho dos componentesColoca os componentes em linha ou coluna
BoxLayout.X_AXIS para componentes em linhaBoxLayout.Y_AXIS para componentes em coluna
![Page 41: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/41.jpg)
![Page 42: POO - II PROF.: JEAN CARLO MENDES JEAN.MENDES@GMAIL.COM HTTP://.](https://reader036.fdocuments.net/reader036/viewer/2022062319/552fc16b497959413d8ec527/html5/thumbnails/42.jpg)