Aula 4
Transcrição
Aula 4
Aula 4 – Programando Interfaces Gráficas Orientadas a Objeto - Parte 2 Planejamento • • • Classe, Objeto, Método,Herança, polimorfismo, Encapsulamento • Introdução a linguagem Java • • • Introdução a Ambientes Integrados de Desenvolvimento Introdução ao Ambiente Eclipse Desenvolvimento de Programas básicos (modo texto) Aula 2 Comandos de controle: if, while,forClasses: String, Integer, DateBibliotecas Básicas: System, java, • • 4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8 4.9 4.10 4.11 4.12 Introdução Conceitos Básicos • • Sumário Aula 1 Aula 3 • Programando Interfaces Gráficas com Java – Parte I • Aula 4 • Programando Interfaces Gráficas com Java – Parte II • Introdução Componente JTextArea Criando uma classe customizada de JPanel Uma subclasse JPanel que trata seus próprios eventos JSlider Windows: Additional Notes Usando Menus com Frames JPopupMenu Pluggable Look-and-Feel JDesktopPane and JInternalFrame JTabbedPane Layout Managers: BoxLayout and GridBagLayout Aula 5 5.1. Introdução a Design Patterns 5.2. Programação concorrente (Threads) Paulo André Castro ITA – Stefanini POO Paulo André Castro 1 POO ITA – Stefanini 2 ITA – Stefanini 4 4.2 JTextArea 4.1 Introdução • Componentes GUI Avançados • JTextArea – Text areas – Sliders – Menus – Area for manipulating multiple lines of text – extends JTextComponent • Multiple Document Interface (MDI) • Layout Managers Avançados – BoxLayout – GridBagLayout Paulo André Castro 1 2 3 4 5 6 7 8 9 10 11 12 13 4 15 16 17 18 19 20 21 22 23 24 25 ITA – Stefanini POO // Fig. 4.1: TextAreaDemo.java // Copying selected text from one textarea to another. import java.awt.*; import java.awt.event.*; import javax.swing.*; 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 public class TextAreaDemo extends JFrame { private JTextArea textArea1, textArea2; private JButton copyButton; // set up GUI public TextAreaDemo() { super( super ( "TextArea Demo" ); Create Box container for organizing GUI components Box box = Box.createHorizontalBox(); String string = "This is a demo string to\ to\n" + "illustrate copying text\ text\nfrom one textarea to \n" + "another textarea using an\ an\nexternal event\ event\n"; n"; // set up textArea1 textArea1 = new JTextArea( string, 10, 10, 15 ); box.add( new JScrollPane( textArea1 ) ); Paulo André Castro POO Populate JTextArea with String, then add to Box ITA – Stefanini Paulo André Castro 3 5 POO // set up copyButton copyButton = new JButton( "Copy >>>" ); box.add( copyButton ); copyButton.addActionListener( new ActionListener() { // anonymous inner class // set text in textArea2 to selected text from textArea1 public void actionPerformed( ActionEvent event ) { textArea2.setText( textArea1.getSelectedText() ); } When user presses JButton, textArea1’s highlighted text is copied into textArea2 } // end anonymous inner class ); // end call to addActionListener // set up textArea2 textArea2 = new JTextArea( 10, 10, 15 ); textArea2.setEditable( false ); box.add( new JScrollPane( textArea2 ) ); Instantiate uneditable JTextArea // add box to content pane Container container = getContentPane(); // place in BorderLayout.CENTER container.add( box ); Paulo André Castro POO ITA – Stefanini 6 1 52 53 54 55 56 57 58 59 60 61 62 63 4.3 Criando uma classe customizada de JPanel setSize( 425, 425, 200 ); setVisible( true ); } // end constructor TextAreaDemo public static void main( String args[] ) { TextAreaDemo application = new TextAreaDemo(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } • Extend JPanel to create new components – Dedicated drawing area • Method paintComponent of class JComponent } // end class TextAreaDemo Paulo André Castro ITA – Stefanini POO 1 // Fig. 4.2: CustomPanel.java 2 // A customized JPanel class. 3 import java.awt.*; 4 import javax.swing.*; 5 6 public class CustomPanel extends JPanel { 7 public final static int CIRCLE = 1, SQUARE = 2; Store integer representing 8 private int shape; shape to draw 9 // use shape to draw an oval or rectangle 10 11 public void paintComponent( Graphics g ) 12 { 13 super.paintComponent( super.paintComponent( g ); Override method 14 paintComponent of if ( shape == CIRCLE ) 15 class JComponent to 16 g.fillOval( 50, 50, 10, 10, 60, 60, 60 ); 17 else if ( shape == SQUARE ) draw oval or rectangle 18 g.fillRect( 50, 50, 10, 10, 60, 60, 60 ); 19 } 20 21 // set shape value and repaint CustomPanel 22 public void draw( int shapeToDraw ) 23 { 24 shape = shapeToDraw; 25 repaint(); Method repaint calls method paintComponent 26 } 27 28 } // end class CustomPanel Paulo André Castro 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 new ActionListener() { ITA – Stefanini POO // anonymous inner class When user presses squareButton, draw square on CustomPanel ); // end call to addActionListener circleButton = new JButton( "Circle" ); circleButton.addActionListener( new ActionListener() { // anonymous inner class // draw a circle public void actionPerformed( ActionEvent event ) { myPanel.draw( CustomPanel.CIRCLE ); } When user presses circleButton, draw circle on CustomPanel } // end anonymous inner class 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 ITA – Stefanini POO 8 // Fig. 4.3: CustomPanelTest.java // Using a customized Panel object. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class CustomPanelTest extends JFrame { private JPanel buttonPanel; private CustomPanel myPanel; private JButton circleButton, squareButton; // set up GUI public CustomPanelTest() { super( super ( "CustomPanel Test" ); // create custom drawing area myPanel = new CustomPanel(); myPanel.setBackground( Color.GREEN ); Instantiate CustomPanel object and set background to green // set up squareButton squareButton = new JButton( "Square" ); squareButton.addActionListener( Paulo André Castro 9 // draw a square public void actionPerformed( ActionEvent event ) { myPanel.draw( CustomPanel.SQUARE ); } } // end anonymous inner class Paulo André Castro 7 ITA – Stefanini POO // set up panel containing buttons buttonPanel = new JPanel(); buttonPanel.setLayout( new GridLayout( 1, 2 ) ); buttonPanel.add( circleButton ); buttonPanel.add( squareButton ); 10 Use GridLayout to organize buttons // attach button panel & custom drawing area to content pane Container container = getContentPane(); container.add( myPanel, BorderLayout.CENTER ); container.add( buttonPanel, BorderLayout.SOUTH ); setSize( 300, 300, 150 ); setVisible( true ); } // end constructor CustomPanelTest public static void main( String args[] ) { CustomPanelTest application = new CustomPanelTest(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } // end class CustomPanelTest ); // end call to addActionListener Paulo André Castro POO ITA – Stefanini 11 Paulo André Castro POO ITA – Stefanini 12 2 4.4 Uma subclasse JPanel que trata seus próprios eventos Exercício • Pergunta: Porquê inicialmente não surge nenhuma forma (círculo ou quadrado) dentro do painel? • Fazer com que o painel seja apresentado inicialmente com o círculo no seu interior • Fazer inicialização de cor de fundo do painel na classe do próprio painel. • ITA – Stefanini POO • e.g., events offered by buttons, text areas, etc. – Capable of recognizing lower-level events • e.g., mouse events, key events, etc. – Self-contained panel • Listens for its own mouse events 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SelfContainedPanel extends JPanel { private int x1, y1, x2, y2; // set up mouse event handling for SelfContainedPanel public SelfContainedPanel() { Self-contained JPanel // set up mouse listener addMouseListener( listens for MouseEvents new MouseAdapter() { // anonymous inner class // handle mouse press event public void mousePressed( MouseEvent event ) { x1 = event.getX(); Save coordinates where user y1 = event.getY(); pressed mouse button } POO ITA – Stefanini } // end anonymous inner class 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 } // end constructor SelfContainedPanel // return preferred width and height of SelfContainedPanel public Dimension getPreferredSize() { 150, return new Dimension( 150 , 100 ); } // paint an oval at the specified coordinates public void paintComponent( Graphics g ) { super.paintComponent( super .paintComponent( g ); Draw oval } } // end class SelfContainedPanel Paulo André Castro POO ITA – Stefanini 17 ITA – Stefanini POO 14 // handle mouse release event public void mouseReleased( MouseEvent event ) { x2 = event.getX(); Save coordinates where user released y2 = event.getY(); mouse button, then repaint repaint(); } } // end anonymous inner class ); // end call to addMouseListener Self-contained JPanel listens for when mouse moves // set up mouse motion listener addMouseMotionListener( new MouseMotionAdapter() { // anonymous inner class // handle mouse drag event public void mouseDragged( MouseEvent event ) { x2 = event.getX(); y2 = event.getY(); repaint(); } Paulo André Castro 15 ); // end call to addMouseMotionListener g.drawOval( Math.min( x1, x2 ), Math.min( y1, y2 ), Math.abs( x1 - x2 ), Math.abs( y1 - y2 ) ); Paulo André Castro 13 // Fig. 4.4: SelfContainedPanel.java // A selfself-contained JPanel class that handles its own mouse events. Paulo André Castro 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 – Does not support conventional events Lembrar do conceito de encapsulamento, comportamento específico de uma classe deve estar definido na própria classe e não externamente Paulo André Castro 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 • JPanel Save coordinates where user dragged mouse, then repaint POO ITA – Stefanini 16 // Fig. 4.5: SelfContainedPanelTest.java // Creating a selfself-contained subclass of JPanel that processes // its own mouse events. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SelfContainedPanelTest extends JFrame { private SelfContainedPanel myPanel; // set up GUI and mouse motion event handlers for application window public SelfContainedPanelTest() { // set up a SelfContainedPanel Instantiate SelfContaintedPanel myPanel = new SelfContainedPanel(); object and set background to yellow myPanel.setBackground( Color.YELLOW ); Container container = getContentPane(); container.setLayout( new FlowLayout() ); container.add( myPanel ); Paulo André Castro POO ITA – Stefanini 18 3 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 // set up mouse motion event handling addMouseMotionListener( new MouseMotionListener() { Register anonymous-inner-class object to handle mouse motion events // anonymous inner class // handle mouse drag event public void mouseDragged( MouseEvent event ) { setTitle( "Dragging: x=" + event.getX() + "; y=" + event.getY() ); } // handle mouse move event public void mouseMoved( MouseEvent event ) { setTitle( "Moving: x=" + event.getX() + "; y=" + event.getY() ); } 51 52 53 54 55 56 57 58 public static void main( String args[] ) { SelfContainedPanelTest application = new SelfContainedPanelTest(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } // end class SelfContainedPanelTest Display String in title bar indicating x-y coordinate where mouse-motion event occurred } // end anonymous inner class ); // end call to addMouseMotionListener setSize( 300, 300, 200 ); setVisible( true ); } // end constructor SelfContainedPanelTest Paulo André Castro POO ITA – Stefanini 19 Paulo André Castro Perguntas POO ITA – Stefanini Exercício • Porque a barra de status não apresenta a informação de posição do mouse quando, este encontra-se sobre a parte amarela • Como seria possível criar várias elipses ao invés de apenas uma ? • Criar ao invés de uma elipse um círculo, caso esteja sendo presionado a tecla Shift durante o “dragging” do mouse Paulo André Castro Paulo André Castro POO 20 ITA – Stefanini 21 POO ITA – Stefanini 22 Fig. 4.6 JSlider component with horizontal orientation 4.5 JSlider • JSlider – Enable users to select from range of integer values – Several features thumb tick mark • Tick marks (major and minor) • Snap-to ticks • Orientation (horizontal and vertical) Paulo André Castro POO ITA – Stefanini 23 Paulo André Castro POO ITA – Stefanini 24 4 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 // Fig. 4.7: OvalPanel.java // A customized JPanel class. import java.awt.*; import javax.swing.*; public class OvalPanel extends JPanel { private int diameter = 10; 10; // draw an oval of the specified diameter public void paintComponent( Graphics g ) { super.paintComponent( super .paintComponent( g ); g.fillOval( 10, 10, 10, 10, diameter, diameter ); // validate and set diameter, then repaint public void setDiameter( int newDiameter ) Set { // if diameter invalid, default to 10 diameter = ( newDiameter >= 0 ? newDiameter : 10 ); repaint(); } 52 53 54 55 56 57 58 ITA – Stefanini POO } // end class OvalPanel Instantiate OvalPanel object and set background to yellow // set up OvalPanel myPanel = new OvalPanel(); myPanel.setBackground( Color.YELLOW ); Instantiate horizontal JSlider object with min. value of 0, max. value of 200 initial thumb location at 10 and // set up JSlider to control diameter value diameterSlider = SwingConstants.HORIZONTAL, new JSlider( SwingConstants.HORIZONTAL , 0, 200, 200, 10 ); diameterSlider.setMajorTickSpacing( 10 ); diameterSlider.setPaintTicks( true ); POO ITA – Stefanini Paulo André Castro 25 public class SliderDemo extends JFrame { private JSlider diameterSlider; private OvalPanel myPanel; Paulo André Castro // used by layout manager to determine minimum size public Dimension getMinimumSize() { return getPreferredSize(); } diameter, then repaint // Fig. 4.8: SliderDemo.java // Using JSliders to size an oval. import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; // set up GUI public SliderDemo() { super( super ( "Slider Demo" ); // used by layout manager to determine preferred size public Dimension getPreferredSize() { 200, return new Dimension( 200 , 200 ); } Draw filled oval of diameter } Paulo André Castro 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 25 26 27 28 29 30 31 32 33 34 35 36 37 27 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 26 Register anonymous ChangeListener object to handle JSlider events // register JSlider event listener diameterSlider.addChangeListener( new ChangeListener() { ITA – Stefanini POO // anonymous inner class // handle change in slider value public void stateChanged( ChangeEvent e ) { myPanel.setDiameter( diameterSlider.getValue() ); } When user accesses JSlider, set OvalPanel’s diameter according to JSlider value } // end anonymous inner class ); // end call to addChangeListener // attach components to content pane Container container = getContentPane(); container.add( diameterSlider, BorderLayout.SOUTH ); container.add( myPanel, BorderLayout.CENTER ); setSize( 220, 220, 270 ); setVisible( true ); } // end constructor SliderDemo Paulo André Castro POO ITA – Stefanini 28 4.6 Caixas de Diálogo Simples JOptionPane public static void main( String args[] ) { SliderDemo application = new SliderDemo(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } • Utilização da classe } // end class SliderDemo – javax.swing.JOptionPane • Caixa de Diálogo para Informação ao Usuário – JOptionPane.showMessageDialog • Parâmetros: – (Component parentComponent, Object message, String title, int messageType ); – Dois últimos argumentos podem ser omitidos • Tipo de Mensagem (messageType) – – – – – Paulo André Castro POO ITA – Stefanini 29 JOptionPane.PLAIN_MESSAGE - nenhum ícone JOptionPane.ERROR_MESSAGE - ícone de erro JOptionPane.INFORMATION_MESSAGE - ícone de informação JOptionPane.WARNING_MESSAGE - ícone de aviso JOptionPane.QUESTION_MESSAGE - ícone de interrogação Paulo André Castro POO ITA – Stefanini 30 5 Caixas de Diálogo Simples - JOptionPane Caixas de Diálogo Úteis - JOptionPane • Caixa de Diálogo para Captar informação do Usuário – JOptionPane.showInputDialog – Parâmetros: (Component parentComponent, Object message, String title, int messageType ); – Dois últimos argumentos podem ser omitidos • Caixa de Diálogo para obter confirmação do Usuário JOPtionPane.showInputDialog – JOptionPane. showConfirmDialog – Parâmetros: (Component parentComponent, Object message, String title, int optionType, int messageType ); – optionType: JOptionPane.YES_NO_OPTION ou YES_NO_CANCEL_OPTION – Três últimos argumentos podem ser omitidos – Retorna um inteiro indicando o valor digitado pelo usuário: JOPtionPane.showMessageDialog JOPtionPane.showConfirmDialog • JOptionPane.YES_OPTION, JOptionPane.NO_OPTION, JOptionPane.CANCEL_OPTION Paulo André Castro POO ITA – Stefanini Paulo André Castro 31 Exemplo 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 POO ITA – Stefanini // set up GUI public MenuTest() { super( super ( "Using JMenus" ); Instantiate File JMenu POO – Allows for performing actions with cluttering GUI – Contained by menu bar • JMenuBar – Comprised of menu items • JMenuItem Paulo André Castro 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 public class MenuTest extends JFrame { private final Color colorValues[] = Color.BLACK, { Color.BLACK , Color.BLUE, Color.BLUE, Color.RED, Color.RED, Color.GREEN }; private JRadioButtonMenuItem colorItems[], fonts[]; private JCheckBoxMenuItem styleItems[]; private JLabel displayLabel; private ButtonGroup fontGroup, colorGroup; private int style; Paulo André Castro • Menus 33 // Fig. 4.9: MenuTest.java // Demonstrating menus import java.awt.*; import java.awt.event.*; import javax.swing.*; // set up File menu and its menu items JMenu fileMenu = new JMenu( "File" ); fileMenu.setMnemonic( 'F' ); 32 4.7 Usando Menus com Frames 1 import javax.swing.JOptionPane; 2 3 public class Dialogos { 4 5 public static void main(String args[]) { 6 int continua; 7 do { 8 String resposta; 9 resposta = JOptionPane.showInputDialog(null, JOptionPane.showInputDialog(null, "Qual o seu nome?", 10 "Nome...",JOptionPane.QUESTION_MESSAGE); 11 12 JOptionPane.showMessageDialog(null,"Olá, JOptionPane.showMessageDialog(null,"Olá, "+resposta); 13 continua=JOptionPane.showConfirmDialog continua=JOptionPane.showConfirmDialog(null, JOptionPane.showConfirmDialog(null, 14 "Deseja executar novamente?","Pergunta", 15 JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE); 16 17 18 } while(continua==JOptionPane.YES_OPTION); 19 } 20 21 } Paulo André Castro ITA – Stefanini POO ITA – Stefanini 35 ITA – Stefanini POO 34 // set up About... menu item JMenuItem aboutItem = new JMenuItem( "About..." ); aboutItem.setMnemonic( 'A' ); Instantiate About… JMenuItem fileMenu.add( aboutItem ); to be placed in fileMenu aboutItem.addActionListener( new ActionListener() { // anonymous inner class // display message dialog when user selects About... public void actionPerformed( ActionEvent event ) { JOptionPane.showMessageDialog( MenuTest.this MenuTest.this, this, example\ menus", "This is an example \nof using menus" , "About", "About" , JOptionPane.PLAIN_MESSAGE ); When } } user selects About… JMenuItem, display message dialog with appropriate text // end anonymous inner class ); // end call to addActionListener // set up Exit menu item JMenuItem exitItem = new JMenuItem( "Exit" ); exitItem.setMnemonic( 'x' ); fileMenu.add( exitItem ); exitItem.addActionListener( Paulo André Castro POO Instantiate Exit JMenuItem to be placed in fileMenu ITA – Stefanini 36 6 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 new ActionListener() { // anonymous inner class selects Exit JMenuItem, exit system } // end anonymous inner class ); // end call to addActionListener // create menu bar and attach it to MenuTest window JMenuBar bar = new JMenuBar(); Instantiate JMenuBar setJMenuBar( bar ); bar.add( fileMenu ); to contain JMenus // create Format menu, its submenus and menu items JMenu formatMenu = new JMenu( "Format" ); Instantiate Format formatMenu.setMnemonic( 'r' ); ITA – Stefanini POO fonts = new JRadioButtonMenuItem[ fontNames.length ]; fontGroup = new ButtonGroup(); // create Font radio button menu items for ( int count = 0; count < fonts.length; count++ ) { fonts[ count ] = new JRadioButtonMenuItem( fontNames[ count ] ); fontMenu.add( fonts[ count ] ); fontGroup.add( fonts[ count ] ); Instantiate fonts[ count ].addActionListener( itemHandler ); JRadioButtonMenuItems } for Font JMenu and ensure that only one menu item is selected at a time // select first Font menu item fonts[ 0 ].setSelected( true ); fontMenu.addSeparator(); // set up style menu items String styleNames[] = { "Bold", "Bold", "Italic" }; styleItems = new JCheckBoxMenuItem[ styleNames.length ]; StyleHandler styleHandler = new StyleHandler(); ITA – Stefanini POO Invoked when user selects JMenuItem // inner class to handle action events from menu items private class ItemHandler implements ActionListener { // process color and font selections public void actionPerformed( ActionEvent event ) Determine which font or color { menu generated event // process color selection for ( int count = 0; count < colorItems.length; count++ ) // process font selection for ( int count = 0; count < fonts.length; count++ ) Set font or color of JLabel, respectively if ( event.getSource() == fonts[ count ] ) { displayLabel.setFont( new Font( fonts[ count ].getText(), style, 72 ) ); break; break ; } Paulo André Castro POO ITA – Stefanini 41 colorItems = new JRadioButtonMenuItem[ colors.length ]; colorGroup = new ButtonGroup(); ItemHandler itemHandler = new ItemHandler(); // create color radio button menu items for ( int count = 0; count < colors.length; count++ ) { colorItems[ count ] = Instantiate new JRadioButtonMenuItem( colors[ count ] ); JRadioButtonMenuItems for colorMenu.add( colorItems[ count ] ); Color JMenu and ensure that only colorGroup.add( colorItems[ count ] ); one ); menu item is selected at a time colorItems[ count ].addActionListener( itemHandler } // select first Color menu item colorItems[ 0 ].setSelected( true ); // add format menu to menu bar formatMenu.add( colorMenu ); formatMenu.addSeparator(); Separator places line between JMenuItems // create Font submenu String fontNames[] = { "Serif", "Serif", "Monospaced", "Monospaced", "SansSerif" }; 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 ITA – Stefanini POO 38 // create style checkbox menu items for ( int count = 0; count < styleNames.length; count++ ) { styleItems[ count ] = new JCheckBoxMenuItem( styleNames[ count ] ); fontMenu.add( styleItems[ count ] ); styleItems[ count ].addItemListener( styleHandler ); } // put Font menu in Format menu formatMenu.add( fontMenu ); // add Format menu to menu bar bar.add( formatMenu ); // set up label to display text displayLabel = new JLabel( "Sample Text", Text", SwingConstants.CENTER ); displayLabel.setForeground( colorValues[ 0 ] ); "Serif", displayLabel.setFont( new Font( "Serif" , Font.PLAIN, Font.PLAIN, 72 ) ); getContentPane().setBackground( Color.CYAN ); getContentPane().add( displayLabel, BorderLayout.CENTER ); setSize( 500, 500, 200 ); setVisible( true ); } // end constructor Paulo André Castro 39 public static void main( String args[] ) { MenuTest application = new MenuTest(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } if ( colorItems[ count ].isSelected() ) { displayLabel.setForeground( colorValues[ count ] ); break; break ; } 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 Instantiate Color JMenu (submenu of Format JMenu) JMenu colorMenu = new JMenu( "Color" ); colorMenu.setMnemonic( 'C' ); Paulo André Castro 37 Instantiate Font JMenu (submenu of Format JMenu) JMenu fontMenu = new JMenu( "Font" ); fontMenu.setMnemonic( 'n' ); Paulo André Castro 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 JMenu // create Color submenu String colors[] = { "Black", "Black", "Blue", "Blue", "Red", "Red", "Green" }; Paulo André Castro 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 // terminate application when user clicks exitItem public void actionPerformed( ActionEvent event ) { System.exit( 0 ); When user } ITA – Stefanini POO 40 repaint(); } // end method actionPerformed } // end class ItemHandler Invoked when user selects menu items // inner class to handle item events from check boxJCheckBoxMenuItem private class StyleHandler implements ItemListener { // process font style selections public void itemStateChanged( ItemEvent e ) { style = 0; // check for bold selection if ( styleItems[ 0 ].isSelected() ) Font.BOLD BOLD; style += Font. BOLD ; Determine new font style // check for italic selection if ( styleItems[ 1 ].isSelected() ) style += Font.ITALIC Font.ITALIC; ITALIC; displayLabel.setFont( new Font( displayLabel.getFont().getName(), style, 72 ) ); Paulo André Castro POO ITA – Stefanini 42 7 206 207 repaint(); 208 } 209 210 } // end class StyleHandler 211 212 } // end class MenuTest Paulo André Castro Exercício • ITA – Stefanini POO • Context-sensitive popup menus – JPopupMenu – Menu generated depending on which component is accessed Paulo André Castro 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 POO ITA – Stefanini getContentPane().setBackground( Color.WHITE ); // declare a MouseListener for the window that displays // a JPopupMenu when the popup trigger event occurs addMouseListener( // anonymous inner class // handle mouse press event public void mousePressed( MouseEvent event ) { checkForTriggerEvent( event ); } // handle mouse release event public void mouseReleased( MouseEvent event ) { checkForTriggerEvent( event ); } Paulo André Castro POO Determine whether popuptrigger event occurred when user presses or releases mouse button ITA – Stefanini 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 47 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 ITA – Stefanini POO 44 // Fig. 4.10: PopupTest.java // Demonstrating JPopupMenus import java.awt.*; import java.awt.event.*; import javax.swing.*; public class PopupTest extends JFrame { private JRadioButtonMenuItem items[]; private final Color colorValues[] = Color.BLUE, Color.YELLOW, { Color.BLUE , Color.YELLOW , Color.RED }; private JPopupMenu popupMenu; // set up GUI public PopupTest() { super( super( "Using JPopupMenus" ); ItemHandler handler = new ItemHandler(); String colors[] = { "Blue", "Blue", "Yellow", "Yellow", "Red" }; // set up popup menu and its items ButtonGroup colorGroup = new ButtonGroup(); popupMenu = new JPopupMenu(); items = new JRadioButtonMenuItem[ 3 ]; Paulo André Castro 45 // construct each menu item and add to popup menu; also // enable event handling for each menu item for ( int count = 0; count < items.length; count++ ) { items[ count ] = new JRadioButtonMenuItem( colors[ count ] ); popupMenu.add( items[ count ] ); colorGroup.add( items[ count ] ); Create JRadioButtonMenuItem items[ count ].addActionListener( handler ); objects to add to JPopupMenu } new MouseAdapter() { Paulo André Castro 43 4.8 JPopupMenu Introduza um novo item no Menu File. O item deve ser “Text”, a tecla mnemônica deve ser ‘T’. Ao ser acionado, o item abre uma caixa de diálogo que pede ao usuário um novo texto, o qual será utilizado para modificar o texto apresentado ao centro da janela. Mantendo a cor, estilo e fonte do texto. Instantiate JPopupMenu object ITA – Stefanini POO 46 // determine whether event should trigger popup menu private void checkForTriggerEvent( MouseEvent event ) { if ( event.isPopupTrigger() ) popupMenu.show( event.getComponent(), event.getX(), event.getY() ); } Show JPopupMenu if popup-trigger occurred } // end anonymous inner clas ); // end call to addMouseListener setSize( 300, 300, 200 ); setVisible( true ); } // end constructor PopupTest public static void main( String args[] ) { PopupTest application = new PopupTest(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } Paulo André Castro POO ITA – Stefanini 48 8 // private inner class to handle menu item events private class ItemHandler implements ActionListener { 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 } // end private inner class ItemHandler } // end class PopupTest Paulo André Castro POO ITA – Stefanini 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 – Windows – Motif – Java UIManager.LookAndFeelInfo looks • • • // recupera os LookAndFeel instalados looks=UIManager.getInstalledLookAndFeels(); //muda o LookAndFeel • UIManager.setLookAndFeel(look[i]); Paulo André Castro POO ITA – Stefanini 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 // set up button for NORTH panel button = new JButton( "JButton" ); northPanel.add( button ); // set up combo box for NORTH panel comboBox = new JComboBox( strings ); northPanel.add( comboBox ); // create array for radio buttons radio = new JRadioButton[ strings.length ]; // set up panel for SOUTH of BorderLayout JPanel southPanel = new JPanel(); southPanel.setLayout( new GridLayout( 1, radio.length ) ); // set up radio buttons for SOUTH panel group = new ButtonGroup(); ItemHandler handler = new ItemHandler(); POO ITA – Stefanini 53 POO ITA – Stefanini 50 // Fig. 4.11: LookAndFeelDemo.java // Changing the look and feel. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class LookAndFeelDemo extends JFrame { private final String strings[] = { "Metal", "Metal", "Motif", "Motif", "Windows" }; private UIManager.LookAndFeelInfo looks[]; private JRadioButton radio[]; private ButtonGroup group; Hold installed look-and-feel private JButton button; private JLabel label; private JComboBox comboBox; information // set up GUI public LookAndFeelDemo() { super( super ( "Look and Feel Demo" ); Container container = getContentPane(); // set up panel for NORTH of BorderLayout JPanel northPanel = new JPanel(); northPanel.setLayout( new GridLayout( 3, 1, 0, 5 ) ); Paulo André Castro 51 // set up label for NORTH panel label = new JLabel( "This is a Metal looklook-andand-feel", feel", SwingConstants.CENTER ); northPanel.add( label ); Paulo André Castro Paulo André Castro 49 • É possível mudar a aparência de sua aplicação Swing em tempo de execução • • Altere o código do exemplo anterior para incluir as opções Green, Black e White, no pop-up Menu e que ao serem selecionadas alterem a cor de fundo da janela para a cor correspondente Determine which JRadioButtonMenuItem was selected, then set window background color 4.9 Pluggable Look-and-Feel 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 Exercício Invoked when user selects // process menu item selections JRadioButtonMenuItem public void actionPerformed( ActionEvent event ) { // determine which menu item was selected for ( int i = 0; i < items.length; i++ ) if ( event.getSource() == items[ i ] ) { getContentPane().setBackground( colorValues[ i ] ); return; return ; } } POO ITA – Stefanini 52 ITA – Stefanini 54 for ( int count = 0; count < radio.length; count++ ) { radio[ count ] = new JRadioButton( strings[ count ] ); radio[ count ].addItemListener( handler ); group.add( radio[ count ] ); southPanel.add( radio[ count ] ); } // attach NORTH and SOUTH panels to content pane container.add( northPanel, BorderLayout.NORTH ); container.add( southPanel, BorderLayout.SOUTH ); // get installed looklook-andand-feel information looks = UIManager.getInstalledLookAndFeels(); setSize( 300, 300, 200 ); setVisible( true ); radio[ 0 ].setSelected( true ); } // end constructor LookAndFeelDemo // use UIManager to change looklook-andand-feel of GUI private void changeTheLookAndFeel( int value ) { Paulo André Castro POO 9 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 // change look and feel try { UIManager.setLookAndFeel( looks[ value ].getClassName() ); SwingUtilities.updateComponentTreeUI( this ); } // process problems changing look and feel catch ( Exception exception ) { exception.printStackTrace(); } Change look-and-feel } 101 if ( radio[ count ].isSelected() ) { 102 label.setText( "This is a " + 103 strings[ count ] + " looklook-andand-feel" ); 104 comboBox.setSelectedIndex( count ); 105 changeTheLookAndFeel( count ); 106 } 107 } 108 109 } // end private inner class ItemHandler 110 111 } // end class LookAndFeelDemo public static void main( String args[] ) { LookAndFeelDemo application = new LookAndFeelDemo(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } // private inner class to handle radio button events private class ItemHandler implements ItemListener { // process user's looklook-andand-feel selection public void itemStateChanged( ItemEvent event ) { for ( int count = 0; count < radio.length; count++ ) Paulo André Castro POO ITA – Stefanini Paulo André Castro 55 ITA – Stefanini POO 56 4.10 JDesktopPane and JInternalFrame Internal Frames Minimize Maximize Close • Multiple document interface – Main (parent) window – Child windows – Switch freely among documents Minimized internal frames Paulo André Castro POO ITA – Stefanini Paulo André Castro 57 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 Paulo André Castro POO ITA – Stefanini 59 Position the mouse over any corner of a child window to resize the window (if resizing is allowed). POO ITA – Stefanini 58 // Fig. 4.12: DesktopTest.java // Demonstrating JDesktopPane. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class DesktopTest extends JFrame { private JDesktopPane theDesktop; Manages JInternalFrame child windows displayed in JDesktopPane // set up GUI public DesktopTest() { super( super ( "Using a JDesktopPane" ); // create menu bar, menu and menu item JMenuBar bar = new JMenuBar(); JMenu addMenu = new JMenu( "Add" ); JMenuItem newFrame = new JMenuItem( "Internal Frame" ); addMenu.add( newFrame ); bar.add( addMenu ); setJMenuBar( bar ); // set up desktop theDesktop = new JDesktopPane(); getContentPane().add( theDesktop ); Paulo André Castro POO ITA – Stefanini 60 10 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 // set up listener for newFrame menu item newFrame.addActionListener( new ActionListener() { Handle event when user selects JMenuItem // anonymous inner class // display new internal window public void actionPerformed( ActionEvent event ) { Invoked when user selects JMenuItem // create internal frame JInternalFrame frame = new JInternalFrame( Frame", "Internal Frame" , true, true, true, true, true, true, true ); // attach panel to internal frame content pane Container container = frame.getContentPane(); MyJPanel panel = new MyJPanel(); container.add( panel, BorderLayout.CENTER ); Create JInternalFrame JPanels can be added to JInternalFrames // set size internal frame to size of its contents frame.pack(); Use preferred size for window // attach internal frame to desktop and show it theDesktop.add( frame ); frame.setVisible( true ); } 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 setSize( 600, 600, 460 ); setVisible( true ); } // end constructor public static void main( String args[] ) { DesktopTest application = new DesktopTest(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } // end class DesktopTest // class to display an ImageIcon on a panel class MyJPanel extends JPanel { private ImageIcon imageIcon; "yellowflowers.png", private String[] images = { "yellowflowers.png" , "purpleflowers.png", "purpleflowers.png", "redflowers.png", "redflowers2.png", "redflowers.png" , "redflowers2.png" , "lavenderflowers.png" }; // load image public MyJPanel() { } // end anonymous inner class Paulo André Castro POO ITA – Stefanini Paulo André Castro 61 80 int randomNumber = ( int ) ( Math.random() * 5 ); 81 imageIcon = new ImageIcon( images[ randomNumber ] ); 82 } 83 84 // display imageIcon on panel 85 public void paintComponent( Graphics g ) 86 { 87 // call superclass paintComponent method 88 super.paintComponent( super.paintComponent( g ); 89 90 // display icon 91 imageIcon.paintIcon( this, this, g, 0, 0 ); 92 } 93 // return image dimensions 94 95 public Dimension getPreferredSize() 96 { 97 return new Dimension( imageIcon.getIconWidth(), 98 imageIcon.getIconHeight() ); 99 } 100 101 } // end class MyJPanel Paulo André Castro 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 ); // end call to addActionListener POO ITA – Stefanini Create a JTabbedPane the first panel // set up panel2 and add it to JTabbedPane JLabel label2 = new JLabel( "panel two", two", SwingConstants.CENTER ); JPanel panel2 = new JPanel(); Add the panel2.setBackground( Color.YELLOW ); panel2.add( label2 ); Two", null, tabbedPane.addTab( "Tab Two" , null , panel2, "Second Panel" ); second panel ITA – Stefanini Paulo André Castro 63 { POO ITA – Stefanini 64 – One layer visible at a time – Access each layer via a tab – JTabbedPane // set up pane11 and add it to JTabbedPane JLabel label1 = new JLabel( "panel one", one", SwingConstants.CENTER ); Add JPanel panel1 = new JPanel(); panel1.add( label1 ); tabbedPane.addTab( "Tab One", One", null, null, panel1, "First Panel" ); Paulo André Castro 62 • Arranges GUI components into layers // set up GUI public JTabbedPaneDemo() { super( super ( "JTabbedPane Demo " ); // create JTabbedPane JTabbedPane tabbedPane = new JTabbedPane(); ITA – Stefanini 4.11 JTabbedPane // Fig. 4.13: JTabbedPaneDemo.java // Demonstrating JTabbedPane. import java.awt.*; import javax.swing.*; public class JTabbedPaneDemo extends JFrame POO 65 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 POO // set up panel3 and add it to JTabbedPane JLabel label3 = new JLabel( "panel three" ); JPanel panel3 = new JPanel(); panel3.setLayout( new BorderLayout() ); panel3.add( new JButton( "North" ), BorderLayout.NORTH ); panel3.add( new JButton( "West" ), BorderLayout.WEST ); panel3.add( new JButton( "East" ), BorderLayout.EAST ); panel3.add( new JButton( "South" ), BorderLayout.SOUTH ); panel3.add( label3, BorderLayout.CENTER ); Three", null, tabbedPane.addTab( "Tab Three" , null , panel3, "Third Panel" ); // add JTabbedPane to container getContentPane().add( tabbedPane ); Add the third panel setSize( 250, 250, 200 ); setVisible( true ); } // end constructor public static void main( String args[] ) { JTabbedPaneDemo tabbedPaneDemo = new JTabbedPaneDemo(); tabbedPaneDemo.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } // end class CardDeck Paulo André Castro POO ITA – Stefanini 66 11 4.12 Layout Managers: BoxLayout e GridBagLayout BoxLayout Layout Manager • Dois Novos Layout Managers • BoxLayout – BoxLayout: – Arranges GUI components • Permite que os componentes GUI sejam arranjados da esquerda para direita ou de cima para baixo em um container. A classe Box declara um container com BoxLayout como Layout padrão e provê métodos estáticos para criar Box com BoxLayout vertical ou horizontal • Horizontally along x-axis • Vertically along y-axis – GridBagLayout: • Similar a GridLayout, porém cada componente pode variar de tamnho e os componentes podem ser adicionados em qualquer ordem. Paulo André Castro ITA – Stefanini POO Paulo André Castro 67 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Paulo André Castro 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 ITA – Stefanini POO // create strut and add buttons to Box vertical1 Add for ( int count = 0; count < SIZE; SIZE; count++ ) { vertical1.add( Box.createVerticalStrut( 25 ) ); vertical1.add( new JButton( "Button " + count ) ); } three JButtons to vertical Box Strut guarantees space between components // create horizontal glue and add buttons to Box horizontal2 Add three JButtons to for ( int count = 0; count < SIZE; SIZE; count++ ) { horizontal Box horizontal2.add( Box.createHorizontalGlue() ); horizontal2.add( new JButton( "Button " + count ) ); Glue guarantees expandable } space between components // create rigid area and add buttons to Box vertical2 for ( int count = 0; count < SIZE; SIZE; count++ ) { Add three to vertical 12, 8 ) ) ); vertical2.add( Box.createRigidArea( new Dimension( 12, JButtons vertical2.add( new JButton( "Button " + count ) ); } Rigid area guarantees Box fixed component size // create vertical glue and add buttons to panel JPanel panel = new JPanel(); panel.setLayout( new BoxLayout( panel, BoxLayout.Y_AXIS BoxLayout.Y_AXIS ) ); for ( int count = 0; count < SIZE; SIZE; count++ ) { panel.add( Box.createGlue() ); panel.add( new JButton( "Button " + count ) ); } Paulo André Castro POO ITA – Stefanini 71 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 68 // Fig. 4.15: BoxLayoutDemo.java // Demonstrating BoxLayout. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class BoxLayoutDemo extends JFrame { // set up GUI public BoxLayoutDemo() { super( super ( "Demostrating BoxLayout" ); // create Box containers with BoxLayout Box horizontal1 = Box.createHorizontalBox(); Box vertical1 = Box.createVerticalBox(); Box horizontal2 = Box.createHorizontalBox(); Box vertical2 = Box.createVerticalBox(); Create Boxes final int SIZE = 3; // number of buttons on each Box Add three JButtons to horizontal Box // add buttons to Box horizontal1 for ( int count = 0; count < SIZE; SIZE; count++ ) horizontal1.add( new JButton( "Button " + count ) ); Paulo André Castro 69 ITA – Stefanini POO ITA – Stefanini POO // create a JTabbedPane JTabbedPane tabs = new JTabbedPane( JTabbedPane.TOP TOP, JTabbedPane. TOP , JTabbedPane.SCROLL_TAB_LAYOUT JTabbedPane.SCROLL_TAB_LAYOUT ); 70 Create a JTabbedPane to hold the Boxes // place each container on tabbed pane tabs.addTab( "Horizontal Box", Box", horizontal1 ); tabs.addTab( "Vertical Box with Struts", Struts", vertical1 ); tabs.addTab( "Horizontal Box with Glue", Glue", horizontal2 ); Areas", tabs.addTab( "Vertical Box with Rigid Areas" , vertical2 ); Glue", tabs.addTab( "Vertical Box with Glue" , panel ); getContentPane().add( tabs ); // place tabbed pane on content pane setSize( 400, 400, 220 ); setVisible( true ); } // end constructor public static void main( String args[] ) { BoxLayoutDemo application = new BoxLayoutDemo(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } // end class BoxLayoutDemo Paulo André Castro POO ITA – Stefanini 72 12 Fig. 4.16 GridBagLayout Layout Manager Designing a GUI that will use GridBagLayout • GridBagLayout – Flexible GridBagLayout • Components can vary in size • Components can occupy multiple rows and columns • Components can be added in any order Column 0 – Uses GridBagConstraints Fig. 4.17 GridBagConstraints field fill 1 ITA – Stefanini POO 2 Paulo André Castro 73 POO ITA – Stefanini 74 POO ITA – Stefanini 76 Description gridx Resize the component in specified direction (NONE, HORIZONTAL, VERTICAL, BOTH) when the display area is larger than the component. The column in which the component will be placed. gridy The row in which the component will be placed. gridwidth The number of columns the component occupies. gridheight The number of rows the component occupies. weightx The portion of extra space to allocate horizontally. The grid slot can become wider when extra space is available. weighty The portion of extra space to allocate vertically. The grid slot can become taller when extra space is available. GridBagLayout with the weights set to zero ITA – Stefanini POO public class GridBagDemo extends JFrame { private Container container; private GridBagLayout layout; private GridBagConstraints constraints; // set up GUI public GridBagDemo() { super( super ( "GridBagLayout" ); container = getContentPane(); layout = new GridBagLayout(); container.setLayout( layout ); Set GridBagLayout as layout manager // instantiate gridbag constraints constraints = new GridBagConstraints(); // create GUI components JTextArea textArea1 = new JTextArea( "TextArea1", "TextArea1", 5, 10 ); "TextArea2", , 2, 2 ); JTextArea textArea2 = new JTextArea( "TextArea2" POO Used to determine component location and size in grid ITA – Stefanini Paulo André Castro 75 // Fig. 4.19: GridBagDemo.java // Demonstrating GridBagLayout. import java.awt.*; import java.awt.event.*; import javax.swing.*; Paulo André Castro 3 GridBagConstraints fields Paulo André Castro 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 2 Row • Specifies how component is placed in GridBagLayout Paulo André Castro 1 0 77 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 String names[] = { "Iron" "Iron", , "Steel", "Steel", "Brass" }; JComboBox comboBox = new JComboBox( names ); JTextField textField = new JTextField( JButton button1 = new JButton( "Button JButton button2 = new JButton( "Button JButton button3 = new JButton( "Button "TextField" ); 1" ); 2" ); 3" ); If user resizes Container, first JTextArea is filled entire allocated area in grid First JTextArea spans // weightx and weighty for textArea1 are both 0: the default one row and three columns // anchor for all components is CENTER: the default constraints.fill = GridBagConstraints.BOTH; GridBagConstraints.BOTH; If user resizes Container, first addComponent( textArea1, 0, 0, 1, 3 ); JButton fills horizontally in grid // weightx and weighty for button1 are both 0: the default constraints.fill = GridBagConstraints.HORIZONTAL; GridBagConstraints.HORIZONTAL; First addComponent( button1, 0, 1, 2, 1 ); JButton spans two rows and one column // weightx and weighty for comboBox are both 0: the default // fill is HORIZONTAL addComponent( comboBox, 2, 1, 2, 1 ); // button2 constraints.weightx = 1000; 1000; // can grow wider // can grow taller constraints.weighty = 1; GridBagConstraints.BOTH; constraints.fill = GridBagConstraints.BOTH ; addComponent( button2, 1, 1, 1, 1 ); Paulo André Castro POO If user resizes Container, second JButton fills extra space ITA – Stefanini 78 13 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 // fill is BOTH for button3 constraints.weightx = 0; constraints.weighty = 0; addComponent( button3, 1, 2, 1, 1 ); 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 // weightx and weighty for textField are both 0, fill is BOTH addComponent( textField, 3, 0, 2, 1 ); // weightx and weighty for textArea2 are both 0, fill is BOTH addComponent( textArea2, 3, 2, 1, 1 ); setSize( 300, 300, 150 ); setVisible( true ); } // end constructor GridBagDemo // set constraints and add component layout.setConstraints( component, constraints ); container.add( component ); } public static void main( String args[] ) { GridBagDemo application = new GridBagDemo(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } // end class GridBagDemo // method to set constraints on private void addComponent( Component component, int row, int column, int width, int height ) { // set gridx and gridy constraints.gridx = column; constraints.gridy = row; Paulo André Castro ITA – Stefanini POO • Constants RELATIVE and REMAINDER – Usados em substituição a gridx e gridy – RELATIVE • Especifica proximidade necessária ao último componente adicionado constraints.gridwidth = GridBagConstraints.RELATIVE; • layout.setConstraints( component, constraints ); • Container.add(component); – REMAINDER • Especifica que o componente deve ser o último da linha ou coluna • constraints.gridwidth = GridBagConstraints.REMAINDER; Paulo André Castro ITA – Stefanini POO String fonts[] = { "Serif", "Serif", "Monospaced" }; JList list = new JList( fonts ); String names[] = { "zero", "zero", "one", "one", "two", "two", "three", "three", "four" }; JButton buttons[] = new JButton[ names.length ]; for ( int count = 0; count < buttons.length; count++ ) buttons[ count ] = new JButton( names[ count ] ); // buttons[0] -- weightx and weighty are 1: fill is BOTH constraints.gridwidth = 1; addComponent( buttons[ 0 ] ); // buttons[1] -- weightx and weighty are 1: fill is BOTH constraints.gridwidth = GridBagConstraints.RELATIVE; GridBagConstraints.RELATIVE; addComponent( buttons[ 1 ] ); Paulo André Castro POO last row Place button[0] as first component in second row Place button[1] right next to button[0] ITA – Stefanini 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 83 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 ITA – Stefanini POO 80 // Fig. 4.20: GridBagDemo2.java // Demonstrating GridBagLayout constants. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class GridBagDemo2 extends JFrame { private GridBagLayout layout; private GridBagConstraints constraints; private Container container; // set up GUI public GridBagDemo2() { super( super ( "GridBagLayout" ); container = getContentPane(); layout = new GridBagLayout(); container.setLayout( layout ); Set GridBagLayout as layout manager // instantiate gridbag constraints constraints = new GridBagConstraints(); Used to determine component location and size in grid // create GUI components String metals[] = { "Copper", "Copper", "Aluminum", "Aluminum", "Silver" }; JComboBox comboBox = new JComboBox( metals ); Paulo André Castro 81 JTextField textField = new JTextField( "TextField" ); // define GUI component constraints for textField Specify textField as constraints.weightx = 1; (only) component in first constraints.weighty = 1; GridBagConstraints.BOTH; constraints.fill = GridBagConstraints.BOTH ; GridBagConstraints.REMAINDER; constraints.gridwidth = GridBagConstraints.REMAINDER ; addComponent( textField ); Paulo André Castro 79 GridBagConstraints Constants RELATIVE and REMAINDER 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 // set gridwidth and gridheight constraints.gridwidth = width; constraints.gridheight = height; ITA – Stefanini POO // buttons[2] -- weightx and weighty are 1: fill is BOTH constraints.gridwidth = GridBagConstraints.REMAINDER; GridBagConstraints.REMAINDER; addComponent( buttons[ 2 ] ); // comboBox -- weightx is 1: fill is BOTH constraints.weighty = 0; GridBagConstraints.REMAINDER; constraints.gridwidth = GridBagConstraints.REMAINDER ; addComponent( comboBox ); // buttons[3] -- weightx is 1: fill is BOTH constraints.weighty = 1; GridBagConstraints.REMAINDER; constraints.gridwidth = GridBagConstraints.REMAINDER ; addComponent( buttons[ 3 ] ); 82 Place button[2] right next to button[1] Specify comboBox as last (only) component in third row Specify buttons[3] as last (only) component in fourth row // buttons[4] -- weightx and weighty are 1: fill is BOTH constraints.gridwidth = GridBagConstraints.RELATIVE; GridBagConstraints.RELATIVE; Place addComponent( buttons[ 4 ] ); button[4] as first component in fifth row // list -- weightx and weighty are 1: fill is BOTH constraints.gridwidth = GridBagConstraints.REMAINDER; GridBagConstraints.REMAINDER; addComponent( list ); Specify list as last component in fifth row setSize( 300, 300, 200 ); setVisible( true ); } // end constructor Paulo André Castro POO ITA – Stefanini 84 14 81 82 83 84 85 86 87 88 89 90 91 92 93 94 // add a Component to the container private void addComponent( Component component ) { layout.setConstraints( component, constraints ); container.add( component ); // add component } public static void main( String args[] ) { GridBagDemo2 application = new GridBagDemo2(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } // end class GridBagDemo2 Paulo André Castro POO ITA – Stefanini 85 15