如何在java中使用按钮控制画布?

xa9qqrwz  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(332)

我被要求用课本上的代码做作业。如何将数据从帧转换到画布?例如,

public class test extends Frame {
   public static void main(String[] args) {new DefPoly();}
   int position = -1;
   test() {
      xxxxx
      });

      setSize(500, 300);
      Button button1 = new Button("lower end points");
      Button button2 = new Button("upper end points");

      button1.setBounds(20, 30,100,20);
      button2.setBounds(20, 60,100,20);

      add(button1);
      add(button2);

      add("Center", new Cvtest());
      setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
      setVisible(true);
   }
}

class CvTest extends Canvas {
   CvTest(){
      xxxxxxx
   }
   int position=1;
   int x1, y1, x2, y2;
   public void paint(Graphics g) {
      g.drawLine(position*x1, y1, x2, y2);
   }
}

代码只是一个例子,我想用 position . 因此我补充说 actionListener 在帧中,但未能更改 position . 我需要看更多关于mcv的内容吗?

jhkqcmku

jhkqcmku1#

在cvtest类中添加一个方法:public setposition(int position),然后在actionlistener中调用此方法来更改所有代码的位置,如下所示:

import java.awt.*;
import java.awt.Canvas;
import java.awt.Cursor;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Test extends Frame {
    int position = -1;
    CvTest cvTest;

    public Test(){
        setSize(500, 300);
        cvTest = new CvTest();

        Button button1 = new Button("lower end points");
        Button button2 = new Button("upper end points");

        button1.setBounds(20, 30,100,20);
        button2.setBounds(20, 60,100,20);

        button1.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent arg0) {
                // here can change position
                cvTest.setPosition(position);
            }

        });

        add(button1);
        add(button2);

        add("Center", cvTest);
        setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
        setVisible(true);
    }

   public static void main(String[] args) {
         new Test();
   }
}

class CvTest extends Canvas {
   int position=1;
   int x1, y1, x2, y2;

   CvTest(){

   }

   public void setPosition(int position){
       this.position = position;
   }

   public void paint(Graphics g) {
      g.drawLine(position*x1, y1, x2, y2);
   }
}

相关问题