Jak zapisać narysowane obiekty w Javie?

0

Witam, mam problem, otóż miałem stworzyć prosty edytor graficzny, w którym mogę mieć możliwość wyboru narzędzi, kolorów, linii, itd. Wszystko jakoś chodzi (no może z wyjątkiem trójkąta), ale za Chiny nie wiem jak zrobić tak, żeby każda z figur nie usuwała się po narysowaniu nowej figury. Czy mógłby mi ktoś edytować kod, albo chociaż wytłumaczyć jak to zrobić? W załączniku paczka z projektem.

 * NewJFrame.java
 *
 * Created on 19 listopad 2013, 11:51
 */

package javaapplication23;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.Line2D;
import javax.swing.JPanel;

import java.awt.*;



public class NewJFrame extends javax.swing.JFrame {
 public int x,y,n;
public int x2, y2;
int funkcja=0;
int wypel=0;
int linia=0;
int tab3[]= new int[10];
int tab4[]= new int[10];


    private Object JLabel2;
     int kolor;
  
    public class rysuj extends JPanel
    {
        private boolean jToggleButton1ActionPerformed;
      
         
        
        @Override
      
        protected void paintComponent(Graphics g)
        {
           
            super.paintComponent(g);
         Graphics2D g2d = (Graphics2D)g;
            Polygon poly = new Polygon();
            if(kolor==1)g.setColor(Color.red);
            if(kolor==2)g.setColor(Color.yellow);
            if(kolor==3)g.setColor(Color.green);
            if(kolor==4)g.setColor(Color.blue);
         if(kolor==5)g.setColor(Color.PINK);
         if(kolor==6)g.setColor(Color.black);
            if(funkcja==6){
            g2d.setStroke(new BasicStroke(5f,
                              BasicStroke.CAP_ROUND,
                              BasicStroke.JOIN_MITER,
                              5f,
                              new float[]{1f, 15f},
                              10f
                              )); 
              g.drawLine(x,y,x2,y2);}
         
            if(funkcja==5){ g2d.setStroke(new BasicStroke(5f,
                              BasicStroke.CAP_ROUND,
                              BasicStroke.JOIN_MITER,
                              5f,
                              new float[]{10f, 15f},
                              10f
                              ));
              g.drawLine(x,y,x2,y2);}
         
        
            
             if(funkcja==1) {g.drawLine(x,y,x2,y2);}
         
            if(funkcja==2) g.drawRect(x,y,x2-x,y2-y);
            if(funkcja==3) g.drawOval(x,y,x2-x,y2-y);
            if(funkcja==7) {
             poly.addPoint(x, y);
        poly.addPoint(x2, y2);
        poly.addPoint(x,(x2+y2)/2);
                poly.addPoint(y,(x2+y2)/2);
        g.drawPolygon(poly);}
           if(funkcja==4) {
              
            
        poly.addPoint(x, y);
        poly.addPoint(x2, y2);
        poly.addPoint(x,(x2+y2)/2);
        g.drawPolygon(poly);
 
           
  
 {  
     
 

                 }  

           }
            
        
        } 
    }
    public NewJFrame() {
        
        initComponents();
        rysuj q= new rysuj();
        this.add(q);
        q.setSize(10000,10000);
         
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jButton5 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jButton7 = new javax.swing.JButton();
        jButton8 = new javax.swing.JButton();
        jButton9 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jButton10 = new javax.swing.JButton();
        jButton11 = new javax.swing.JButton();
        jButton12 = new javax.swing.JButton();
        jButton13 = new javax.swing.JButton();

        jLabel1.setText("jLabel1");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(1000, 980));
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                formMousePressed(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                formMouseReleased(evt);
            }
        });
        addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                formMouseMoved(evt);
            }
        });

        jButton2.setIcon(new javax.swing.ImageIcon("C:\\Users\\pc\\Desktop\\ikonki\\linia.png")); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setIcon(new javax.swing.ImageIcon("C:\\Users\\pc\\Desktop\\ikonki\\prostokont.png")); // NOI18N
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setIcon(new javax.swing.ImageIcon("C:\\Users\\pc\\Desktop\\ikonki\\elipsa.png")); // NOI18N
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jLabel2.setText("jLabel2");

        jLabel3.setText("jLabel3");

        jButton5.setBackground(new java.awt.Color(255, 51, 51));
        jButton5.setForeground(new java.awt.Color(255, 153, 51));
        jButton5.setText("jButton5");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        jButton6.setBackground(new java.awt.Color(255, 255, 0));
        jButton6.setText("jButton6");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });

        jButton7.setBackground(new java.awt.Color(102, 255, 0));
        jButton7.setText("jButton7");
        jButton7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton7ActionPerformed(evt);
            }
        });

        jButton8.setIcon(new javax.swing.ImageIcon("C:\\Users\\pc\\Desktop\\ikonki\\przerywana.png")); // NOI18N
        jButton8.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton8ActionPerformed(evt);
            }
        });

        jButton9.setIcon(new javax.swing.ImageIcon("C:\\Users\\pc\\Desktop\\ikonki\\kropki.png")); // NOI18N
        jButton9.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton9ActionPerformed(evt);
            }
        });

        jButton1.setBackground(new java.awt.Color(0, 102, 255));
        jButton1.setText("jButton1");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton10.setBackground(new java.awt.Color(255, 204, 204));
        jButton10.setText("jButton1");
        jButton10.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton10ActionPerformed(evt);
            }
        });

        jButton11.setBackground(new java.awt.Color(0, 0, 0));
        jButton11.setText("jButton1");
        jButton11.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton11ActionPerformed(evt);
            }
        });

        jButton12.setText("jButton12");
        jButton12.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton12ActionPerformed(evt);
            }
        });

        jButton13.setText("jButton13");
        jButton13.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton13ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(40, 40, 40)
                        .addComponent(jLabel3)
                        .addGap(34, 34, 34))
                    .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton4)
                        .addGap(53, 53, 53)
                        .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(14, 14, 14)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton10, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton11, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(56, 56, 56))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(373, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jButton8, javax.swing.GroupLayout.Alignment.LEADING, 0, 0, Short.MAX_VALUE)
                            .addComponent(jButton9, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 26, Short.MAX_VALUE))
                        .addContainerGap())))
            .addGroup(layout.createSequentialGroup()
                .addComponent(jButton12)
                .addContainerGap(331, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addComponent(jButton13)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jButton4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton12)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton13)
                .addGap(44, 44, 44)
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton8)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton9)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 39, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3))
                .addGap(21, 21, 21))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton5)
                    .addComponent(jButton6)
                    .addComponent(jButton1)
                    .addComponent(jButton7)
                    .addComponent(jButton10)
                    .addComponent(jButton11))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>                        

    private void formMousePressed(java.awt.event.MouseEvent evt) {                                  
  x=evt.getX()-8;
y=evt.getY()-30;


    }                                 

    private void formMouseReleased(java.awt.event.MouseEvent evt) {                                   
       x2=evt.getX()-8;
y2=evt.getY()-30;
this.repaint();

    }                                  

    private void formMouseMoved(java.awt.event.MouseEvent evt) {                                
      jLabel2.setText("x:"+String.valueOf(evt.getX()));
        jLabel3.setText("y:"+String.valueOf(evt.getY()));
    }                               

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        funkcja= 1;
    }                                        

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
       funkcja=2;
    }                                        

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        kolor=1;
    }                                        

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {                                         
kolor=2;        // TODO add your handling code here:
    }                                        

    private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {                                         
kolor=3;        // TODO add your handling code here:
    }                                        

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
       funkcja=3;
    }                                        

    private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {                                         
funkcja=6;        // TODO add your handling code here:
    }                                        

    private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {                                         
funkcja=5;        // TODO add your handling code here:
    }                                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
