Как работать с Graphics - Java
Формулировка задачи:
Здравствуйте!
Пишу графический редактор, но мне все непонятно, как работает Graphics, куда, например, в моем коде его впихивать и тд
Пробовал написать, например,
Или
Но ничего не менялось, да и понятно, что тут явно неправильно
Graphics g; g.drowChars(...);
this.setBackGround(Colour.WHITE)
import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.ImageObserver; import java.io.File; import java.text.AttributedCharacterIterator; import java.util.LinkedHashMap; public class GraphicsEditor extends JFrame { File file; // Our selected file Graphics graphics; private ActionListener open = new ActionListener() { // Opens a file @Override public void actionPerformed(ActionEvent actionEvent) { JFileChooser chooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter( "JPG & GIF Images", "jpg", "gif", "png"); chooser.setFileFilter(filter); if(JFileChooser.APPROVE_OPTION == (chooser.showDialog(null, "Open"))) { file = chooser.getSelectedFile(); } } }; private ActionListener save = new ActionListener() { // Saves a file @Override public void actionPerformed(ActionEvent actionEvent) { JFileChooser chooser = new JFileChooser(); File file = null; int r = chooser.showSaveDialog(null); /* if(JFileChooser.APPROVE_OPTION == (chooser.showSaveDialog(null)))*/ } }; /* Remove the full paths to the icons sometime*/ ImageIcon whiteIcon = new ImageIcon("D:\\java\\ideaprojects\\graphics editor\\Icons\\white.png"); ImageIcon blackIcon = new ImageIcon("D:\\java\\ideaprojects\\graphics editor\\Icons\\black.png"); ImageIcon redIcon = new ImageIcon("D:\\java\\ideaprojects\\graphics editor\\Icons\\red.png"); ImageIcon greenIcon = new ImageIcon("D:\\java\\ideaprojects\\graphics editor\\Icons\\green.png"); ImageIcon yellowIcon = new ImageIcon("D:\\java\\ideaprojects\\graphics editor\\Icons\\yellow.png"); ImageIcon blueIcon = new ImageIcon("D:\\java\\ideaprojects\\graphics editor\\Icons\\blue.png"); JButton white = new JButton(whiteIcon); JButton black = new JButton(blackIcon); JButton red = new JButton(redIcon); JButton green = new JButton(greenIcon); JButton yellow = new JButton(yellowIcon); JButton blue = new JButton(blueIcon); private JMenu[] menus = { new JMenu("File")/*, new JMenu("Tools"), new JMenu("Size")*/ }; private JMenuItem[] items = { new JMenuItem("Open"), new JMenuItem("Save"), new JMenuItem("Save as")/*, new JMenuItem("Pencil"), new JMenuItem("Eraser"), new JMenuItem("Text"), new JMenuItem("1"), new JMenuItem("2"), new JMenuItem("2")*/ }; public GraphicsEditor() { for(int i = 0; i < items.length; i++) menus[i/3].add(items[i]); JMenuBar mb = new JMenuBar(); for(JMenu jm : menus) mb.add(jm); setJMenuBar(mb); Dimension colours = new Dimension(15, 15); white.setPreferredSize(colours); black.setPreferredSize(colours); red.setPreferredSize(colours); green.setPreferredSize(colours); yellow.setPreferredSize(colours); blue.setPreferredSize(colours); add(white); add(black); add(red); add(green); add(yellow); add(blue); items[0].addActionListener(open); // open a file items[1].addActionListener(save); // save the file setLayout(new FlowLayout()); } public static void main(String[] args) { Swing.go(new GraphicsEditor(), 750, 550); } }
Решение задачи: «Как работать с Graphics»
textual
Листинг программы
import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.*; import java.awt.event.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; public class GraphicsEditor extends JFrame { private final String[] IMAGE_NAMES = "white black yellow green red blue".split(" "); private final Color[] IMAGE_COLORS = { Color.WHITE, Color.BLACK, Color.YELLOW, Color.GREEN, Color.RED, Color.BLUE}; private final String IMAGE_PATH = "D:/java/ideaprojects/graphics editor/Icons/"; File file; // Our selected file private GraphicsPanel jp = new GraphicsPanel(this); private JButton[] jButtons; private ActionListener open = new ActionListener() { // Opens a file @Override public void actionPerformed(ActionEvent actionEvent) { JFileChooser chooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter( "JPG & GIF Images", "jpg", "gif", "png"); chooser.setFileFilter(filter); if (JFileChooser.APPROVE_OPTION == (chooser.showDialog(null, "Open"))) { file = chooser.getSelectedFile(); } ImageIcon image = new ImageIcon(chooser.getSelectedFile().getPath()); jp.setImage(image); repaint(); } }; private ActionListener save = new ActionListener() { // Saves a file @Override public void actionPerformed(ActionEvent actionEvent) { JFileChooser chooser = new JFileChooser(); File file = null; int r = chooser.showSaveDialog(null); /* if(JFileChooser.APPROVE_OPTION == (chooser.showSaveDialog(null)))*/ BufferedImage image = jp.getImage(); try { ImageIO.write(image, "jpg", chooser.getSelectedFile()); } catch (IOException e) { e.printStackTrace(); } } }; private ActionListener bListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JButton jButton = (JButton) e.getSource(); for (int i = 0; i < jButtons.length; i++) { // порядок цветов такой же как имен картинок if (jButton == jButtons[i]) { // порядок кнопок такой же как имен картинок jp.setPenColor(IMAGE_COLORS[i]); // задаем цвет карандаша по кнопке return; } } } }; private MouseMotionListener mMListener = new MouseMotionListener() { @Override public void mouseDragged(MouseEvent e) { jp.add(e.getX(),e.getY()); repaint(); } @Override public void mouseMoved(MouseEvent e) { } }; private MouseListener mListener = new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { jp.setPressed(true); } @Override public void mouseReleased(MouseEvent e) { jp.setPressed(false); } }; /* Remove the full paths to the icons sometime*/ private JMenu[] menus = { new JMenu("File")/*, new JMenu("Tools"), new JMenu("Size")*/ }; private JMenuItem[] items = { new JMenuItem("Open"), new JMenuItem("Save"), new JMenuItem("Save as")/*, new JMenuItem("Pencil"), new JMenuItem("Eraser"), new JMenuItem("Text"), new JMenuItem("1"), new JMenuItem("2"), new JMenuItem("2")*/ }; public GraphicsEditor() { JPanel jpColors = new JPanel();//new GridLayout(1, 6)); jpColors.setPreferredSize(new Dimension(90, 20)); Dimension bSize = new Dimension(15, 15); jButtons = new JButton[IMAGE_NAMES.length]; // сколько имен столько и кнопок for (int i = 0; i < jButtons.length; i++) { ImageIcon image = new ImageIcon(IMAGE_PATH + IMAGE_NAMES[i] + ".png"); JButton b = new JButton(image); b.setPreferredSize(bSize); b.addActionListener(bListener); jpColors.add(b); jButtons[i] = b; // сохраняем если понадобится необязательно } for (int i = 0; i < items.length; i++) menus[i / 3].add(items[i]); JMenuBar mb = new JMenuBar(); for (JMenu jm : menus) mb.add(jm); setJMenuBar(mb); add(jpColors, BorderLayout.NORTH); jp.setBackground(Color.WHITE); jp.addMouseListener(mListener); jp.addMouseMotionListener(mMListener); add(jp); items[0].addActionListener(open); // open a file items[1].addActionListener(save); // save the file } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { GraphicsEditor ge = new GraphicsEditor(); ge.setSize(750, 550); ge.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); ge.setLocationRelativeTo(null); ge.setVisible(true); } }); } }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д