confused with java graphics paint

前端 未结 3 1671
春和景丽
春和景丽 2021-01-25 22:15

i am very bigginer to java .i trying to draw a line in a jpanel (using netbean ide)..i read some articles .but problem is it draw thais line without calling it .i want to draw l

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-25 23:15

    Problem: You have no event code in your button event handler.

    1. Try creating a state variable called boolean showLine before your constructor.
    2. Initialize it to false in constructor.
    3. Modify state variable on button click.

      private void jButton1ActionPerformed(
                      java.awt.event.ActionEvent evt) {                                         
      Graphics gg = null;
      // TODO add your handling code here:
      showLine = (true) ? false : true;
      

      }

    4. Add condition checking to paint method.

      @Override public void paint(Graphics g) { Graphics2D ga = (Graphics2D)g;

      if (showLine) {
          ga.setPaint(Color.red);
          ga.drawLine(200,100,200,300);
      }
      

      }

提交回复
热议问题