/* * Kaur Männiko * Graafika redaktor. * Graafika ja muusika programmeerimine */ import javax.swing.*; import javax.swing.event.MouseInputAdapter; import java.awt.*; import java.awt.event.*; import java.awt.image.*; import java.awt.geom.*; import java.io.*; import java.util.*; import com.sun.image.codec.jpeg.*; public class KObjectDraw extends JPanel implements MouseListener, ActionListener, ItemListener { private Dimension area; //indicates area taken up by graphics private Vector shapes; //coordinates used to draw graphics private JPanel drawingPane; private final Color colors[] = { Color.BLACK, Color.WHITE, Color.BLUE, Color.CYAN, Color.DARK_GRAY, Color.GRAY, Color.GREEN, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE, Color.PINK, Color.RED, Color.YELLOW }; private final int color_n = colors.length; public static final int TOOL_SELECT = 0; public static final int TOOL_RECT = 1; public static final int TOOL_OVAL = 2; private int selectedTool = TOOL_RECT; private Color selectedColor = Color.BLACK; private DrawingObject selectedObject = null; JLabel label1, label2; //Object handles: Rectangle ctrl1 = new Rectangle(0, 0, 8, 8); Rectangle ctrl2 = new Rectangle(0, 0, 8, 8); Rectangle ctrl3 = new Rectangle(0, 0, 8, 8); Rectangle ctrl4 = new Rectangle(0, 0, 8, 8); public KObjectDraw() { super(new BorderLayout()); area = new Dimension(0,0); shapes = new Vector(); //Set up the instructions. label1 = new JLabel( "Objekte: "); label2 = new JLabel("0"); JPanel instructionPanel = new JPanel(new GridLayout(1,0)); instructionPanel.add(label1); instructionPanel.add(label2); //Set up the drawing area. drawingPane = new DrawingPane(); drawingPane.setBackground(Color.white); drawingPane.addMouseListener(this); //Put the drawing area in a scroll pane. JScrollPane scroller = new JScrollPane(drawingPane); scroller.setPreferredSize(new Dimension(200,200)); //Lay out this demo. add(instructionPanel, BorderLayout.PAGE_START); add(scroller, BorderLayout.CENTER); //Color bar JToolBar colorbar = new JToolBar(); ColorButton colBtn = null; for (int i = 0; i < colors.length; i++) { colBtn = new ColorButton(colors[i]); colBtn.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { selectedColor = ((ColorButton)e.getSource()).color; if (selectedObject != null) selectedObject.color = selectedColor; drawingPane.repaint(); } } ); colorbar.add(colBtn); } add(colorbar, BorderLayout.SOUTH); } /** The component inside the scroll pane. */ public class DrawingPane extends JPanel { /* private drawHandle(Graphicsdouble x, double y) { g2.fill(ctrl1); } */ protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; Shape s; DrawingObject o; for (int i = 0; i < shapes.size(); i++) { o = (DrawingObject)shapes.elementAt(i); s = (Shape)o.shape; //g2.setColor(colors[(i % color_n)]); g2.setColor(o.color); if (o.filled) g2.fill(s); else g2.draw(s); } //handles if (selectedTool == TOOL_SELECT && selectedObject != null) { g2.setColor(Color.RED); g2.fill(ctrl1); g2.fill(ctrl2); g2.fill(ctrl3); g2.fill(ctrl4); } } } public void mouseReleased(MouseEvent e) { final int W = 100; final int H = 100; boolean changed = false; DrawingObject o; if (SwingUtilities.isRightMouseButton(e)) return; if (selectedTool == TOOL_SELECT) { Rectangle bounds; boolean firstTime = true; for (int i = shapes.size()-1; i > -1 ; i--) { o = (DrawingObject)shapes.get(i); bounds = o.shape.getBounds(); if (bounds.contains(e.getX(), e.getY())) { if (firstTime) { //määra handlilte asukohad ctrl1.setLocation(bounds.x -4, bounds.y -4); ctrl2.setLocation(bounds.x + bounds.width -4, bounds.y -4); ctrl3.setLocation(bounds.x + bounds.width -4, bounds.y + bounds.height -4); ctrl4.setLocation(bounds.x -4, bounds.y + bounds.height -4); selectedObject = o; //käsi uuesti joonistada drawingPane.repaint(); firstTime = false; return; } } } } else { int x = e.getX() - W/2; int y = e.getY() - H/2; if (x < 0) x = 0; if (y < 0) y = 0; o = new DrawingObject(); if (selectedTool == TOOL_RECT) {o.shape = new Rectangle(x, y, W, H);} if (selectedTool == TOOL_OVAL) {o.shape = new Ellipse(x, y, W, H);} o.filled = mnCbFill.getState(); o.color = selectedColor; shapes.addElement(o); drawingPane.scrollRectToVisible(o.shape.getBounds()); int this_width = (x + W + 2); if (this_width > area.width) { area.width = this_width; changed=true; } int this_height = (y + H + 2); if (this_height > area.height) { area.height = this_height; changed=true; } } if (changed) { //Update client's preferred size because //the area taken up by the graphics has //gotten larger or smaller (if cleared). drawingPane.setPreferredSize(area); //Let the scroll pane know to update itself //and its scrollbars. drawingPane.revalidate(); } drawingPane.repaint(); label2.setText(""+ shapes.size()); } public void mouseClicked(MouseEvent e){} public void mouseEntered(MouseEvent e){} public void mouseExited(MouseEvent e){} public void mousePressed(MouseEvent e){} JMenuItem mnLoad, mnSave, mnImport, mnExport, mnDelete, mnDeleteAll; JCheckBoxMenuItem mnCbFill; JRadioButtonMenuItem mnRbRect, mnRbOval, mnRbSelect; public JMenuBar createMenuBar() { //Set up the menu bar, which appears above the content pane. JMenuBar menuBar = new JMenuBar(); JMenu menu = null; JMenuItem menuItem = null; menu = new JMenu("Failid"); menuItem = new JMenuItem("Lae.."); menuItem.addActionListener(this); menu.add(menuItem); mnLoad = menuItem; menuItem = new JMenuItem("Salvesta.."); menuItem.addActionListener(this); menu.add(menuItem); mnSave = menuItem; menu.addSeparator(); menuItem = new JMenuItem("Impordi pilt.."); menuItem.addActionListener(this); menu.add(menuItem); mnImport = menuItem; menuItem = new JMenuItem("Ekspordi pilt.."); menuItem.addActionListener(this); menu.add(menuItem); mnExport = menuItem; menuBar.add(menu); menu = new JMenu("Tööriistad"); mnCbFill = new JCheckBoxMenuItem("Täidetud"); mnCbFill.addActionListener(this); menu.add(mnCbFill); menu.addSeparator(); //a group of radio button menu items ButtonGroup group = new ButtonGroup(); JRadioButtonMenuItem rbMenuItem; rbMenuItem = new JRadioButtonMenuItem("Selektor"); rbMenuItem.addActionListener(this); group.add(rbMenuItem); menu.add(rbMenuItem); mnRbSelect = rbMenuItem; menu.addSeparator(); rbMenuItem = new JRadioButtonMenuItem("Ristkülik"); rbMenuItem.setSelected(true); rbMenuItem.addActionListener(this); group.add(rbMenuItem); menu.add(rbMenuItem); mnRbRect = rbMenuItem; rbMenuItem = new JRadioButtonMenuItem("Ellips"); rbMenuItem.addActionListener(this); group.add(rbMenuItem); menu.add(rbMenuItem); mnRbOval = rbMenuItem; menu.addSeparator(); menuItem = new JMenuItem("Kustuta objekt"); menuItem.addActionListener(this); menu.add(menuItem); mnDelete = menuItem; menuItem = new JMenuItem("Kustuta kõik!"); menuItem.addActionListener(this); menu.add(menuItem); mnDeleteAll = menuItem; menuBar.add(menu); return menuBar; } public void actionPerformed(ActionEvent e) { if(e.getSource()==mnLoad){loadDoc(); } else if(e.getSource()==mnSave){saveDoc(); } else if(e.getSource()==mnImport){importPic(); } else if(e.getSource()==mnExport){exportPic(); } else if(e.getSource()==mnCbFill){ if (selectedObject != null) selectedObject.filled = mnCbFill.getState(); drawingPane.repaint(); } else if(e.getSource()==mnRbSelect){selectedTool = TOOL_SELECT; } else if(e.getSource()==mnRbRect){selectedTool = TOOL_RECT; } else if(e.getSource()==mnRbOval){selectedTool = TOOL_OVAL; } else if(e.getSource()==mnDelete){ shapes.removeElement(selectedObject); selectedObject = null; drawingPane.repaint(); } else if(e.getSource()==mnDeleteAll){ shapes.removeAllElements(); area.width=0; area.height=0; drawingPane.setPreferredSize(area); drawingPane.revalidate(); drawingPane.repaint(); } label2.setText(""+ shapes.size()); //System.out.println(shapes.size()); } public void itemStateChanged(ItemEvent e) { //...Get information from the item event... //...Display it in the text area... } //Create a file chooser JFileChooser fc = new JFileChooser(); public void loadDoc() { int returnVal = fc.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); try{ System.out.println("Opening: " + file.getCanonicalPath()); FileInputStream fis = new FileInputStream(file.getCanonicalPath()); ObjectInputStream ois = new ObjectInputStream(fis); shapes = (Vector) ois.readObject(); ois.close(); } catch(Exception ex) {ex.printStackTrace();} } else { System.out.println("Open command cancelled by user." ); } } public void saveDoc() { int returnVal = fc.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); try{ System.out.println("Saving: " + file.getCanonicalPath()); FileOutputStream fos = new FileOutputStream(file.getCanonicalPath()); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(shapes); oos.close(); } catch(IOException ex) {ex.printStackTrace();} } else { System.out.println("Save command cancelled by user."); } } public void importPic() { System.out.println("See funktsioon pole realiseeritud."); } public void exportPic() { int returnVal = fc.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); try{ System.out.println("Saving: " + file.getCanonicalPath()); BufferedImage pilt = new BufferedImage(area.width, area.height, BufferedImage.TYPE_INT_RGB); Graphics2D piltg = pilt.createGraphics(); drawingPane.paint(piltg); FileOutputStream fos = new FileOutputStream(file.getCanonicalPath()); JPEGCodec.createJPEGEncoder(fos).encode(pilt); fos.close(); } catch(IOException ex) {ex.printStackTrace();} } else { System.out.println("Save command cancelled by user."); } } public static void main(String[] args) { //Make sure we have nice window decorations. JFrame.setDefaultLookAndFeelDecorated(true); //Create and set up the window. JFrame frame = new JFrame("KObjectDraw"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Create and set up the content pane. //JComponent newContentPane = new KObjectDraw(); KObjectDraw kodContentPane = new KObjectDraw(); kodContentPane.setOpaque(true); frame.setJMenuBar(kodContentPane.createMenuBar()); frame.setContentPane(kodContentPane); //Display the window. frame.pack(); frame.setVisible(true); } } class DrawingObject implements Serializable { Shape shape; Color color; Stroke stroke; boolean filled; } class Ellipse extends Ellipse2D.Double implements Serializable { public Ellipse() { super(); } public Ellipse(double x, double y, double w, double h) { super(x, y, w, h); } // Serialization code - readObject private void readObject(java.io.ObjectInputStream ois) throws java.lang.ClassNotFoundException, java.io.IOException { // Initialize object from stream Object[] data = (Object[]) ois.readObject(); x = ((java.lang.Double)data[0]).doubleValue(); y = ((java.lang.Double)data[1]).doubleValue(); width = ((java.lang.Double)data[2]).doubleValue(); height = ((java.lang.Double)data[3]).doubleValue(); } // Serialization code - writeObject private void writeObject(java.io.ObjectOutputStream oos) throws java.io.IOException { Object data[] = new Object[4]; data[0] = new java.lang.Double(x); data[1] = new java.lang.Double(y); data[2] = new java.lang.Double(width); data[3] = new java.lang.Double(height); oos.writeObject(data); } } class ColorButton extends JButton{ Color color; public ColorButton(Color c){ setIcon(new ColorIcon(c)); color = c; } } class ColorIcon implements Icon { Color color; public ColorIcon (Color c) { color = c; } public void paintIcon (Component c, Graphics g, int x, int y) { g.setColor(color); g.fillRect (x, y, getIconWidth(), getIconHeight()); } public int getIconWidth() { return 20; } public int getIconHeight() { return 20; } }