How to Draw a Circle When Pressing Jbutton
13.4 Button Events
Whenever a button is pressed, this produces an event known as an action effect. We say that the button object is the source of the event. If some object is interested in knowing that a particular event has occurred, that object must indicate that information technology wants to exist a listener to occurrences of that event. To do so, the object must register as a listener. Each object that tin produce events maintains a listing of the objects that are listeners to that particular type of event. When an event occurs, all of the objects registered as listeners for that blazon of consequence are passed appropriate information about the issue. They can then act on this information in whatsoever way that we wish them to do.
To begin to show how this works, suppose that we accept synthetic a JButton object called demoButton and that we want an object of the class ButtonResponse to deed as a listener for presses of demoButton. To do and then, we must do a number of things.
- We register an object as a listener by implementing an interface. To mind to a push button, the interface that nosotros need to implement is called ActionListener. For our example, we note that ButtonResponse is implementing the ActionListener interface by writing the form header as
class ButtonResponse implements ActionListener - We must now really perform this implementation of the ActionListener interface. Think that to implement an interface, we must provide actual methods for all the methods whose headers are given in the interface. The ActionListener interface requires the implementation of only i method:
public void actionPerformed (ActionEvent e)
It is within this method that nosotros would identify our code for the action nosotros want to perform whenever demoButton is pressed. - Finally, we need to add a ButtonResponse object to demoButton�s listing of listeners by invoking the method with header
void addActionListener (ActionListener al)
The implicit object passed to this method is demoButton and the parameter is a ButtonResponse object (which we take made into an ActionListener object through the utilize of the interface). If we are calling the method from inside the ButtonResponse class, the ActionListener object that we pass to the method is the current implicit ButtonResponse object. The call, therefore, would take the course
demoButton.addActionListener(this);
The next example shows how we can contain these ideas into a complete (although fairly fiddling) program.
Example i
This program creates a window containing a single push. Whenever the button is pressed, the background colour of the push button changes randomly.import java.awt.*; import coffee.awt.event.*; import javax.swing.*; public class ButtonColour implements ActionListener { JButton colourButton = new JButton("Change Colour"); public ButtonColour() { JFrame frame = new JFrame("Push Events"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 100); colourButton.addActionListener( this ); frame.setLayout( new FlowLayout()); frame.add(colourButton); frame.setVisible( true ); } public void actionPerformed(ActionEvent e) { colourButton.setBackground( new Color(forcefulness(), strength(), strength())); } public static int forcefulness() { return ( int )(256 * Math.random()); } public static void principal( String [] args) { new ButtonColour(); } }
The window produced by the program should look something like this. Each time that the button is pressed, the colour of the button changes randomly to one of 16 777 216 (2563 = xvi 777 216) possible colours.
Note: There is no telephone call to the method actionPerformed. Instead, since the colourButton object is registered equally a listener to ActionEvents, a telephone call to the actionPerformed method within the ButtonColour grade is made automatically whenever the button chosen colourButton is pressed.
The parameter of the method actionPerformed is an ActionEvent object called e. This parameter, supplied automatically by Coffee, contains information about the outcome that produced the call to actionPerformed. Since our plan is but registered as a listener for ane event (the pushing of colourButton), nosotros exercise not demand to utilize the parameter because the only fourth dimension that this method will be called is when that detail button is pushed. If nosotros have registered for more than ane event, and then we may need to examine the parameter to determine which outcome caused the call to actionPerformed. This is illustrated in the next example.
Example 2
The grade TriColourFrame defines windows that take 3 buttons � one for each of the component colours (ruby, dark-green, or blueish). An object of this class volition prepare the background colour of a window to one of these colours whenever the appropriate button is pressed.import java.awt.*; import java.awt.upshot.*; import javax.swing.*; class TriColourFrame implements ActionListener { JButton redButton = new JButton("blood-red"); JButton greenButton = new JButton("green"); JButton blueButton = new JButton("bluish"); JFrame frame = new JFrame("Tricolour Buttons"); public TriColourFrame () { frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); redButton.addActionListener( this ); greenButton.addActionListener( this ); blueButton.addActionListener( this ); frame.setLayout( new FlowLayout()); frame.add together(redButton); frame.add(greenButton); frame.add(blueButton); frame.setSize(300,100); frame.setVisible( true ); } public void actionPerformed (ActionEvent east) { if (e.getSource() == redButton) frame.getContentPane().setBackground(Color.red); else if (east.getSource() == greenButton) frame.getContentPane().setBackground(Color.dark-green); else if (e.getSource() == blueButton) frame.getContentPane().setBackground(Colour.bluish); else frame.getContentPane().setBackground(Colour.black); } public static void main( Cord [] args) { new TriColourFrame(); } }
In Case two, the deportment of the constructor in the class TriColourFrame are like to those of the corresponding constructor in the previous example. The only essential deviation is the extra work that must be done because at that place are at present iii buttons instead of one.
The actionPerformed method uses the value of the parameter east to decide what activeness should be taken. The getSource method gives a reference to the JButton that generated the ActionEvent (which button was clicked). The actionPerformed method then sets the frame'south backgound to the appropriate colour.
The following instance is similar to Example two except it shows how to utilize graphics with buttons.
Example 3
This example will draw a square, rectangle or a circle depending on which push is pressed.
import java.awt.*; import java.awt.issue.*; import javax.swing.*; public class DrawingShapes implements ActionListener { int choice = 0; JButton square = new JButton("Square"); JButton rectangle = new JButton("Rectangle"); JButton circle = new JButton("Circle"); Drawing depict = new Drawing(); public DrawingShapes() { JFrame frame = new JFrame("Draw Shapes"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); square.addActionListener( this ); rectangle.addActionListener( this ); circle.addActionListener( this ); JPanel panel = new JPanel(); panel.add together(square); console.add together(rectangle); panel.add(circumvolve); frame.add(panel, "North"); frame.add together(describe); frame.setSize(500,500); frame.setVisible( true ); } public void actionPerformed(ActionEvent e) { if (due east.getSource() == foursquare) choice = 1; else if (east.getSource() == rectangle) option = 2; else option = 3; draw.repaint(); } class Drawing extends JComponent { public void paint(Graphics g) { grand.setColor(Colour.crimson); if (pick == 1) g.fillRect(100,lxxx,300,300); else if (choice == 2) yard.fillRect(50,200,350,100); else if (choice == 3) g.fillOval(150,100,200,200); } } public static void main( Cord [] args) { new DrawingShapes(); } }
Hither is what the output will expect like after the circle button is pressed.
Exercise 13.four
- Write a program that uses a flow layout to display a window containing two buttons, 1 labelled "On" and the other labelled "Off". If a user presses "On", the groundwork colour should be set to white but if a user presses "Off", the groundwork should be gear up to black.
- Alter the program of the previous question then that the labels on the buttons are "Brighter" and "Dimmer". If a user presses "Brighter", the background colour should be fix closer to white (if it is not already white) while pressing "Dimmer" moves the background closer to blackness (if it is non already blackness). Have each press of a button change the intensity past one-sixteenth of the divergence between pure white and pure black.
- Change the code in instance 3 to add together two buttons labelled "Larger" and "Smaller". Clicking "Larger" volition add v pixels to the size of the shape that is showing (it will affect any shape shown after too). Clicking "Smaller" will decrease five pixels from the size.
Source: http://ntci.on.ca/compsci/java/ch13/13_4.html
0 Response to "How to Draw a Circle When Pressing Jbutton"
Post a Comment