How is setForeground method called without creating instance in java? - java

I was looking at an applet code and it struck me.
My Questions:
why is setForeground() used without an object here despite it being defined as a non-static method in the API
the code is as follows:
import java.applet.Applet;
import java.awt.*;
/*<applet code = "swings.class" height = "500" width = "500"></applet>*/
public class Swings extends Applet{
public void init(){
setBackground(Color.yellow);
setForeground(Color.red);
Font f = new Font("Comic Sans MS",Font.BOLD,25);
setFont(f);
}
public void paint(Graphics g){
g.drawString("Welcome to Applets",100,100);
}
}

setForeground is declared as public in Component, Swings is a subclass of Component,
which means setForeground will be inherited by Swings as its own class member, so you can call setForeground in Swings directly.
You can check jls for more details.
update
In java, if both non-static methods are in the same class, they can call each other directly, without creating a new instance.
Since setForeground is inherited by Swings, setForeground and init are both members of class Swings. So you can call setForeground in init directly.

Related

AWT: I am trying to learn Java and was unable to understand the following program

What is "new MyCanvas()" in f.add(new MyCanvas());
How did we get the oval even though the paint() method is not called either in CanvasExample class constructor or in the main() method
What is new CanvasExample() in the main() method
import java.awt.*;
public class CanvasExample {
public CanvasExample() {
Frame f = new Frame("Canvas Example");
f.add(new MyCanvas());
f.setLayout(null);
f.setSize(400, 400);
f.setVisible(true);
}
public static void main(String args[]) {
new CanvasExample();
}
}
class MyCanvas extends Canvas {
public MyCanvas() {
setBackground (Color.GRAY);
setSize(300, 200);
}
public void paint(Graphics g){
g.setColor(Color.red);
g.fillOval(75, 75, 150, 75);
}
}
Please explain
It's an instance of Canvas class. In Java new is a keyword used to create an object (an instance of given class). That being said - new Canvas() creates new instance of Canvas class. Brackets after class name indicate constructor - block of code that is being called when you wan to create an object of given type.
You got oval because the paint method was called. It just wasn't called explicitly from your code. As you can read in this tutorial article published by Oracle, the paint method will be always triggerred as so called "callback mechanism". This method belongs to Container class. I suggest reading docs about it. The paint method in MyCanvas class overrides the paint method from Canvas. When extending Canvas class and overriding paint method you should always call the super method at the beginning of your method. You can read why in the links I have already included in this point.
As in point #1 - new CanvasExample() creates new instance of MyCanvas class. More specifically, it calls constructor (public CanvasExample() { ... }). In code you presented, constructor of CanvasExample creates new object of type Frame and calls some of it's methods. One of these methods is add and it was inherited by class Frame from its the superclass - Container.As Java awt API explains, the add method:
appends the specified component to the end of this container.
I hope you will understand :D
at first it call public static void main(String args[])
then main make new instance of class CanvasExample and call its constructorCanvasExample()
that constructor make new instance of class Frame named "f" and call constructor of class Frame it set title of that frame to "Canvas Example"
in next row of constructorCanvasExample() it make and add new instance of class MyCanvas to instance of Frame named "f"third row of constructorCanvasExample() it just set Layout of "f" to nullfourth row of constructorCanvasExample() it set size of "f" to 400x400fifth row of constructorCanvasExample() it just show "f" to screen (so you can see it)
and end of constructorCanvasExample() it get back to mainwhen creating new instance of class MyCanvas is called constructor of it and that constructor set background of it to "Color.GRAY" and size of it to 300x200 and all of MyCanvas() constructor
everytime when "f" needs to be rendered again it call method paint(Graphics g) of instance of class MyCanvas bit that instance is smaller than "f" so you can see white behind
that white is background of "f"
I think thats all what you ask for.
have a nice day

Repainting a JPanel from a JCheckBox ActionListener in another Package

OK, I am going to try to explain this as best as I can. I am fairly proficient at Java but am unable to find a logical solution to this after extensive searching. Lets say that I have a JPanel class inside package A that will contain a graph that will be drawn.
package A
public class DrawGraph extends JPanel
{
public DrawGraph()
{
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
// other stuff
}
public void updateGraph()
{
repaint();
}
}
In a different class inside package B I have a JCheckBox that when selected should trigger a repaint of the graph in package A. This class does not initialize the DrawGraph class. That class is initialized elsewhere.
package B
public class CheckBoxClass extends JPanel
public CheckBoxClass
{
graphicsCheckBox.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent cb)
{
GUI_Data.graphics = true;
DrawGraph.updateGraph(); // Calls Update Graph function
}
});
}
Now how do I call the updateGraph function in my DrawGraph class without having to create a new instance of the DrawGraph class? I know that I cannot make the updateGraph method static since repaint() is not static. I feel like there has to be a way to do this without repainting via a timer or some other convoluted and inefficient method. Am I looking at this problem in the wrong way? Basically I need a way to trigger a repaint of the DrawGraph class from the JCheckBox class actionlistener. If this question isn't clear, please let me know so I can revise it. Thank you guys in advance, this is my first question but I have been using you guys for several years.
There seem to be a bit of confusion of concepts here, let me try to explain.
static vs. instance methods:
A class can have static and non static methods. non-static methods can be called only on an instance of the class. static can be called only on the class (although you can call them through a variable containing an instnace of the class).
method visibility: a method can be private, protected, package-protected or public. private methods can be called only from within the same class). protected can be called only from within the class or subclasses. package-protected (without any qualifier) can be called from classes within the same package. public can be called from anywhere.
In your case, the fact that the CheckBoxClass is not in the same package has nothing to do with the fact that you can't call DrawGraph.updateGraph(). updateGraph() is an instance method (non-static), hence you have to have an instance to call it. Now, if you know that there is going to be only one instance of DrawGraph in your program, then you can use the singleton pattern:
1) in the DrawGraph class have a static variable initialized to an instance of the class itself. Also have a static method that returns such instance:
public class DrawGraph {
private static DrawGraph singleton = new DrawGraph();
public static getInstance() {
return singleton;
}
}
Now you can do the following from CheckBoxClass:
#Override
public void actionPerformed(ActionEvent cb)
{
GUI_Data.graphics = true;
DrawGraph.getInstance().updateGraph(); // Calls Update Graph function
}

