May 2000
Beginner
726 pages
21h 42m
English
Well, now that
we have those concepts under
control, we can move on to some fun stuff.
HelloJava3 brings us a new graphical interface
component: the JButton.[9] We add a JButton component to our
application that changes the color of our text each time the button
is pressed. The draggable-message capability is still there, too. Our
new example is:
//file: HelloJava3.java import java.awt.*; import java.awt.event.*; import javax.swing.*; public class HelloJava3 extends JComponent implements MouseMotionListener, ActionListener { // Coordinates for the message int messageX = 125, messageY = 95; String theMessage; JButton theButton; // Current index into someColors int colorIndex; static Color[] someColors = { Color.black, Color.red, Color.green, Color.blue, Color.magenta }; public HelloJava3(String message) { theMessage = message; theButton = new JButton("Change Color"); setLayout(new FlowLayout( )); add(theButton); theButton.addActionListener(this); addMouseMotionListener(this); } public void paintComponent(Graphics g) { g.drawString(theMessage, messageX, messageY); } public void mouseDragged(MouseEvent e) { // Save the mouse coordinates and paint the message. messageX = e.getX( ); messageY = e.getY( ); repaint( ); } public void mouseMoved(MouseEvent e) {} public void actionPerformed(ActionEvent e) { // Did somebody push our button? if (e.getSource( ) == theButton) changeColor( ); } synchronized private void changeColor( ) { // Change the index to the ...Read now
Unlock full access