{ "@context": "https://schema.org", "@type": "Organization", "name": "Brainscape", "url": "https://www.brainscape.com/", "logo": "https://www.brainscape.com/pks/images/cms/public-views/shared/Brainscape-logo-c4e172b280b4616f7fda.svg", "sameAs": [ "https://www.facebook.com/Brainscape", "https://x.com/brainscape", "https://www.linkedin.com/company/brainscape", "https://www.instagram.com/brainscape/", "https://www.tiktok.com/@brainscapeu", "https://www.pinterest.com/brainscape/", "https://www.youtube.com/@BrainscapeNY" ], "contactPoint": { "@type": "ContactPoint", "telephone": "(929) 334-4005", "contactType": "customer service", "availableLanguage": ["English"] }, "founder": { "@type": "Person", "name": "Andrew Cohen" }, "description": "Brainscape’s spaced repetition system is proven to DOUBLE learning results! Find, make, and study flashcards online or in our mobile app. Serious learners only.", "address": { "@type": "PostalAddress", "streetAddress": "159 W 25th St, Ste 517", "addressLocality": "New York", "addressRegion": "NY", "postalCode": "10001", "addressCountry": "USA" } }

qna Flashcards

(119 cards)

1
Q

Question - What is an objective when learning graphics in Java

A

Answer - An objective is to implement simple drawing objects in Java.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Question - How do you create a basic JFrame for drawing in Java

A

Answer - You can create a JFrame instance, set its size, title, default close operation, and visibility. An example involves creating an integer w for width (e.g., 640) and h for height (e.g., 480), creating a JFrame f = new JFrame(), setting its size with f.setSize(w,h), setting the title with f.setTitle(“Drawing in Java”), setting the default close operation with f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE), and making it visible with f.setVisible(true). Remember to import javax.swing.*.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Question - Where are the lines for creating a JFrame typically placed, and why are they sometimes shown in the main method in these lessons

A

Answer - All the lines for creating a JFrame are usually placed in a separate class. To reduce the number of files used in the lesson, the JFrame is created in the main method instead.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Question - What is used as the canvas for programmatic drawing in Java graphics, and what is it like

A

Answer - You create a class that extends JComponent. This is where the programmatic drawing will be created. It is like the canvas that is drawn on, although the JComponent class is not exclusively just for drawing.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Question - What packages need to be imported when working with a JComponent subclass for drawing

A

Answer - You need to import java.awt.* for Color and Graphics, java.awt.geom.* for shapes and paths, and javax.swing.* for the JComponent.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Question - Why might a JComponent subclass constructor accept width and height parameters

A

Answer - The width (w) and height (h) parameters allow the JComponent to accept the width and height of the JFrame. This is not a requirement, but it can be useful for basing the position and size of the elements on the JFrame’s dimensions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Question - What method in a JComponent subclass is used for drawing, when is it called, and what object is automatically passed to it

A

Answer - You must override the paintComponent(Graphics g) method of the JComponent class. This method automatically gets called when the component is added to the frame; there is no need to write a call to it anywhere in the code. A Graphics object automatically gets passed to it as well; there is no need to create one.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Question - What is the Graphics object responsible for

A

Answer - The Graphics object is responsible for tasks such as setting the color, drawing lines, and filling shapes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Question - What is a Graphics2D object, how is it related to Graphics, and why might you use it

A

Answer - The Graphics2D object is an enhanced version of the Graphics object. It allows things like adding antialiasing to make the edges of shapes appear smoother.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Question - How do you obtain a Graphics2D object from the Graphics object passed to paintComponent

A

Answer - You can convert the Graphics object into a Graphics2D object using casting. The code is Graphics2D g2d = (Graphics2D) g;.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Question - What Java package contains classes used to create shapes and paths

A

Answer - The java.awt.geom package contains some classes that can be used to create shapes and paths.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Question - What are some examples of shape classes available in java.awt.geom

A

Answer - Some examples are Ellipse2D.Double, Line2D.Double, Path2D.Double, and Rectangle2D.Double.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Question - How do you create a rectangle using Rectangle2D.Double, and what do the constructor arguments represent

A

