网络白板优化:设配器模式增加发送文字了

在前篇文章Java项目网络白板实战-完整设计、实现到效果演示 实现了初步功能,有许多完善的地方,本文内容补充一些内容

  • 图形颜色设置
  • 增加发送文字功能

效果图

网络白板优化:设配器模式增加发送文字了

图形颜色设置

颜色选择器使用,通用图形类增加 Color 字段

JColorChooser.showDialog(ClientPanel.this,"选择图形颜色",Color.black);
public abstract class AbstractShape implements Serializable {

    protected  Point start;

    protected Point end;

    protected Color color;


    public AbstractShape(Point start, Point end,Color color) {
        this.start = start;
        this.end = end;
        this.color = color;
 
    }

    public abstract void paint(Graphics g);

}

设配器模式

图形与文字两者一定程度上存在差异,可以通过适配器模式进行转换,也可以简单加上冗余字段

网络白板优化:设配器模式增加发送文字了

如果用设配器模式 Shape ,线、圆、矩形等图形接口;

Text 发送文字类,TextAdapter 设配器类,此处有点为了设计模式而设计模式

public interface Shape {
     void paint(Graphics g);
}
public class Text {

    private Point start;
    private Color color;
    private String text;

    public void drawText(Graphics g){
        if(color!=null){
            g.setColor(color);
        }
        g.drawString(text,start.getX(),start.getY());
    }


}

public class TextAdapter extends Text implements Shape{

    @Override
    public void paint(Graphics g) {
        super.drawText(g);
    }
}

发送文字实现

swing 输入文字需要用到 JTextField ,主要流程

当选择图形为“文字”时,

  • 按下鼠标,JTextField 设置位置为鼠标位置、设置可见、请求焦点
  • 输入需要发送的内容
  • 按回车确定

JTextField添加 KeyListener,捕获到回车、则确定图形,隐藏自身。

         if(e.getKeyChar() == '\n'){
                    ClientPanel.this.addShape(xxx);
                    textField.requestFocus(false);
                    textField.setVisible(false);
                }

讲完,下期打算完成 撤销功能,盲猜备忘录模式可以用。