kolor=4;        // TODO add your handling code here:
    }                                        

    private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {                                          
kolor=5;        // TODO add your handling code here:
    }                                         

    private void jButton11ActionPerformed(java.awt.event.ActionEvent evt) {                                          
kolor=6;        // TODO add your handling code here:
    }                                         

    private void jButton12ActionPerformed(java.awt.event.ActionEvent evt) {                                          
funkcja=4;        // TODO add your handling code here:
    }                                         

    private void jButton13ActionPerformed(java.awt.event.ActionEvent evt) {                                          
funkcja=7;        // TODO add your handling code here:
    }                                         
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton10;
    private javax.swing.JButton jButton11;
    private javax.swing.JButton jButton12;
    private javax.swing.JButton jButton13;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JButton jButton7;
    private javax.swing.JButton jButton8;
    private javax.swing.JButton jButton9;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    // End of variables declaration                   
    
}
0

Stwórz kolekcję rysowanych przez użytkownika obiektów i w metodzie paintComponent rysuj wszystkie te obiekty w pętli.
Btw. co to jest "prostokont"?

0

Ten "prostokont" to po prostu wynik tego, że miałem już "prostokąt.png" ale był za duży więc po prostu zamiast zmniejszać go czy tam bawić się w podmiany nazwy po prostu dla żartu dałem właśnie taką nazwę.

