SWING 3 painting (lập TRÌNH NÂNG CAO SLIDE)

55 8 0
SWING 3   painting (lập TRÌNH NÂNG CAO SLIDE)

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

PHẦN - SWING PAINTING MOUSE AND KEYBOARD EVENTS How Painting Happens  When a Swing GUI needs to paint itself — whether for the first time, in response to becoming unhidden, or because it needs to reflect a change in the program's state — it starts with the highest component that needs to be repainted and works its way down the containment hierarchy This process is orchestrated by the AWT painting system, and made more efficient and smooth by the Swing repaint manager  Swing components generally repaint themselves whenever necessary When you invoke the setText method on a component, for example, the component automatically repaints itself and, if appropriate, resizes itself Behind the scenes, when a visible property changes the repaint method is invoked on the component to request that it be scheduled for painting If the component's size or position also needs to change, a call to revalidate precedes the one to repaint The repaint and revalidate methods are thread safe — they can be invoked from any thread Khoa CNTT – ĐH Nông Lâm TP HCM 2014 2/55 The Swing Painting Methods  paintComponent — The main method for painting By default, it first paints the background if the component is opaque Then it performs any custom painting  paintBorder — Tells the component's border (if any) to paint Do not invoke or override this method  paintChildren — Tells any components contained by this component to paint themselves Do not invoke or override this method Khoa CNTT – ĐH Nông Lâm TP HCM 2014 3/55 Custom Painting  Before you implement a component that performs custom painting, first make sure that you really need to so You might be able to use the text and image capabilities of labels , buttons , or text components instead And remember, you can use borders to customize the outside edges of a component  If you really need to perform custom painting, then you need to decide which superclass to use We recommend that you extend either JPanel or a more specialized Swing component class  When implementing custom painting code, keep two things in mind:  Your custom painting code belongs in a method named paintComponent  You can and probably should use a border to paint the outside edges of your component Khoa CNTT – ĐH Nông Lâm TP HCM 2014 4/55 An Example of Custom Painting class ImagePanel extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); //paint background //Draw image at its natural size first g.drawImage(image, 0, 0, this); //85x62 image //Now draw the image scaled g.drawImage(image, 90, 0, 300, 62, this); } } Khoa CNTT – ĐH Nông Lâm TP HCM 2014 5/55 The rules for the custom painting:  The painting code does something that no standard Swing component does If we just wanted to display the figure once, at its natural size, we would have used a JLabel object instead of the custom component  The custom component is a JPanel subclass This is a common superclass for custom components  All the custom painting code is in a method called paintComponent  Before performing any custom painting, the component paints its background by invoking super.paintComponent Khoa CNTT – ĐH Nông Lâm TP HCM 2014 6/55 The Coordinate System Khoa CNTT – ĐH Nông Lâm TP HCM 2014 7/55 The Coordinate System  When painting a component, you must take into account not only the component's size but also the size of the component's border, if any For example, a border that paints a one-pixel line around a component changes the top leftmost corner from (0,0) to (1,1) and reduces the width and the height of the painting area by two pixels each (one pixel per side) Khoa CNTT – ĐH Nông Lâm TP HCM 2014 8/55 The Coordinate System  You get the width and height of a component using its getWidth and getHeight methods To determine the border size, use the getInsets method Here is some code that a component might use to determine the width and height available for custom painting: public void paintComponent(Graphics g) { Insets insets = getInsets(); int currentWidth = getWidth() - insets.left - insets.right; int currentHeight = getHeight()-insets.top-insets.bottom; ./* First painting occurs at (x,y), where x is at least insets.left, and y is at least insets.height */ } Khoa CNTT – ĐH Nông Lâm TP HCM 2014 9/55 Arguments to the repaint Method  Remember that calling a component's repaint method requests that the component be scheduled to paint itself When the painting system is unable to keep up with the pace of repaint requests, it might combine multiple requests into a single paint request to the component The repaint method has two useful forms:  void repaint()  Requests that the entire component be repainted  void repaint(int, int, int, int)  Requests that only the specified part of the component be repainted The arguments specify first the X and Y coordinates at the upper left of the area to be repainted, and then the area's width and height Khoa CNTT – ĐH Nông Lâm TP HCM 2014 10/55 Keyboard Events  When the user pushes a key, a key_Pressed KeyEvent is generated When the user releases the key, a key_Release KeyEvent is triggered You trap these events in the keyPressed and keyReleased methods of any class that implements the KeyListener interface Use these methods to trap raw keystrokes A third method, keyTyped, combines the two: it reports on the characters that were generated by the user's keystrokes  Java makes a distinction between characters and virtual key codes Virtual key codes are indicated with a prefix of VK_, such as VK_A or VK_SHIFT Virtual key codes correspond to keys on the keyboard For example, VK_A denotes the key marked A There is no separate lowercase virtual key code—the keyboard does not have separate lowercase keys Khoa CNTT – ĐH Nông Lâm TP HCM 2014 41/55 Keyboard Events  suppose that the user types an uppercase "A" in the usual way, by pressing the SHIFT key along with the A key Java reports five events in response to this user action Pressed the SHIFT key (keyPressed called for VK_SHIFT) Pressed the A key (keyPressed called for VK_A) Typed "A" (keyTyped called for an "A") Released the A key (keyReleased called for VK_A) Released the SHIFT key (keyReleased called for VK_SHIFT) Khoa CNTT – ĐH Nông Lâm TP HCM 2014 42/55 Keyboard Events   if the user typed a lowercase "a" by simply pressing the A key, then there are only three events: Pressed the A key (keyPressed called for VK_A) Typed "a" (keyTyped called for an "a") Released the A key (keyReleased called for VK_A) Thus, the keyTyped procedure reports the character that was typed ("A" or "a"), whereas the keyPressed and keyReleased methods report on the actual keys that the user pressed Khoa CNTT – ĐH Nông Lâm TP HCM 2014 43/55 Keyboard Events  To work with the keyPressed and keyReleased methods, you want to first check the key code  public void keyPressed(KeyEvent event) { int keyCode = event.getKeyCode(); }  The key code will equal one of the following (reasonably mnemonic) constants They are defined in the KeyEvent class  VK_A VK_Z , VK_0 VK_9, VK_SPACE, VK_ENTER, VK_BACK_SPACE, VK_TAB, VK_ESCAPE VK_SHIFT, VK_CONTROL, VK_ALT, VK_F1 VK_F24, VK_NUMPAD0 VK_NUMPAD9, VK_KP_DOWN, VK_KP_LEFT, VK_KP_RIGHT, VK_KP_UP Khoa CNTT – ĐH Nông Lâm TP HCM 2014 44/55 Keyboard Events  To find the current state of the SHIFT, CONTROL, ALT, you can, of course, track the VK_SHIFT, VK_CONTROL, VK_ALT key presses or simply use the isShiftDown, isControlDown, isAltDown methods  For example, the following code tests whether the user presses SHIFT + RIGHT ARROW:  public void keyPressed(KeyEvent event) { int keyCode = event.getKeyCode(); if (keyCode == KeyEvent.VK_RIGHT && event.isShiftDown()) { } }  In the keyTyped method, you call the getKeyChar method to obtain the actual character that was typed Khoa CNTT – ĐH Nông Lâm TP HCM 2014 45/55 Keyboard Events  Not all keystrokes result in a call to keyTyped Only those keystrokes that generate a Unicode character can be captured in the keyTyped method You need to use the keyPressed method to check for cursor keys and other command keys Khoa CNTT – ĐH Nông Lâm TP HCM 2014 46/55 java.awt.event.KeyEvent  char getKeyChar() returns the character that the user typed  int getKeyCode() returns the virtual key code of this key event  boolean isActionKey() returns true if the key in this event is an "action" key The following keys are action keys: HOME, END, PAGE UP, PAGE DOWN, UP, DOWN, LEFT, RIGHT, F1 F24, PRINT SCREEN, SCROLL LOCK, CAPS LOCK, NUM LOCK, PAUSE, INSERT, DELETE, ENTER, BACKSPACE, DELETE, and TAB  static String getKeyText(int keyCode) returns a string describing the key code For example, getKeyText(KeyEvent.VK_END) is the string "End"  static String getKeyModifiersText(int modifiers) returns a string describing the modifier keys, such as SHIFT or CTRL + SHIFT Parameters:modifiers The modifier state, as reported by getModifiers Khoa CNTT – ĐH Nông Lâm TP HCM 2014 47/55 java.awt.event.InputEvent  int getModifiers() returns an integer whose bits describe the state of the modifiers SHIFT, CONTROL, ALT, and META This method applies to both keyboard and mouse events To see if a bit is set, test the return value against one of the bit masks SHIFT_MASK, CTRL_MASK, ALT_MASK, ALT_GRAPH_MASK, META_MASK, or use one of the following methods  boolean isShiftDown()  boolean isControlDown()  boolean isAltDown() Khoa CNTT – ĐH Nông Lâm TP HCM 2014 48/55 A sketch program  You move a pen up, down, left, and right with the cursor keys If you hold down the SHIFT key, the pen moves by a larger increment Or, if you are experienced using the vi editor, you can bypass the cursor keys and use the lowercase h, j, k, and l keys to move the pen The uppercase H, J, K, and L move the pen by a larger increment We trap the cursor keys in the keyPressed method and the characters in the keyTyped method Khoa CNTT – ĐH Nông Lâm TP HCM 2014 49/55 A sketch program public class SketchFrame extends JFrame{ public SketchFrame() { setTitle("Sketch"); setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); // add panel to frame SketchPanel panel = new SketchPanel(); Container contentPane = getContentPane(); contentPane.add(panel); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public static final int DEFAULT_WIDTH = 300; public static final int DEFAULT_HEIGHT = 200; } Khoa CNTT – ĐH Nông Lâm TP HCM 2014 50/55 A sketch program class SketchPanel extends JPanel{ private Point last; private ArrayList lines; private static final int SMALL_INCREMENT = 2; private static final int LARGE_INCREMENT = 10; public SketchPanel() { //The polyLine begins from Point(10,10) last = new Point(10, 10); lines = new ArrayList(); lines.add(last); KeyHandler listener = new KeyHandler(); addKeyListener(listener); setBackground(Color.white); setFocusable(true); } Khoa CNTT – ĐH Nông Lâm TP HCM 2014 51/55 A sketch program //Add a new line segment to the sketch by relative position public void add(int dx, int dy){ // compute new end point Point end = new Point(last.x + dx,last.y + dy); lines.add(end); // add line segment last = end; // remember new end point repaint(); } public void paintComponent(Graphics g){ super.paintComponent(g); g.setColor(Color.red); // draw all lines Point firstPoint = lines.get(0); Point secondPoint; for (int i = 1; i < lines.size(); i++){ secondPoint = (Point) lines.get(i); g.drawLine(firstPoint.x, firstPoint.y, secondPoint.x, secondPoint.y); firstPoint = secondPoint; } } Khoa CNTT – ĐH Nông Lâm TP HCM 2014 52/55 A sketch program private class KeyHandler implements KeyListener { public void keyPressed(KeyEvent event){ int keyCode = event.getKeyCode(); // set distance int d; if (event.isShiftDown()) d = LARGE_INCREMENT; else d = SMALL_INCREMENT; // add line segment if (keyCode == KeyEvent.VK_LEFT) add(-d, 0); else if (keyCode == KeyEvent.VK_RIGHT) add(d, 0); else if (keyCode == KeyEvent.VK_UP) add(0, -d); else if (keyCode == KeyEvent.VK_DOWN) add(0, d); } public void keyReleased(KeyEvent event) {} Khoa CNTT – ĐH Nông Lâm TP HCM 2014 53/55 A sketch program public void keyTyped(KeyEvent event) { char keyChar = event.getKeyChar(); // set distance int d; if (Character.isUpperCase(keyChar)) { d = LARGE_INCREMENT; keyChar = Character.toLowerCase(keyChar); } else d = SMALL_INCREMENT; // add line segment if (keyChar == 'h') add(-d, 0); else if (keyChar == 'l') add(d, 0); else if (keyChar == 'k') add(0, -d); else if (keyChar == 'j') add(0, d); } } } Khoa CNTT – ĐH Nông Lâm TP HCM 2014 54/55 Class ActionEvent  public String getActionCommand() Returns the command string associated with this action  public int getModifiers() Returns the modifier keys held down during this action event  public Object getSource() The object on which the Event initially occurred  public static final int SHIFT_MASK The shift modifier An indicator that the shift key was held down during the event  public static final int CTRL_MASK The control modifier An indicator that the control key was held down during the event  public static final int ALT_MASK The alt modifier An indicator that the alt key was held down during the event Khoa CNTT – ĐH Nông Lâm TP HCM 2014 55/55 ... 2014 2/55 The Swing Painting Methods  paintComponent — The main method for painting By default, it first paints the background if the component is opaque Then it performs any custom painting ... g.drawImage(image, 90, 0, 30 0, 62, this); } } Khoa CNTT – ĐH Nông Lâm TP HCM 2014 5/55 The rules for the custom painting:  The painting code does something that no standard Swing component does If... override this method Khoa CNTT – ĐH Nông Lâm TP HCM 2014 3/ 55 Custom Painting  Before you implement a component that performs custom painting, first make sure that you really need to so You

Ngày đăng: 29/03/2021, 10:53