Answer - To create a rectangle, you use Rectangle2D.Double r = new Rectangle2D.Double(x,y,w,h);. The x and y are the shape’s location coordinates, and w and h are the shape’s dimensions (width and height). Double values for arguments are valid. For example, new Rectangle2D.Double(50,75,100,250) creates a rectangle originating from point x=50 and y=75, which is 100 pixels wide and 250 pixels high.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Question - Where is the origin point (x=0, y=0) located in a JComponent’s container

A

Answer - The point x=0 and y=0 is located at the top left corner of the JComponent’s container.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Question - How do you set the drawing color using a Graphics2D object, and how can you specify a color

A

Answer - You set the color using the setColor(Color c) method of Graphics2D. The Color constructor accepts three arguments, each an integer from 0 to 255, representing RGB (red, green, blue) values. Alternatively, you can use Color constants like Color.BLACK, Color.BLUE, or Color.MAGENTA.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Question - How do you fill a shape using a Graphics2D object

A

Answer - You use the fill(Shape s) method of Graphics2D to fill the shape with the most recently set Color.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Question - Where should the code for drawing shapes be placed within the JComponent subclass

A

Answer - Place all of the drawing code in the paintComponent(Graphics g) method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Question - How is the drawing viewed after creating the JFrame and JComponent subclass

A

Answer - To view the drawing, you create an instance of the JComponent subclass and add it to the frame in the main method. For example, after creating the JFrame f, you would create DrawingComponent dc = new DrawingComponent(w,h); and then call f.add(dc); before making the frame visible.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Question - How can a solid background be added to the drawing, and how should its dimensions relate to the frame

A

Answer - One way is to draw a large rectangle that covers the whole area. Set the x and y values to 0 so that it starts at the upper-left corner of the container. Make its dimensions match the width and height of the frame, using the width and height fields created in the JComponent subclass.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Question - How do you draw a circle or oval using Ellipse2D.Double, what do the arguments represent, and what determines if it’s a circle or an oval

A

Answer - To draw a circle, you use Ellipse2D.Double e = new Ellipse2D.Double(x,y,width,height);. The first two values passed to the constructor are the x and y coordinates. The last two values are the width and height. Equal values for width and height create a circle; unequal values will create an oval. You use the g2d.fill(e) method to render it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Question - How do you draw a line using Line2D.Double, what do the arguments represent, and what method is used to render it

A

Answer - To draw a line, you use Line2D.Double line = new Line2D.Double(x1,y1,x2,y2);. The first two values passed to the constructor are the x and y coordinates of the line segment’s starting point. The last two values are the x and y coordinates of the line segment’s ending point. Use the draw(Shape s) method for lines instead of fill(Shape s).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Question - How does the order of drawing commands affect the appearance of overlapping shapes

A

Answer - Based on the order of code in the paintComponent method, the first shape drawn will appear behind the succeeding shapes (more apparent if the shapes overlap). Each succeeding shape appears higher in the stack.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Question - What is antialiasing, and how is it implemented in Java graphics

A

Answer - Antialiasing will smoothen the edges of shapes (especially curves) by blending the colors of the edges with the background. To add antialiasing, create a RenderingHints object, for example RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);. Pass it to the Graphics2D object using its setRenderingHints(RenderingHints rh) method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Question - When should you set the RenderingHints for antialiasing

A

