I found this code online and it works for my application. I'm trying to trace through and understand it more thoroughly. I don't find any documentation that explains the use of the "add(new Surface());" statement. I understand what it does, but here is what I don't understand:
(Sample code below)
package testMainMethod;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
class Surface extends JPanel {
private void doDrawing(Graphics g, int x) {
double xd = (double) x;
Graphics2D g2d = (Graphics2D) g;
// Code to draw line image goes here
}
@Override
public void paintComponent(Graphics g) {
for (int i = 0; i < 512; i++) {
// super.paintComponent(g); // this erases each line
doDrawing(g, i);
}
}
}
public class SampleAddMethod extends JFrame {
public SampleAddMethod() {
initUI();
}
private void initUI() {
setTitle("Lines");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new Surface());
setSize(650, 350);
setLocationRelativeTo(null);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
SampleAddMethod lines = new SampleAddMethod();
lines.setVisible(true);
}
});
}
}
Why does "super.add(new Surface()); work, but ""SampleAddMethod.add(new Surface());" fail?
Because add(Component)
is an instance method on Container
, basically - and SampleAddMethod
is a subclass of Container
, indirectly. So the add
call in initUI
is implicitly this.add(new Surface())
. You can't call it as SampleAddMethod.add
because that would only work if it were a static method.
Am I correct that (new Surface()) creates an "anonymous class"?
No. It's just calling a constructor. The code is equivalent to:
Surface surface = new Surface();
add(surface);
The only anonymous type in the code you've shown us is in main
, where it creates a new anonymous class implementing Runnable
.
See more on this question at Stackoverflow