Adapters:
Programming empty code for methods that cater for events we are not interested in is tedious, and a better solution is available in Java. The solution involves what are known as adapter classes. These are classes that are analogues of the interfaces, which implement the methods asked for by the interfaces by means of providing the empty code bodies. They allow the programmer who wants to react to a small number of events to inherit from these adapter classes. An example of an adapter class is MouseAdapter. This class provides empty bodies for the five methods detailed above.
We use adapters in the same way as listeners by defining inner classes, except now we extend rather than implement. This is because adapters are classes (albeit somewhat empty classes) rather than interfaces, unlike listeners. So the above code for class MouseFrame can be rewritten as:
import java.awt. *;
import java.awt.event. *;
import javax.swing. *;
public class NewMouser extends JFrame
{
private JLabel yCoordLabel;
private JLabel xCoordLabel;
private JPanel c;
public NewMouser (String title)
{
super(title);
setSize(300, 300);
yCoordLabel = new JLabel("");
xCoordLabel = new JLabel("");
c = new JPanel( );
c.setBackground(Color.yellow);
getContentPane( ).setLayout(new GridLayout(3, 1));
getContentPane( ).add(yCoordLabel);
getContentPane( ).add(xCoordLabel);
getContentPane( ).add(c);
c.addMouseListener(new MouseEventer( ));
}
// inner class
private class MouseEventer extends MouseAdapter
{
public void mouseClicked (MouseEvent e)
{
int xCoordinate = e.getX( );
int yCoordinate = e.getY( );
yCoordLabel.setText(yCoordinate + "");
xCoordLabel.setText(xCoordinate + "");
}
} // end of inner class
}
The inner class MouseEventer extends MouseAdapter. An instance of MouseEventer is created and registered as a listener within the constructor of the class NewMouser.
Java Assignment Help - Java Homework Help
Struggling with java programming language? Are you not finding solution for your Adapters homework and assignments? Live Adapters experts are working for students by solving their doubts & questions during their course studies and training program. We at Expertsmind.com offer Adapters homework help, java assignment help and Adapters projects help anytime from anywhere for 24x7 hours. Computer science programming assignments help making life easy for students.
Why Expertsmind for assignment help
- Higher degree holder and experienced experts network
- Punctuality and responsibility of work
- Quality solution with 100% plagiarism free answers
- Time on Delivery
- Privacy of information and details
- Excellence in solving java programming language queries in excels and word format.
- Best tutoring assistance 24x7 hours