Help get this topic noticed by sharing it on Twitter, Facebook, or email.

Learning Java 4th Ed. Errors in Examples

Hey Guys,

I am trying to follow the examples in the Learning Java 4th edition book and am running into problems when typing them exactly as I see them. Below is an example from Chapter 2. It is complaining at the first "frame.add" method.
package bookWork; Can anyone explain to me why this is happening and how to fix it?

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class HelloJava2 {
public static void main(String[] args){
JFrame frame = new JFrame("Frame Title");
frame.add(new HelloComponent2("Hello, Java")); //ERROR!: No enclosing instance of type HelloJava2 is accessible. Must qualify the allocation with an eclosing instace of type HelloJava2.
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true);
}
class HelloComponent2 extends JComponent
implements MouseMotionListener{
String theMessage;
int messageX = 125, messageY = 95; //Coordinates of the message

public HelloComponent2( String message){
theMessage = message;
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) {}
}
}

Another problem is from the first example of chapter 2.
You have 2 classes in separate class .java files. The HelloComponent class has an error on the "public class HelloComponent" line, saying "The serializable class HelloComponent does ont declare a static final serialVersionUID field of type long", this is also the case for HelloComponent2 mentioned above. Can someone explain to me the reason for this error and how to fix it?

package bookWork;

import javax.swing.*;

public class HelloJava {

public static void main(String[] args) {
JFrame frame = new JFrame("Frame Title!");
//JLabel label = new JLabel("Label Content", JLabel.CENTER);
frame.setSize(300,600);
//frame.add(label);
frame.add( new HelloComponent());
frame.setVisible(true);

}

}

package bookWork;
import java.awt.*;

import javax.swing.JComponent;

public class HelloComponent extends JComponent{ //ERROR! The serializable....
public void paintComponent( Graphics g){
g.drawString( "Hello, Java!", 125, 195);
}
}
1 person has
this problem
+1
Reply