1. Trang chủ
  2. » Giáo Dục - Đào Tạo

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

55 9 0

Đ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

Thông tin cơ bản

Định dạng
Số trang 55
Dung lượng 166,98 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Here is some code that a component might use to determine the width and height available for custom painting: public void paintComponentGraphics g { .... Class Graphicy, int width, int

Trang 1

PHẦN 2 - SWING

PAINTING

MOUSE AND KEYBOARD EVENTS

Trang 2

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.

Trang 3

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

Trang 4

Custom Painting

 Before you implement a component that performs custom painting, first make sure that you really need to do 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

Trang 5

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

}

}

Trang 6

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

Trang 7

The Coordinate System

Trang 8

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)

Trang 9

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 */

}

Trang 10

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

 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.

Trang 11

Painting Shapes

 The Graphics class defines methods for painting the

following kinds of shapes:

 Lines (drawLine)

 Rectangles (drawRect and fillRect)

 Raised or lowered rectangles (draw3DRect and

fill3DRect)

 Round-edged rectangles (drawRoundRect and

fillRoundRect)

 Ovals (drawOval and fillOval)

 Arcs (drawArc and fillArc)

 Polygons (drawPolygon, drawPolyline, and

fillPolygon)

Trang 12

Shape Sample

Trang 13

Class Graphic

Gets this graphics context's current color

Returns:this graphics context's current color

Sets this graphics context's current color to the specified

color All subsequent graphics operations using this

graphics context use this specified color

Parameters:c - the new rendering color

Gets the current font Returns:this graphics context's current font

Sets this graphics context's font to the specified font All

subsequent text operations using this graphics context use this font Parameters:font - the font

Trang 14

Class Graphic

y, int width, int height, int dx, int

dy)

Copies an area of the component by a distance specified by

dx and dy From the point specified by x and y, this method copies downwards and to the right

 Parameters:

x - the x coordinate of the source rectangle

y - the y coordinate of the source rectangle

width - the width of the source rectangle

height - the height of the source rectangle

dx - the horizontal distance to copy the pixels

dy - the vertical distance to copy the pixels

Trang 15

fillRect public abstract void fillRect(int

x, int y, int width, int height)

Fills the specified rectangle The left and right edges of the

rectangle are at x and x + width - 1 The top and bottom edges are at y and y + height - 1 The resulting rectangle covers an area width pixels wide by height pixels tall The rectangle is filled

using the graphics context's current color

public void drawRect(int x, int y, int

width, int height)

Draws the outline of the specified rectangle The left and right edges of the rectangle are at x and x + width The top and

bottom edges are at y and y + height The rectangle is drawn

using the graphics context's current color

Trang 16

Class Graphic

int width,int height)

Clears the specified rectangle by filling it with the background color

of the current drawing surface This operation does not use the current paint mode

y, int width,int height,int arcWidth, int

arcHeight)

Draws an outlined round-cornered rectangle using this graphics

context's current color The left and right edges of the rectangle are at

x and x + width, respectively The top and bottom edges of the

rectangle are at y and y + height

Parameters:

x - the x coordinate of the rectangle to be drawn.

y - the y coordinate of the rectangle to be drawn.

width - the width of the rectangle to be drawn.

height - the height of the rectangle to be drawn.

arcWidth - the horizontal diameter of the arc at the four corners.

arcHeight - the vertical diameter of the arc at the four corners.

Trang 17

Class Graphic

y, int width, int height, int arcWidth, int

arcHeight)

Fills the specified rounded corner rectangle with the current color

The left and right edges of the rectangle are at x and x + width - 1, respectively The top and bottom edges of the rectangle are at y and y + height – 1

width, int height,boolean raised)

Draws a 3-D highlighted outline of the specified rectangle The edges

of the rectangle are highlighted so that they appear to be beveled and lit from the upper left corner The colors used for the highlighting

effect are determined based on the current color The resulting

rectangle covers an area that is width + 1 pixels wide by height + 1 pixels tall

width, int height, boolean raised)

Trang 18

Class Graphic

y, int width, int height)

Draws the outline of an oval The result is a circle or ellipse that fits within the rectangle specified by the x, y, width, and height arguments The oval covers an area that is width + 1 pixels wide and height + 1 pixels tall

width - the width of the oval to be drawn.

height - the height of the oval to be drawn.

y, int width, int height)

Fills an oval bounded by the specified rectangle with the current color.

Trang 19

Class Graphic

y, int width, int height, int

startAngle, int arcAngle)

width - the width of the arc to be drawn

height - the height of the arc to be drawn

startAngle - the beginning angle

arcAngle - the angular extent of the arc, relative to the start angle

y, int width, int height, int

startAngle, int arcAngle)

Trang 20

Class Graphic

xPoints, int[] yPoints,int nPoints)

Draws a sequence of connected lines defined by arrays of x and y

coordinates Each pair of (x, y) coordinates defines a point The figure is not closed if the first point differs from the last point

Parameters:

xPoints - an array of x points

yPoints - an array of y points

nPoints - the total number of points

int[] yPoints,int nPoints)

int[] yPoints,int nPoints)

