June 2013
Beginner
1007 pages
33h 32m
English
Now we can move on to some fun stuff. HelloJava3 brings us a new graphical interface
component: JButton.[4] In this example, 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 code looks like
this:
//file: HelloJava3.javaimportjava.awt.*;importjava.awt.event.*;importjavax.swing.*;publicclassHelloJava3{publicstaticvoidmain(String[]args){JFrameframe=newJFrame("HelloJava3");frame.add(newHelloComponent3("Hello, Java!"));frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setSize(300,300);frame.setVisible(true);}}classHelloComponent3extendsJComponentimplementsMouseMotionListener,ActionListener{StringtheMessage;intmessageX=125,messageY=95;// Coordinates of the messageJButtontheButton;intcolorIndex;// Current index into someColorsstaticColor[]someColors={Color.black,Color.red,Color.green,Color.blue,Color.magenta};publicHelloComponent3(Stringmessage){theMessage=message;theButton=newJButton("Change Color");setLayout(newFlowLayout());add(theButton);theButton.addActionListener(this);addMouseMotionListener(this);}publicvoidpaintComponent(Graphicsg){g.drawString(theMessage,messageX,messageY);}publicvoidmouseDragged(MouseEvente){messageX=e.getX();messageY=e.getY();repaint();}publicvoidmouseMoved(MouseEvent ...