Answer - Set the RenderingHints before drawing the shapes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Question - Why might you want to declutter the paintComponent method, especially when drawing many elements
Answer - When drawing a lot of elements, the paintComponent method will end up with too many lines, which may become difficult to maintain.
26
Question - How can you declutter the paintComponent method by separating drawing elements
Answer - Consider separating these drawing elements into different classes. For example, lines of code that draw a cloud using multiple ellipses can be transferred to its own class.
27
Question - How can drawing code be moved to a separate class, and what method signature might be used there
Answer - You can create a new class (e.g., Cloud) and create a method inside it called draw that accepts a Graphics2D object. The drawing code for that element (e.g., the cloud ellipses) can be transferred to this draw method. Remember that the Graphics2D class also has a method named draw; the method in your new class can be named differently to minimize confusion.
28
Question - Once drawing code is in a separate class, how is the drawing executed from the paintComponent method
Answer - Back in paintComponent, you instantiate the new class (e.g., Cloud c1 = new Cloud();) and invoke its draw method, passing a reference to the Graphics2D object (e.g., c1.draw(g2d);). There is no need to create a new Graphics2D object; simply pass the original object reference, thinking of it as "passing the pen".
29
Question - How can a drawing class (like the Cloud example) be made reusable to draw different instances
Answer - Add instance fields to make the class reusable, allowing one class to draw different elements. These fields can include properties like position (private double x; private double y;), size (private double size;), and color (private Color color;).
30
Question - How are fields like position, size, and color used in the draw method of a reusable drawing class
Answer - Add a constructor to initialize the values of the fields (e.g., public Cloud(double x, double y, double s, Color c) { this.x = x; this.y = y; size = s; color = c; }). Then, use the fields to draw the object in the draw method instead of hard-coded values. The position and dimensions of shapes become relative to the values of the fields (x, y, and size), and the color is set using the field (color).
31
Question - How do you draw multiple instances of a reusable drawing class
Answer - Lastly, create instances of the reusable objects (e.g., Cloud c1 = new Cloud(10,50,75,Color.LIGHT_GRAY); Cloud c2 = new Cloud(200,75,90,Color.BLUE); Cloud c3 = new Cloud(420,60,85,Color.DARK_GRAY);) inside paintComponent and call the draw method for each instance (e.g., c1.draw(g2d); c2.draw(g2d); c3.draw(g2d);).
32
More Graphics in Java
33
Question - What are some objectives related to more complex graphics in Java
Answer - Objectives include implementing more complex graphics, and implementing Path2D objects, bezier curves, and transformations.
34
Question - How do you draw geometric paths in Java
Answer - Use the Path2D.Double class. Create an instance (e.g., Path2D.Double p = new Path2D.Double();). Use the moveTo(x,y) method to specify a starting point for the path. The call to moveTo moves the "pen" to the location (x, y); that will be the point where the path begins. Then use lineTo(x,y) to create a path segment from the previous point to the coordinates specified in the call to lineTo.
35
Question - When does a segment created with lineTo become visible
Answer - At the point where lineTo is called, the segment is not yet visible; a call to fill or draw on the Graphics2D object is required to render segments.
36
Question - Can you draw multiple disjoint segments in a single Path2D object
Answer - Yes, a call to moveTo can also be made in between calls to lineTo. This is like lifting the "pen" off the sheet of paper and moving it to a new point to start drawing a new segment. You can also make more calls to lineTo to create more segments connected to the previous point.
37
Question - How do you create curved segments in a path
Answer - Use the curveTo method. It requires six arguments: curveTo(x1, y1, x2, y2, x3, y3). x1,y1 are the coordinates of the 1st Bézier control point, x2,y2 are the coordinates of the 2nd Bézier control point, and x3,y3 are the coordinates of the segment's end point. The starting coordinate is determined by the previous segment.
38
Question - What are Bézier control points and Bézier handles used for in drawing curves
Answer - Bézier points create the Bézier handles. The first Bézier handle is formed by connecting the starting point to Bézier control point #1, and control point #2 connects to the segment's ending point. Bézier handles act as levers that control the direction of the curve. Instead of drawing a line from start point to end point, you follow the direction of the handle on each side.
39
Question - Can you connect multiple curved segments or mix straight and curved segments in a path
Answer - Yes, calls to curveTo can be made successively; the starting point of the next curve will be the ending point of the previous one. A call to lineTo can also come before or after curveTo, creating a straight segment and a curved segment that are connected.
40
Question - What class is used for applying transformations like translation, scaling, and rotation to graphics
Answer - Use the Graphics2D class to apply transformation functions.
41
Question - What is translation in graphics, and how does the translate(x,y) method work
Answer - Translation allows moving the origin point (which was originally at x:0, y:0 of the container) elsewhere. When you call g2d.translate(250,300), it is not the shape's coordinates that are changed. Instead, after the call to translate, anything drawn follows the newly translated origin point, which is now at x:250, y:300. An analogy is moving the entire sheet of paper instead of moving the pen.
42
Question - What happens with successive calls to the translate method
Answer - Further calls to translate will concatenate the translation values.
43
Question - How can you reset the translation back to the original origin point using the translate method
Answer - Pass the negative counterparts of the previous values to offset back to the original. Calling translate(0,0) will simply add 0 to the previous x and y translation values, leaving them unchanged, and will not reset the values back to the original.
44
Question - Is there a better way to reset transformations than using negative translate values
Answer - Yes, use an AffineTransform object.
45
Question - What is an AffineTransform object, and how can it be used to reset transformations
Answer - An AffineTransform object contains the values that represent a transformation's state (rotation, translation, etc.). You can access this information using the getTransform method of the Graphics2D class (e.g., g2d.getTransform()). To reset transformations, get the default AffineTransform before making any transformations, for example AffineTransform reset = g2d.getTransform();. This object contains the values representing the original state. You can then reset the values back to the original state using the setTransform method of the Graphics2D class, which accepts an AffineTransform object (e.g., g2d.setTransform(reset);).
46
Question - Why is the translate method useful
Answer - The translate method enables moving a group of objects instead of editing their x and y positions one by one.
47
Question - How do you rotate graphics using the Graphics2D class, and what unit is used for the angle
Answer - Use the rotate method of the Graphics2D class. Pass to it the desired angle of rotation. The value must be in radians, not degrees. You can use Math.toRadians and pass to it the value in degrees to convert it, for example g2d.rotate(Math.toRadians(15));.
48
Question - What is the default pivot point for rotation when using the rotate(angle) method
Answer - The rotated shape pivots from x:0, y:0 of the coordinate space, and not the shape's own x and y coordinates. This might not be the intended behaviour.
49
Question - How can you rotate a shape around a specific pivot point
Answer - Pass three arguments to the rotate method instead of one: the angle of rotation, the x coordinate of the pivot point, and the y coordinate of the pivot point. For example, g2d.rotate(Math.toRadians(15),250,300); will cause the rotation to pivot from the point (250, 300).
50
Question - What happens with successive calls to the rotate method
Answer - Succeeding calls to rotate will rotate based on the previous call. For instance, if you rotate by 15 degrees, draw, and then rotate by another 5 degrees, the subsequent shapes will have a 20-degree rotation (15 from the previous plus 5).
51
Question - How do you reset the rotation transformation before applying a new rotation
Answer - Do a reset if successive rotations are not intended. You can use AffineTransform reset = g2d.getTransform(); before the rotation, draw, and then call g2d.setTransform(reset);. This way, the succeeding shapes will have a rotation based on the default transformation settings or a new, independent rotation.
52
Simple Collisions
53
Question - What is the objective related to simple collisions in Java graphics
Answer - The objective is to implement collision detection for graphics in Java.
54
Question - How are the position and dimension of graphical objects represented
Answer - Graphical objects need at least two numbers to represent their location along the x-axis and along the y-axis. In addition to position, it is necessary to consider the space an object occupies; for example, a rectangle's space can be represented by width and height.
55
Question - In the Java coordinate system, how do changes in x and y values affect an object's position
Answer - x = 0, y = 0 is the upper left corner of the drawing component. Increasing x moves right, decreasing x moves left. Increasing y moves down, decreasing y moves up.
56
Question - How is a simple rectangle drawn using the Graphics object
Answer - A rectangle can be drawn using g.fillRect(x, y, width, height);. The x and y represent the rectangle's upper left point, and width and height are its dimensions. This concept applies even when using Graphics2D.
57
Question - What is collision detection
Answer - Collision detection is the process of determining if two objects overlap — whether they both occupy the same space or at least parts of them occupy the same space.
58
Question - How is collision defined for the purpose of the lesson on simple collisions
Answer - Collision, for the purposes of this lesson, is defined to be true if and only if ANY of their pixels overlap.
59
Question - What are the conditions that indicate non-collision between two rectangles (r1 and r2)
Answer - Two rectangles are not colliding if any of the following conditions are true:
60
The rightmost edge of r1 (r1.x + r1.width) is less than or equal to the leftmost edge of r2 (r2.x). If r1.x + r1.width is less than r2.x, they are not colliding. If r1.x + r1.width is equal to r2.x, they are beside each other but not colliding.
61
The leftmost edge of r1 (r1.x) is greater than or equal to the rightmost edge of r2 (r2.x + r2.width). This checks if the leftmost edge of r1 is NOT colliding with the rightmost edge of r2.
62
The bottommost edge of r1 (r1.y + r1.height) is less than or equal to the topmost edge of r2 (r2.y). This checks if the bottommost edge of r1 is NOT colliding with the topmost edge of r2.
63
The topmost edge of r1 (r1.y) is greater than or equal to the bottommost edge of r2 (r2.y + r2.height). This checks if the topmost edge of r1 is NOT colliding with the bottommost edge of r2.
64
Question - How can these non-collision conditions be used to determine if two rectangles are colliding
Answer - Determine conditions that state NON-collision. Check all four of those possibilities. If at least one of those conditions is true, then the rectangles are not colliding. If all of those conditions are false, then the rectangles are colliding.
65
Question - How is the isColliding method implemented for rectangles, and why is the result negated
Answer - The isColliding method accepts another MyRectangle object as input. It returns the negation of the combined non-collision conditions using the logical OR operator (||): return !(this.x + this.width <= other.getX() || this.x >= other.getX() + other.getWidth() || this.y + this.height <= other.getY() || this.y >= other.getY() + other.getHeight() );. The negation (!) is used because the individual conditions check for non-collision, but the method is named isColliding.
66
Question - What is an alternative naming convention for the collision method if the negation is removed
Answer - Alternatively, the negation can be removed, and the method can be renamed isNotColliding.
67
Question - How are circles represented in terms of position and dimension for drawing
Answer - The position can be represented by using x and y. The dimension can be represented using a radius. A circle can be drawn using g.fillOval(x, y, radius*2, radius*2);.
68
Question - What mathematical clues are given for determining if two circles are colliding
Answer - Mathematically, all points on a circle's perimeter are equidistant from the center, with the distance being equal to the radius. The shortest path between two points is a straight line. If a straight line were drawn to connect the center points of two circles, you can determine the length of that line. To detect collision, consider the relationship between the sum of each circle's radius and the length of the line connecting their centers.
69
Threads
70
Question - What is the objective related to threads in Java
Answer - The objective is to implement threads to allow multiple tasks to execute in parallel.
71
Question - How are lines of code usually executed in a program
Answer - Lines of code are executed in sequence.
72
Question - Why might you need tasks to be executed concurrently
Answer - You might need tasks executed concurrently if, for example, you want to play some animation and also play some music while the animation is running.
73
Question - What are threads, and how do they relate to processes
Answer - To execute concurrent tasks, you use threads. A thread is a lightweight process (LWP), whereas a traditional process is known as a heavyweight process (HWP). Like other processes, a thread runs on a processor, is loaded and terminated, refers to program code, manipulates data, and can spawn other processes or threads.
74
Question - What is a key difference between a thread and a traditional process regarding their creation
Answer - Unlike a regular process, a thread MUST be spawned by another process or thread.
75
Question - Do threads actually run concurrently on a single processor machine
Answer - No, threads don't actually run concurrently; they only appear to do so. The processor rapidly switches between threads.
76
Question - How is the appearance of simultaneous execution achieved with threads on a single processor
Answer - Each thread gets a certain amount of time, which is called a time slice. For example, with two threads and a 10ms time slice, the CPU devotes 10ms to Thread 1, then switches to Thread 2 and devotes 10ms, rapidly switching until one or both threads terminate. The CPU can switch very quickly, creating the illusion of simultaneous execution.
77
Question - What happens with threads if the machine has multiple processors
Answer - If the machine has multiple processors, some threads can run simultaneously. This may significantly increase computation speed for some applications. Data and computational load can be shared among threads. You can break a large task into smaller ones and assign them to threads, and results of one thread can be retrieved by another thread.
78
Question - What are the two main ways to use threads in Java
Answer - The two ways to use threads in Java are: 1. Extend the Thread class, and 2. Implement the Runnable interface.
79
Question - How do you create and run a thread by extending the Thread class
Answer - Create a class that extends Thread. Override the run() method; the task instructions go inside this method. Instantiate the Thread object (an instance of your class) and call the start() method. Calling the start() method will cause instructions defined inside run to execute in a new thread. The thread terminates once the run() method is finished.
80
Question - What is the difference between calling the start() method and the run() method of a Thread object
Answer - If the run() method is called directly, it will execute the instructions, but they will NOT run in a new thread. Calling start() is necessary to execute run() in a separate thread.
81
Question - What is a limitation of extending the Thread class for creating threads
Answer - In Java, each class can only extend one other class. If the class that has to run in a thread needs to extend another class, consider implementing the Runnable interface instead.
82
Question - How do you create and run a thread by implementing the Runnable interface
Answer - Implement the Runnable interface and override the run() method; the task instructions go inside this method. Create an instance of the Runnable object (e.g., Runnable r = new MyRunnable();). Create a Thread object and pass the Runnable object to its constructor (e.g., Thread t = new Thread(r);). Finally, start the thread by calling the start() method on the Thread object (e.g., t.start();).
83
Question - How can you make a thread pause or sleep for a specific duration in Java
Answer - The Thread class has a static method named sleep. It accepts a value in milliseconds. It makes the thread sleep for that amount of time.
84
Question - What Java structure is required when using the Thread.sleep() method
Answer - When using the sleep() method, it must be placed inside a try-catch block. For example: try { // instructions } catch (SomeException e) { // other instructions }. The specific exception to catch is InterruptedException.
85
Key Bindings
86
Question - What is the objective related to key bindings in Java
Answer - The objective is to implement key bindings as a way of responding to user keystrokes.
87
Question - What Java packages are needed for implementing key bindings
Answer - You need to import java.awt.*, java.awt.event.*, and javax.swing.*.
88
Question - How do you prepare a GUI component to accept key bindings
Answer - When setting up the GUI, get the contentPane of the JFrame. Cast it to a JPanel so that its ActionMap and InputMap can be retrieved. Make the contentPane focusable by calling cp.setFocusable(true) to ensure that keystrokes can be detected.
89
Question - What two components are key bindings based on, and where are they accessed from
Answer - Key bindings rely on an ActionMap and an InputMap. These objects can be accessed from a JComponent.
90
Question - What does an ActionMap do in key bindings
Answer - An ActionMap is responsible for mapping an action to a name. For example, "up" could map to code that makes a character move up.
91
Question - What does an InputMap do in key bindings
Answer - An InputMap is responsible for mapping a key on the keyboard to an action name. For example, the up arrow key could map to the "up" action.
92
Question - How do you obtain the ActionMap and InputMap objects from a component
Answer - You can retrieve them using the getActionMap() and getInputMap() methods of the component, for example ActionMap am = cp.getActionMap(); InputMap im = cp.getInputMap();.
93
Question - What class is used to define an action for key bindings, and what method contains the action's code
Answer - Use the AbstractAction class and override the actionPerformed(ActionEvent ae) method to specify the instructions for the action.
94
Question - How are actions associated with names in the ActionMap
Answer - Put the actions in the ActionMap using the put() method. The method signature is am.put("actionName", abstractActionObject);. The first argument is the name assigned to the action (determined by the programmer), and the second argument is a reference to the AbstractAction object.
95
Question - How are keystrokes mapped to action names using the InputMap
Answer - Use the InputMap to map keystrokes to action names. The method signature is im.put(KeyStroke.getKeyStroke(...), "actionName");. The first argument is the keystroke, and the second argument is the action name (from the ActionMap).
96
Question - How is a KeyStroke object created, and what do its arguments represent
Answer - A KeyStroke object can be created using the static method KeyStroke.getKeyStroke(). It takes arguments like KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false). The first argument is the key code (e.g., KeyEvent.VK_UP), the second argument is the modifier (e.g., 0 if there is no modifier like SHIFT + UP), and the third argument activates the key either on press (false) or on release (true).
97
Networking in Java
98
Question - What is the objective related to networking in Java
Answer - The objective is to implement programs that communicate across networks.
99
Question - What is the client-server model in networking
Answer - Communication over the network often occurs between a client and a server. A client is a device that requests services or resources from another device, known as the server. A server is a system that provides or serves these requested services or resources to the client.
100
Question - What are the typical roles of a server and a client in the client-server model
Answer - A server waits for connection requests from clients, accepts them, and then responds to their requests. A client connects to a server and then sends and receives data.
101
Question - What is TCP/IP, and what are the roles of TCP and IP
Answer - TCP/IP is a suite of protocols used for network communication. TCP (Transmission Control Protocol) is responsible for establishing reliable connections and manages packet ordering, retransmissions, and flow control. IP (Internet Protocol) is responsible for addressing and routing; it assigns addresses (IP addresses) to devices and ensures data packets are correctly routed.
102
Question - What are the benefits of using TCP/IP
Answer - TCP/IP enables interoperability across different networks. It also provides an abstraction of complex network operations, hiding the complexity of underlying network hardware and communication details from applications, meaning developers don't need to be networking experts.
103
Question - What is a host in networking
How is it identified
104
Question - What is a port, and what is it used for
Answer - A port is a number that specifies a particular service provided by the host. For example, port 80 is for HTTP. Each server can listen to many ports, and each port can accommodate many clients.
105
Question - What is a Socket in Java networking
Answer - A Socket is an object that encapsulates the process of communicating over the network.
106
Question - What Java package is used for networking, and what are some important classes within it
Answer - The java.net package is used for networking. Some important classes from this package are Socket and ServerSocket.
107
Question - How is a Socket object created by a client program, and what methods are useful for sending/receiving data
Answer - The Socket constructor takes the host's IP address (or hostname) and the port number that the client wants to connect to. Useful Socket methods are InputStream getInputStream() and OutputStream getOutputStream(). Writing to the OutputStream sends data to the other host, and reading data requires the other host to read from its InputStream.
108
Question - What is a ServerSocket, and how does it differ from a Socket
Answer - Its name is a misnomer; it is NOT a Socket. It does NOT extend Socket and does not have the same methods. It creates Sockets in response to a client connection.
109
Question - How is a ServerSocket created, and what does its accept() method do
Answer - The ServerSocket constructor takes the port number to bind the ServerSocket to. The accept() method is called to accept a client. The thread that calls accept() blocks (waits or sleeps) until a client connects. The thread continues after a client connects, and the accept() method returns a Socket object connected to the client.
110
Question - What are the basic steps involved in a server program for network communication
Answer - In the server program, you create a ServerSocket object and specify the port number. You then invoke accept() on that object to obtain the Socket object returned by the accept() method. Obtain I/O streams from the Socket and carry out communication (send and receive data) using these streams.
111
Question - What are the basic steps involved in a client program for network communication
Answer - In the client program, you create the Socket object. You specify the host's IP address (or hostname) and the port number that the ServerSocket is bound to. Obtain I/O streams from the Socket and carry out communication (send and receive data) using these streams.
112
Question - Which program, the client or the server, should be executed first
Answer - It is important to execute the server program before the client program.
113
Question - What Java exception handling is necessary for network instructions
Answer - You should place network instructions inside a try-catch block to handle IOException.
114
Question - How can client and server programs be tested on a single machine
Answer - To test the Client and Server on the same machine, open two Command Line / Terminal windows. Run the Server in one window. In the Client, replace the server's IP address or hostname (like "myserver") with "localhost" or "127.0.0.1" and then run the Client in the second window. The machine will connect to itself.
115
Question - How should read and write operations be aligned between the client and the server
Answer - Note that if one host first writes a message, the other should have a matching read instruction. They cannot both be reading or writing at the same time. If the server should write first, then the client should start with a read. If one host makes n consecutive writes, then the other one should have n consecutive reads, and vice versa.
116
Question - Can data types other than String be sent and received using the streams obtained from a Socket
Answer - Yes, it is possible to read and write other types of data. Examples include readBoolean(), writeBoolean(Boolean b), readInt(), writeInt(int i), readDouble(), and writeDouble(Double d). These methods are available on DataInputStream and DataOutputStream.
117
Question - How can a server program handle multiple clients concurrently
Answer - To handle multiple clients, use Threads. The Main Thread in the Server can have a loop that continuously calls accept(). Create and start a new "connection thread" whenever accept() returns a Socket, with one thread to manage each client.
118
Question - What is the role of a "connection thread" in a multi-client server
Answer - A connection thread is a thread for communicating with one (1) client only. Do not use one thread for more than one client; have one thread for each client. The thread reads from and writes to its client via the Socket's input and output streams. Each client will have its own Socket. Use a loop within the connection thread to continuously read data coming from its client.
119
Question - Should network code and GUI code be placed in the same thread
Why or why not