Javafree
Página Inicial do Fórum > Java Básico

Código Java não funciona



Criar novo tópico   Responder tópico


  1. Elkran
    Posts:1


    Comment Arrow

    Publicado em: 19/07/2016 14:57:41

    Olá, pessoal! Gostaria de saber aonde está o erro nesse código! Obrigado!!!


    package javarobotpainter;

    import java.awt.*;
    import java.awt.datatransfer.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import java.util.*;
    import javax.imageio.ImageIO;


    public class JavaRobotPainter {

    private Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();


    private static final int START_POSITION_X = 61;

    private static final int START_POSITION_Y = 94;


    private int rectangleSize = 5;

    private ArrayList<Color> availableColors = new ArrayList<Color>();

    private HashMap<Color, Point> colorPosition = new HashMap<Color, Point>();

    private enum ColorNr {COLOR_ONE, COLOR_TWO};

    private ColorNr currentColor = ColorNr.COLOR_ONE;
    private Color[] selectedColors = new Color[]{new Color(0, 0, 0), new Color(255, 255, 255)};


    private BufferedImage image;


    private Process msPaint;

    private Robot robot;

    private int robotDelay = 1;


    private long timeRequiredToStartMsPaint = 1000;


    public JavaRobotPainter() throws AWTException, IOException {
    image = ImageIO.read(new File("cavalos.jpg");
    robot = new Robot();
    robot.setAutoDelay(robotDelay);

    initMsPaint();
    startPainting();
    }

    private void initMsPaint() throws IOException {
    msPaint = Runtime.getRuntime().exec("mspaint.exe";

    // wait until mspaint.exe starts
    long time = System.currentTimeMillis();
    while(System.currentTimeMillis() - time < timeRequiredToStartMsPaint);

    // maximize the window
    // NOTE: the shortcut may vary, depending on the language your windows version has
    robot.keyPress(KeyEvent.VK_ALT);
    robot.keyPress(KeyEvent.VK_SPACE);
    robot.keyPress(KeyEvent.VK_M);
    robot.keyRelease(KeyEvent.VK_M);
    robot.keyRelease(KeyEvent.VK_SPACE);
    robot.keyRelease(KeyEvent.VK_ALT);

    setAttributes(image.getWidth(), image.getHeight());
    initColors();
    chooseFilledRectangle();
    }


    private void setAttributes(int width, int height) {
    // if the width or height is too large then exit program
    if (width + START_POSITION_X > screenSize.width || height + START_POSITION_Y > screenSize.height) {
    System.out.println("The width or height is too large!";
    msPaint.destroy();
    System.exit(0);
    }

    // open attributes window
    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_E);
    robot.keyRelease(KeyEvent.VK_E);
    robot.keyRelease(KeyEvent.VK_CONTROL);

    // set width and height
    setCliboard(new Integer(width).toString());
    pasteDataFromClipboard();
    robot.keyPress(KeyEvent.VK_TAB);
    robot.keyRelease(KeyEvent.VK_TAB);
    setCliboard(new Integer(height).toString());
    pasteDataFromClipboard();
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);
    }


    private void initColors() {
    int interval = 16; // The distance the mouse is going to be moved from each color.
    int startX = 95; // The x position to the first color in the panel.
    int startY = 55; // The y position to the first color in the panel.

    // Finds the colors and adds them to avaibleColors, and puts the color position in colorPosition.
    for (int i = 0; i < 14; i++) {
    for (int j = 0; j < 2; j++) {
    Color color = robot.getPixelColor(startX + i*interval, startY + j*interval);
    availableColors.add(color);
    colorPosition.put(color, new Point(startX + i*interval, startY + j*interval));
    }
    }
    }


    private void chooseFilledRectangle() {

    robot.mouseMove(15, 210);
    robot.mousePress(InputEvent.BUTTON1_MASK);
    robot.mouseRelease(InputEvent.BUTTON1_MASK);


    robot.mouseMove(15, 300);
    robot.mousePress(InputEvent.BUTTON1_MASK);
    robot.mouseRelease(InputEvent.BUTTON1_MASK);
    }


    private void pasteDataFromClipboard() {
    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_CONTROL);
    }


    public void setCliboard(String string) {
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    clipboard.setContents(new StringSelection(string), null);
    }

    private void startPainting() {
    Point point = new Point(MouseInfo.getPointerInfo().getLocation().x, MouseInfo.getPointerInfo().getLocation().y);
    for (int i = START_POSITION_Y; i-START_POSITION_Y < image.getHeight(); i += rectangleSize) {
    for (int j = START_POSITION_X; j-START_POSITION_X < image.getWidth(); j += rectangleSize) {
    // if user moves the mouse then the program terminates
    if (point.x != MouseInfo.getPointerInfo().getLocation().x || point.y != MouseInfo.getPointerInfo().getLocation().y)
    System.exit(0);

    setColor(new Color(image.getRGB(j-START_POSITION_X, i-START_POSITION_Y)));

    int mouseButton = (currentColor == ColorNr.COLOR_ONE) ? InputEvent.BUTTON1_MASK : InputEvent.BUTTON3_MASK;
    robot.mouseMove(j, i);
    robot.mousePress(mouseButton);
    robot.mouseMove(j + rectangleSize, i + rectangleSize);
    robot.mouseRelease(mouseButton);

    point.setLocation(j + rectangleSize, i + rectangleSize);
    }
    }
    }


    private void setColor(Color pixelColor) {
    Color mostAccurateColor = findMostAccurateColorAvailable(pixelColor);

    if (selectedColors[0].equals(mostAccurateColor)) {
    currentColor = ColorNr.COLOR_ONE;
    }
    else if (selectedColors[1].equals(mostAccurateColor)) {
    currentColor = ColorNr.COLOR_TWO;
    }
    else {
    Point p = colorPosition.get(mostAccurateColor);

    int mouseButton;
    if (currentColor == ColorNr.COLOR_ONE) {
    mouseButton = InputEvent.BUTTON3_MASK;
    currentColor = ColorNr.COLOR_TWO;
    selectedColors[1] = mostAccurateColor;
    }
    else {
    mouseButton = InputEvent.BUTTON1_MASK;
    currentColor = ColorNr.COLOR_ONE;
    selectedColors[0] = mostAccurateColor;
    }

    robot.mouseMove(p.x, p.y);
    robot.mousePress(mouseButton);
    robot.mouseRelease(mouseButton);
    }
    }


    private Color findMostAccurateColorAvailable(Color pixelColor) {
    double minError = Double.MAX_VALUE;
    int bestColorIndex = 0;
    for (int i = 0; i < availableColors.size(); i++) {
    int r1 = availableColors.get(i).getRed();
    int g1 = availableColors.get(i).getGreen();
    int b1 = availableColors.get(i).getBlue();

    int r2 = pixelColor.getRed();
    int g2 = pixelColor.getGreen();
    int b2 = pixelColor.getBlue();

    // 2-norm distance
    double error = Math.sqrt((r1-r2)*(r1-r2) + (g1-g2)*(g1-g2) + (b1-b2)*(b1-b2));

    if (error < minError) {
    minError = error;
    bestColorIndex = i;
    }
    }

    return availableColors.get(bestColorIndex);
    }


    public static void main(String[] args) throws AWTException, IOException {
    new JavaRobotPainter();
    }
    }
    [/code]



  1. Astiazara
    Posts:3


    Comment Arrow

    Publicado em: 06/08/2016 22:36:22

    Bem, entendo que existem 3 maneiras de um código não funcionar:
    1. Ele não compila: erro de compilação.
    2. Ele não executa ou ao executar determinada ação ele mostra um erro: erro de tempo de execução.
    3. Ele executa sem erros, mas o resultado produzido não é o esperado (por exemplo, valores calculado errados): erro de implementação, lógica, projeto ou análise.

    Ajudaria se você desse mais detalhes sobre o seu tipo de erro.
    Se for o 1, mostrar qual a mensagem de erro que o compilador dá. Ele normalmente mostra o número da linha que o erro está.
    Se for o tipo 2, você deve postar aqui no fórum a pilha de chamadas que foi impressa no console quando o erro ocorreu.
    Se for tipo3, você deve nos explicar o que seu programa deveria fazer e não está fazendo.



  1. Relacionados