The problem with the initialization of Graphics g. The drawing does not start if I call the paint() method; He demands to transfer argument there. I create the Graphics g argument, it requires it to be initialized, with what and how incomprehensible.

What do you need to add to make paint() ?

 import java.awt.FlowLayout; import java.awt.Graphics; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class GrSw { react rt = new react(); JFrame fr = new JFrame(); JPanel pn= new JPanel(); JButton bt= new JButton("OK"); FlowLayout fl = new FlowLayout(); GrSw() { bt.addActionListener(rt); pn.add(bt); fr.add(pn); fr.setLayout(fl); fr.setSize(400,100); fr.setVisible(true); } void paint(Graphics g){ g.drawLine(100,100,400,400); } public static void main(String[] args) { GrSw add = new GrSw(); } } 
  • You can take Graphics from the component you're going to draw on using the getGraphics () method. - Max

2 answers 2

Here is the simplest example of drawing, you can draw anything on the component by overriding the paintXXXX () methods and adding Listeners

 class Painter extends JPanel implements MouseMotionListener { Graphics2D g2; int x, y; public Painter() { //добавляСм ΡΠ»ΡƒΡˆΠ°Ρ‚Π΅Π»ΡŒ addMouseMotionListener(this); } @Override protected void paintComponent(Graphics g) { g2 = (Graphics2D) g; g2.setColor(Color.black); //РисуСм ΠΊΡ€ΡƒΠ³ g2.drawOval(x, y, 10, 10); } @Override public void mouseDragged(MouseEvent e) { //ΠŸΡ€ΠΈΡΠ²Π°ΠΈΠ²Π°Π΅ΠΌ ΠΊΠΎΠΎΡ€Π΄ΠΈΠ½Π°Ρ‚Ρ‹ кусора x = e.getX(); y = e.getY(); //ΠŸΠ΅Ρ€Π΅Ρ€ΠΈΡΠΎΠ²Ρ‹Π²Π°Π΅ΠΌ содСрТимоС ΠΊΠΎΠΌΠΏΠΎΠ½Π΅Π½Ρ‚Ρ‹ repaint(); } @Override public void mouseMoved(MouseEvent e) { } } 

    Under the picture means a drawn line?

    Sketched a simple example of how to draw a line using java.awt.Graphics :

     import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.geom.Line2D; import javax.swing.JComponent; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; class DrawLines { public static void main(String[] args) { Runnable r = new Runnable() { public void run() { CustomLineComponent lineComponent = new CustomLineComponent(250,250); Line2D.Double line = new Line2D.Double(20, 20, 60, 85); lineComponent.setLine(line); JOptionPane.showMessageDialog(null, lineComponent); } }; SwingUtilities.invokeLater(r); } } class CustomLineComponent extends JComponent { Line2D.Double line; CustomLineComponent(int width, int height) { super(); setPreferredSize(new Dimension(width,height)); } public void setLine(Line2D.Double line) { this.line = line; repaint(); } public void paintComponent(Graphics g) { g.setColor(Color.white); g.fillRect(0, 0, getWidth(), getHeight()); getPreferredSize(); g.setColor(Color.black); g.drawLine( (int)line.getX1(), (int)line.getY1(), (int)line.getX2(), (int)line.getY2() ); } }