将绘制的内容从一个jcomponent传输到另一个



我有一个Java程序,它有两个文本区域和一个按钮。我想允许用户使用触摸笔或鼠标写一个一个文本区域,当他/她点击按钮时,绘制的内容应该发送到2号文本区域。

因此,在用户正在写的文本区域,我给出了一个带有paintComponent方法的mousemotion监听器。当我运行应用程序时,我已经意识到texarea方法getText()setText()不能设置或获取绘制的内容。

我有办法完成上述任务吗?我也尝试过JPanel,但它没有setContent()方法。

我感谢你的帮助。

这是我的第一个文本区域,用户在这里用触摸笔写字。

public class Area1 extends JTextArea {
    int pointcount = 0;
    Point[] points = new Point[10000];
    public Area1() {
        addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseDragged(MouseEvent event) {
                if (pointcount < points.length) {
                    points[pointcount] = event.getPoint();
                    ++pointcount;
                    repaint();
                }
            }
        });
    }
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        for (int i = 0; i < pointcount; i++) {
            g.fillOval(points[i].x, points[i].y, 4, 4);
        }
    }
}

这是我的整个应用程序,带有文本区域2按钮

public class Handwriting extends JFrame {
    private JTextArea area2;
    private JButton b1;
    Area1 area1;
    public Handwriting() {
        Box box = Box.createHorizontalBox();
        area1 = new Area1();
        area1.setRows(30);
        area1.setColumns(30);
        area2 = new JTextArea(30, 30);
        b1 = new JButton("Copy");
        b1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                if (event.getSource() == b1) {
                    area2.setText(area1.getText());
                }
            }
        });
        box.add(area1);
        box.add(b1);
        box.add(area2);
        add(box);
    }
    public static void main(String[] args) {
        Handwriting hand = new Handwriting();
        hand.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        hand.setSize(500, 500);
        hand.setVisible(true);
    }
}

一种可能的解决方案是将一个类作为另一个类的内部类,这样即使是私有实例字段也可以访问

最新更新