After introduction/strengthen lessons, now is the time to learn something related with a graphical interface. It is an interesting variety compared with what we had so far during studies.
Lesson 3
After introduction/strengthen lessons, now is the time to learn something related with a graphical interface. It is an interesting variety compared with what we had so far during studies.
import javax.swing.*;
public class Main {
public static void main(String[] args) {
JFrame window = new JFrame();
window.setSize(1024, 768);
window.setTitle("Hello, world!");
window.setVisible(true);
}
}
Move the code from the main method to a constructor of new class that extends JFrame.
Code is more origanized this way.
Currently our window has a skype syndrome. If we will close it, it will not exit the program.
If you want to exit the program after closing a window, you need to add the following instruction to the view (window) class.
// If I close a window, I exit the program
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Write paint method in a class which extends JFrame.
Add a blue circle in a created window.
class A extends JFrame {
A() {
//...
}
public void paint(Graphics g) {
// We are setting RGB color for drawing
g.setColor(new Color(255, 1, 100));
// At the point (512, 512) we are drawing an ellipse with dimension 40x40
// Notice: (0,0) point is located in top left corner of a window
g.drawOval(512, 512, 40, 40);
}
}
Methods getWidth(), getHeight() are used to get current dimension of a window.
Calculate (x,y) for the ellipse so it is always drawn in the center of a window.
Caution: consider, that you need (x,y) for top-left corner of a rectangle in which the ellipse is inscribed in.
Run the program from the previous task and start resizing a window.
Fix the bug seen in the previous task (you have to use Oracle Java to see the problem).
You can do this by calling paint method from the extended class before drawing an ellipse.
You can also use clearRect method on a Graphics object.
Add new integer fields: x, y, radius to your window class.
Let paint method draw a circle in (x, y) with a radius radius.
Create an additional thread which will change values for those attributes.
Prepare a list of elements to draw. The elements should implement an interface like this:
interface Renderable {
void render(Graphics g);
}
Create classess: circle, triangle and rectangle. Each class constructor should assign properies of each shape (color, position etc.).
Using loop add 20 shapes to the list of elements to draw.
Make the frame painting those elements.
Make every shape possible to save to a file.
Main window should save all shapes from a list to file. It should be done outside the paint method (we don't want to write to file with every paint, because it is not efficient).
Create a new window. It should display the same picture like the previous one, but reading shapes from a file.