How do I set JFrame size from different class

I've got two classes. My QuizatMainClass class and a class called window. I'm trying to create a window from the Quizat class with a set size but it won't compile. I've set the parameter to (x and y) e.g (1080 and 720). But it does'nt like that. I'm new to Java and don't really understand why I can't do this. The way the IDE fixes it is with something about superclass stuff. If someone could explain what this means to me or a more simple way to do what I'm trying to run I'd appreciate it. Layman's terms please.
QuizatMainClass:
package Quizat;
public class QuizatMainClass extends Window{
public static void main(String[] args) {
Window QuizatHomeScreen = new Window(1080, 20);
}
}
Window Class:
package Quizat;
import javax.swing.JFrame;
public class Window{
public Window(int x, int y){
JFrame window = new JFrame();
window.setSize(x,y);
window.setLocationRelativeTo(null);
window.setResizable(false);
window.setVisible(true);
}
}
The explanation for your problem is that since QuizatMainClass extends the Window class, and Window has a specific parameter-using constructor, the QuizatMainClass will either need to create a constructor that specifically calls Window's super constructor with parameters, or else give Window a default no-arg constructor.
Having said that your real problem is that you're misusing inheritance. QuizatMainClass shouldn't extend the Window class, that's it.

Methods in built-in classes

I am kinda new to java. I was reading java codes to learn more about it, and this had me confused. A method would only be performed if only it is called, right? But how about those methods of built-in classes like paint(), paintComponent(), run() in Runnable class, etc. Are these methods performed without explicitly calling them, once a class that implements these methods is used to instantiate an object? Is that really how it works?
Like for example in this code, method paint() was not really called.
import javax.swing.*;
import java.awt.*;
public class FrameExampleTest{
public static void main(String args[]){
FrameExample frame = new FrameExample();
frame.setSize(500,500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class FrameExample extends JFrame{
PanelExample panel;
public FrameExample(){
Container c = getContentPane();
panel = new PanelExample();
c.add(panel,BorderLayout.CENTER);
}
}
class PanelExample extends JPanel{
public PanelExample(){
setSize(300,200);
}
public void paint(Graphics g){
g.fillArc(20,20,30,30,0,360);
}
}
You don't call paint or run yourself, but other code in the JVM does call it for you. For instance code inside the Thread class will call your run method. Code inside the event loop will call paint or paintComponent. Over time, you will see that there's nothing magical. Whenever a method is called, some other code calls it.
Yes. The window framework calls paint and paintComponent methods for you. It figures out when the paint/repaint is required (e.g. when window is moved, opened, re-opened, resized, etc). Javadoc to these methods sometimes mentions it isn't advised/not required to call them directly, but is required to implement them to do such and such things.

Do I need another method to use the ColorFactory class?

I just found this really great ColorFactory class that I am using in my first Swing project. It is really cool: I can now pass a named color from my main class, like "crimson" or "mediumaquamarine" for example, to the createContentPane Container method.
Code:
frame.setContentPane(ContentPaneCreator.createContentPane("darkorange"));`
Question:
Do I need the public final void setBackground(Color color, JPanel contentPane) method at all? Can everything be done inside createContentPane() method instead? Thank you for your help.
import java.awt.Color;
import java.awt.Container;
import javax.swing.JPanel;
public final class ContentPaneCreator extends JPanel {
private static final long serialVersionUID = 1L;
public static Container createContentPane(String color) {
JPanel contentPane = new JPanel();
// awesome txt to Color conversions using the ColorFactory().getColor();
// written by The Lobo Project
new ContentPaneCreator().setBackground(
new ColorFactory().getColor(color), contentPane);
contentPane.setOpaque(true);
return contentPane;
}
public final void setBackground(Color color, JPanel contentPane) {
contentPane.setBackground(color);
}
)
Several things may bear closer scrutiny:
As you plan to extend JPanel, supply a String colorName via the constructor and store the name in a field for later reference; the panel's backgroundColor is a bound property.
The static factory, ColorFactory.getInstance(), should be re-factored to use the initialization-on-demand holder idiom.
The code, excerpted from the Lobo Project, may have since been updated.
The names appear to be standard.
Answer to your question - I can't see why (or why you needed to start with, but hay).
Extended answer:
It should be: (if we're looking at the same piece of code)
ColorFactory.getInstance().getColor(colorName);
Other wise you creating the color map on each instantiation, which is just a waste.
I'm also not sure why you need to extend JPanel, but it's not my code :P

Categories