Good day, hashkodovtsy! I don’t even know how to start the question, in general, the code with Java Graphics does not work for me. As I didn’t twist it, I don’t want to paint anything. I found several code examples in the net, everything looked something like this. Maximum simplified code:
import java.awt. *;
import javax.swing.JFrame;
public class Main {
public static void main (String [] args) {
JFrame frame = new JFrame ("Test");
frame.setBounds (0, 0,400,500);
frame.setVisible (true);
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}
public void paint (Graphics g) {
g = (Graphics2D) g;
g.setColor (Color.BLACK);
g.drawLine (20, 20, 360, 20);
}
}
Answer 1, authority 100%
You’d better understand how Swing
works first, there are tons of articles on this topic on the Internet. but this particular example should be rewritten like this:
import java.awt. *;
import javax.swing. *;
public class Main {
public static void main (String [] args) {
JFrame frame = new JFrame ("Test");
frame.setBounds (0, 0,400,500);
frame.setVisible (true);
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel () {
Graphics2D g2;
protected void paintComponent (Graphics g) {
super.paintComponent (g);
g2 = (Graphics2D) g;
g2.setColor (Color.BLACK);
g2.drawLine (20, 20, 360, 20);
}
};
frame.setContentPane (contentPane);
}
}
Answer 2, authority 100%
Easier this way
package jAp;
import java.awt.Graphics;
import javax.swing.JFrame;
public class Ap {
public static void main (String [] args) {
new JFrame () {
{
setBounds (0, 0,400,500);
setVisible (true);
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
}
public void paint (Graphics g) {super.paint (g); g.drawLine (20,20,200,200); }
};
}
}