Wracając do Twojej odpowiedzi - nasz nauczyciel powiedział nam coś podobnego, żeby stworzyć tablicę obiektów czy coś takiego. Mógłbyś mi trochę bardziej przybliżyć jak to zrobić?

0

Stwórz w klasie pole typu ArrayList<Shape> np. o nazwie figury. W metodzie formMouseReleased dodawaj do kolekcji figury nowy obiekt (zależny od wartości zmiennej funkcja.

public void paintComponent(Graphics g)
{
     super.paintComponent(g);
     Graphics2D g2 = (Graphics2D)g;
     for(int i=0;i<figury.size())
     {
         g2.draw(figury.get(i));
     }
}

Klasa Shape nie ma chyba informacji o kolorze. Stwórz nową klasę

class ColoredShape extends Shape
{
     private Color kolor;
     ...
}

i zapamiętuj w tym nowym polu kolor. Trochę się zmieni funkcja rysująca

public void paintComponent(Graphics g)
{
     super.paintComponent(g);
     Graphics2D g2 = (Graphics2D)g;
     for(int i=0;i<figury.size())
     {
         ColoredShape figura = figury.get(i); 
         g2.setColor(figura.getColor());
         g2.draw(figura);
     }
}
0

Dzięki za odpowiedź. Zrobiłem to co kazałeś, lecz nadal bez efektu. Bardzo doceniłbym, gdybyś mógł ściągnąć ten załącznik i zrobić ekspertyzę profesjonalnym okiem :D

1

Nie zrobiłeś tego co "kazałem", nawet 5% nie zrobiłeś. :P
Trochę zmieniłem koncepcje (zapomniałem, że Shape jest interfejsem). Nie obsługuję też wielokątów, bo nie rozumiem Twojej koncepcji.
Edit, Zmieniłem też typ zmiennej kolor na Color. Jest to bardziej logiczne, można też łatwo zmienić program tak, by użytkownik - korzystając z klasy JColorChooser - mógł wybrać dowolny kolor.
Klasa ColoredShape

import java.awt.*;

public class ColoredShape
{
    private Color color;
    private Shape shape;
    private Stroke stroke = null;
    public ColoredShape(Shape shape,Color color,Stroke stroke)
    {
        this.shape = shape;
        this.color = color;
        this.stroke = stroke;
    }
    public Color getColor()
    {
        return color;
    }
    public Shape getShape()
    {
        return shape;
    }
    public Stroke getStroke()
    {
        return stroke;
    }
}

Klasa NewJFrame

//pola
    private ArrayList<ColoredShape> fig
//metoda paintComponent
        protected void paintComponent(Graphics g)
        {           
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D)g;
            for(int i=0;i<figury.size();i++)
            {
                ColoredShape figura = figury.get(i); 
                g2d.setColor(figura.getColor());
                g2d.setStroke(figura.getStroke());       
                g2d.draw(figura.getShape());
            }
       }
//metoda formMouseReleased
    private void formMouseReleased(java.awt.event.MouseEvent evt) 
    {        
        x2 = evt.getX()-8;
        y2 = evt.getY()-30;
        Shape shape = null;
        Stroke stroke = new BasicStroke();
        switch(funkcja)
        {
            case 6:
                shape = new Line2D.Double(x,y,x2,y2);
                stroke = new BasicStroke(5f,BasicStroke.CAP_ROUND,BasicStroke.JOIN_MITER,
                         5f,new float[]{1f, 15f},10f); 
             
                break;
            case 5:
                shape = new Line2D.Double(x,y,x2,y2);
                stroke = new BasicStroke(5f,BasicStroke.CAP_ROUND,BasicStroke.JOIN_MITER,
                         5f,new float[]{10f, 15f},10f);         
                break;
            case 1:
                shape = new Line2D.Double(x,y,x2,y2);
                break;
            case 2:
                shape = new Rectangle2D.Double(x,y,x2-x,y2-y);
                break;                
            case 3:
                shape = new Ellipse2D.Double(x,y,x2-x,y2-y);
                break;             
        }
        ColoredShape coloredShape = new ColoredShape(shape,kolor,stroke);
        figury.add(coloredShape);         
        this.repaint();
    }
0

Dzięki Ci bardzo! Nawet nie wiesz jak bardzo mi pomogłeś. Dzięki Tobie zrozumiałem o co w tym wszystkim chodzi. Duże piwo dla Ciebie, przyjacielu.

Jeszcze męczę się z narysowaniem trójkąta... próbowałem połączyć jakoś 3 linie ale to przerasta moje możliwości.

1 użytkowników online, w tym zalogowanych: 0, gości: 1