Trang 21

Class Graphic

int x,int y, ImageObserver observer)

Draws as much of the specified image as is currently available The image is drawn with its top-left corner at (x, y) in this graphics

context's coordinate space If the image has not yet been completely loaded, then drawImage returns false As more of the image becomes available, the process that draws the image notifies the specified

observer - object to be notified as more of the image is converted.

int x, int y, int width, int height,

ImageObserver observer)

Trang 22

ShapeTest

Trang 24

ShapeTest

Trang 25

Mouse Events

 When the user clicks a mouse button, three listener

methods are called:

1 mousePressed when the mouse is first pressed,

2 mouseReleased when the mouse is released, and,

finally,

3 mouseClicked.

 If you are only interested in complete clicks, you can

ignore the first two methods By using the getX and

getY methods on the MouseEvent argument, you can

obtain the x- and y-coordinates of the mouse pointer when the mouse was clicked If you want to distinguish between single, double and triple (!) clicks, use the

getClickCount method.

Trang 26

MouseListener Interface

Invoked when the mouse button has been clicked (pressed and released) on a component

Invoked when a mouse button has been pressed on a

component

Invoked when a mouse button has been released on a

component

Invoked when the mouse enters a component

Invoked when the mouse exits a component

Trang 27

Invoked when a mouse button is pressed on a component

and then dragged MOUSE_DRAGGED events will

continue to be delivered to the component where the drag originated until the mouse button is released (regardless of whether the mouse position is within the bounds of the

component) Due to platform-dependent Drag&Drop

implementations, MOUSE_DRAGGED events may not be

delivered during a native Drag&Drop operation

Invoked when the mouse cursor has been moved onto a

component but no buttons have been pushed

Trang 28

Invoked when the mouse cursor has been moved onto a component but

no buttons have been pushed.

Trang 29

Mouse Events

 If the user presses a mouse button while the mouse is in

motion, mouseDragged calls are generated instead of

mouseClicked calls

 Some user interface designers inflict mouse click and

keyboard modifier combinations, such as CONTROL +

SHIFT + CLICK.

mouse buttons and keyboard modifiers of a mouse event

(nonprimary) mouse button under Windows For example, you can use code like this to detect if the right mouse button

Trang 30

 Finally, we need to explain how to listen to mouse events Mouse

clicks are reported through the mouseClicked procedure, which is part of the MouseListener interface Because many applications

are interested only in mouse clicks and not in mouse moves, and

because mouse move events occur so frequently, the mouse move

and drag events are defined in a separate interface called

MouseMotionListener :

1 public void mouseDragged(MouseEvent e)

2 public void mouseMoved(MouseEvent e)

Trang 31

public Point getLocationOnScreen()

Returns the absolute x, y position of the event.

public int getX()

Returns the horizontal x position of the event relative to the

source component.

public int getY()

Returns the vertical y position of the event relative to the source component.

public int getClickCount()

Returns the number of mouse clicks associated with this event

public int getButton()

Returns which, if any, of the mouse buttons has changed state

( NOBUTTON , BUTTON1 , BUTTON2 or BUTTON3 ).

public int getModifiersEx()

Returns the extended modifier mask for this event, such as ALT,

CTRL and the mouse buttons just after the event occurred

Trang 32

Button Paint Test

Trang 33

Button Paint Test

public class ButtonFrame extends JFrame{

JPanel panel;

public ButtonFrame(){

super("Button Paint Test");

panel = new JPanel();

panel.setLayout(new FlowLayout());

panel.add(new MouseButton("Mouse Button"));

Trang 34

Button Paint Test

private class MouseButton extends JButton{

private class MouseHandler extends MouseAdapter{

public void mouseEntered(MouseEvent e){

Trang 35

MouseEvent - Paint Test

Trang 36

MouseEvent - Paint Test

public class SketchMouseFrame extends JFrame {

public SketchMouseFrame(){

setTitle("MouseEvent Test");

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

getContentPane().add(new MousePanel());

setSize(300,200);

setVisible(true);

}

Trang 37

MouseEvent - Paint Test

private class MousePanel extends JPanel{

private boolean start;

private Point last;

private ArrayList<Point> lines;

public MousePanel(){

start = false;

lines = new ArrayList<Point>();

addMouseListener(new MouseHandler());

addMouseMotionListener(new

MouseMotionHandler());

setBackground(Color.white);

}

Trang 38

MouseEvent - Paint Test

private class MouseHandler extends MouseAdapter{

public void mouseClicked(MouseEvent e){

if (e.getButton() == e.BUTTON1){

start = true ;

last = new Point(e.getX(), e.getY());

lines add( last );

last = new Point(e.getX(), e.getY());

lines add( last );

repaint();

}

} }

Trang 39

MouseEvent - Paint Test

public void paintComponent(Graphics g){

super.paintComponent(g);

g.setColor(Color.black);

// draw all lines

if (lines.size()<2) return;

Point firstPoint = (Point)lines.get(0);

Point secondPoint;

for (int i = 1; i < lines.size(); i++){

secondPoint = (Point) lines.get(i);

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

w