Нажмите и перетащите компоненты электроники рисования в Java Swing - PullRequest
0 голосов
/ 09 мая 2018

Я пытаюсь создать своего рода OrCad в Java, и до сих пор я решил использовать линии с разными цветами для представления каждого компонента. Я тестировал свой код, рисуя линии, и он работал (щелкал и перетаскивал, а затем перерисовывал при рисовании новой линии), но я не знаю, почему он больше не работает сейчас, когда я пытаюсь нарисовать свои компоненты вместо простого Line2D.

У меня есть компоненты класса и несколько базовых производных компонентов, и у каждого есть поле Line2D и поле цвета. Рисование выполняется с помощью всплывающего меню (пользователь щелкает правой кнопкой мыши, чтобы выбрать компонент), а затем, когда они начинают щелкать и перетаскивать объект компонента, создается и добавляется в массив, который всегда перерисовывается.

Это основной класс:

public class Main {
private static String checked;


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

private static void createAndShowGUI()
{
    DrawingArea drawingArea = new DrawingArea();
    PopUpMenu popup = new PopUpMenu();
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    frame.getContentPane().add(drawingArea);
    frame.getContentPane().add(popup);
    frame.setSize(900, 500);
    frame.setLocationRelativeTo( null );
    frame.setVisible(true);
}

static class PopUpMenu extends JPanel {

    public PopUpMenu()
    {
        setBackground(Color.BLACK);
        JPopupMenu pmenu = new JPopupMenu();
        JMenuItem resistance = new JMenuItem("Add Resitance");
        JMenuItem wire = new JMenuItem("Add Wire");
        JMenuItem capacitor = new JMenuItem("Add Capacitor");
        JMenuItem source = new JMenuItem("Add Source");

        pmenu.add(resistance);
        pmenu.add(wire);
        pmenu.add(capacitor);
        pmenu.add(source);

        resistance.addActionListener( new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {

                checked = "R";

            }

        });

        wire.addActionListener( new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {

                checked = "W";

            }

        });

        capacitor.addActionListener( new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {

                checked = "C";

            }

        });

        source.addActionListener( new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {

                checked = "S";

            }

        });

        addMouseListener( new MouseAdapter() {
              public void mouseReleased(MouseEvent e) {
                  if(e.getButton() == MouseEvent.BUTTON3)
                  {
                      pmenu.show(e.getComponent(),e.getX(),e.getY());
                  }
               }

        });

    }

}

static class DrawingArea extends JPanel
{

    private ArrayList<Component> lines = new ArrayList<Component>();
    private Component shape;

    public DrawingArea()
    {
        setBackground(Color.BLACK);

        MyMouseListener ml = new MyMouseListener();
        addMouseListener(ml);
        addMouseMotionListener(ml);
    }


protected void paintComponent(Graphics g)
{
    super.paintComponent(g);


    Graphics2D g2d = (Graphics2D) g;
    //g2d.setColor( Color.RED );
     g2d.setStroke(new BasicStroke(3,  BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL));


    for (Component aux : lines)
    {
        g2d.setColor(aux.getCul());
        g2d.drawLine((int)aux.getLine().getX1(), (int)aux.getLine().getY1(), (int)aux.getLine().getX2(), (int)aux.getLine().getY2());
    }


    if (shape != null)
    {
        g2d.draw( shape.getLine() );
    }
}


class MyMouseListener extends MouseInputAdapter
{
    private Point startPoint;
    private Point endPoint;

    public void mousePressed(MouseEvent e)
    {
        startPoint = e.getPoint();
        switch(checked)
        {
        case "W": shape = new Wire();
                break;
        case "R": shape = new Resistance();
                break;
        case "C": shape = new Capacitor();
                break;
        case "S": shape = new Source();
                break;
        }
        lines.add(shape);
    }
    public Line2D el = null;

    public void mouseDragged(MouseEvent e)
    {
        endPoint = e.getPoint();

        el.setLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y);
        shape.setLine(el);
        repaint();
    }

     public void mouseReleased(MouseEvent e) {
       endPoint = e.getPoint();
       el.setLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y);
        shape.setLine(el);
       repaint();
        }
}
}

}

И это мои компоненты (я добавил только один производный класс).

public class Component {
protected double value;
protected Line2D line;
protected int ID;
protected Color cul;
protected String type;

public Component()
{

}


public String getType() {
    return type;
}



public Line2D getLine() {
    return line;
}

public void setLine(Line2D line) {
    this.line = line;
}

public int getID() {
    return ID;
}

public void setID(int iD) {
    ID = iD;
}

public Color getCul() {
    return cul;
}

public int returnX1() {
    return (int)line.getP1().getX();
}

public int returnY1() {
    return (int)line.getP1().getY();
}

public int returnX2() {
    return (int)line.getP2().getX();
}

public int returnY2() {
    return (int)line.getP2().getY();
}

}

Открытый класс Capacitor расширяет Компонент {

private double value;
private Line2D line;
private int ID;
private Color cul = Color.ORANGE;
private String type = "C";

public Capacitor(){
    super();
}

@Override
public String getType() {
    // TODO Auto-generated method stub
    return type;
}

@Override
public Line2D getLine() {
    // TODO Auto-generated method stub
    return super.getLine();
}
@Override
public void setLine(Line2D line) {
    // TODO Auto-generated method stub
    super.setLine(line);
}
@Override
public int getID() {
    // TODO Auto-generated method stub
    return super.getID();
}
@Override
public void setID(int iD) {
    // TODO Auto-generated method stub
    super.setID(iD);
}
@Override
public Color getCul() {
    // TODO Auto-generated method stub
    return cul;
}
@Override
public int returnX1() {
    // TODO Auto-generated method stub
    return super.returnX1();
}
@Override
public int returnY1() {
    // TODO Auto-generated method stub
    return super.returnY1();
}
@Override
public int returnX2() {
    // TODO Auto-generated method stub
    return super.returnX2();
}
@Override
public int returnY2() {
    // TODO Auto-generated method stub
    return super.returnY2();
}
}

Я чувствую, что это как-то связано с тем, как я копирую строку в мышах, перетаскиваемых и освобождающих методы.

...