/** constructor */
 public DanceQueuePanel() {
   //	flow layout
   setLayout(new FlowLayout());
   //	uses buffer	to	draw arrows	based	on	queues in an array
   myImage = new BufferedImage(600, 600, BufferedImage.TYPE_INT_RGB);
   myBuffer = myImage.getGraphics();
   // uses timer to queue buffer changes
   time = 0;
   timer = new Timer(5, new Listener());
   timer.start();
   setFocusable(true);
   // picks instructions	based	on	song & level
   if (Danceoff.getSong() == -1 && Danceoff.getDifficulty() == 0) {
     arrows = new Arrow[] {new UpArrow(1000), new DownArrow(2000), new LeftArrow(3000)};
   }
   // setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.BLACK, 3),
   //	"DanceQueuePanel"));
   // load images for arrows
   rightArrowImg = null;
   leftArrowImg = null;
   upArrowImg = null;
   downArrowImg = null;
   try {
     rightArrowImg = ImageIO.read(new File("arrowB right.png"));
     leftArrowImg = ImageIO.read(new File("arrowB left.png"));
     upArrowImg = ImageIO.read(new File("arrowB up copy.png"));
     downArrowImg = ImageIO.read(new File("arrowB down.png"));
   } catch (IOException e) {
     warn("YOU FAIL", e);
     System.exit(2);
   }
 }
示例#2
0
  /**
   * Loads the tileset defined in the constructor into a JPanel which it then returns. Makes no
   * assumptions about height or width, which means it needs to read an extra 64 tiles at worst (32
   * down to check height and 32 across for width), since the maximum height/width is 32 tiles.
   */
  public JPanel loadTileset() {
    int height = MAX_TILESET_SIZE;
    int width = MAX_TILESET_SIZE;

    boolean maxHeight = false;
    boolean maxWidth = false;

    // find width
    int j = 0;
    while (!maxWidth) {
      try {
        File f = new File(tileDir + "/" + j + "_" + 0 + ".png");
        ImageIO.read(f);
      } catch (IOException e) {
        width = j;
        maxWidth = true;
      }
      j += TILE_SIZE;
    }

    // find height
    int i = 0;
    while (!maxHeight) {
      try {
        File f = new File(tileDir + "/" + 0 + "_" + i + ".png");
        ImageIO.read(f);
      } catch (IOException e) {
        height = i;
        maxHeight = true;
      }
      i += TILE_SIZE;
    }

    JPanel tileDisplay = new JPanel();
    tileDisplay.setLayout(new GridLayout(height / TILE_SIZE, width / TILE_SIZE));
    tileDisplay.setMinimumSize(new Dimension(width, height));
    tileDisplay.setPreferredSize(new Dimension(width, height));
    tileDisplay.setMaximumSize(new Dimension(width, height));

    for (i = 0; i < height; i += TILE_SIZE) {
      for (j = 0; j < width; j += TILE_SIZE) {
        String fPath = tileDir + "/" + j + "_" + i;
        try {
          int[] mov = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};

          Image icon = getTile(tileDir, j, i, 1);
          Tile tile =
              new Tile(new ImageIcon(icon), "palette", 0, 0, mov, "none", false, "" + j + "_" + i);
          tile.addMouseListener(new PaletteButtonListener());
          tile.setMaximumSize(new Dimension(TILE_SIZE, TILE_SIZE));
          tile.setPreferredSize(new Dimension(TILE_SIZE, TILE_SIZE));
          tile.setMinimumSize(new Dimension(TILE_SIZE, TILE_SIZE));
          tileDisplay.add(tile);
        } catch (IOException e) {
        }
      }
    }
    return tileDisplay;
  }
示例#3
0
 /**
  * Takes a filepath to a tileset folder, x, y coordinates and a scale and returns the desired
  * tile.
  */
 public static Image getTile(String filepath, int x, int y, int scale) throws IOException {
   // System.out.println(filepath+"/"+x+"_"+y);
   try {
     return scaleImage(ImageIO.read(new File(filepath + "/" + x + "_" + y + ".png")), scale);
   } catch (IOException e) {
     return scaleImage(ImageIO.read(new File(filepath + "/" + x + "_" + y)), scale);
   }
 }
示例#4
0
文件: Frame.java 项目: stuydw/final
 /*======== public void save() ==========
 Inputs:  String filename
 Returns:
 saves the bufferedImage as a png file with the given filename
 ====================*/
 public void save(String filename) {
   try {
     File fn = new File(filename);
     ImageIO.write(bi, "png", fn);
   } catch (IOException e) {
   }
 }
示例#5
0
  public void readImg(String in) {
    try {
      character = ImageIO.read(new File(in));
    } catch (IOException e) {

    }
  }
示例#6
0
 public PanImage1() {
   try {
     image = ImageIO.read(new File("WALLPAPER02.jpg"));
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
示例#7
0
 /**
  * Returns the specified image.
  *
  * @param url image url
  * @return image
  */
 public static Image get(final URL url) {
   try {
     return ImageIO.read(url);
   } catch (final IOException ex) {
     throw Util.notExpected(ex);
   }
 }
示例#8
0
 public void init() throws Exception {
   table = ImageIO.read(new File("image/board.jpg"));
   black = ImageIO.read(new File("image/black.gif"));
   white = ImageIO.read(new File("image/white.gif"));
   selected = ImageIO.read(new File("image/selected.gif"));
   // 把每个元素赋为"╋",用于在控制台画出棋盘
   for (int i = 0; i < BOARD_SIZE; i++) {
     for (int j = 0; j < BOARD_SIZE; j++) {
       board[i][j] = "╋";
     }
   }
   chessBoard.setPreferredSize(new Dimension(TABLE_WIDTH, TABLE_HETGHT));
   chessBoard.addMouseListener(
       new MouseAdapter() {
         public void mouseClicked(MouseEvent e) {
           // 将用户鼠标事件的座标转换成棋子数组的座标。
           int xPos = (int) ((e.getX() - X_OFFSET) / RATE);
           int yPos = (int) ((e.getY() - Y_OFFSET) / RATE);
           board[xPos][yPos] = "●";
           /*
           电脑随机生成2个整数,作为电脑下棋的座标,赋给board数组。
           还涉及:
           1.如果下棋的点已经棋子,不能重复下棋。
           2.每次下棋后,需要扫描谁赢了
           */
           chessBoard.repaint();
         }
         // 当鼠标退出棋盘区后,复位选中点座标
         public void mouseExited(MouseEvent e) {
           selectedX = -1;
           selectedY = -1;
           chessBoard.repaint();
         }
       });
   chessBoard.addMouseMotionListener(
       new MouseMotionAdapter() {
         // 当鼠标移动时,改变选中点的座标
         public void mouseMoved(MouseEvent e) {
           selectedX = (e.getX() - X_OFFSET) / RATE;
           selectedY = (e.getY() - Y_OFFSET) / RATE;
           chessBoard.repaint();
         }
       });
   f.add(chessBoard);
   f.pack();
   f.setVisible(true);
 }
示例#9
0
  public PanImage2() {
    try {
      image2 = ImageIO.read(new File("Initial.D.full.501729.jpg"));

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
示例#10
0
  public PanImage3() {
    try {
      image3 = ImageIO.read(new File("sleeping_dogs_2012_video_game-wallpaper-1024x768.jpg"));

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
示例#11
0
  /**
   * Write a BufferedImage to a File.
   *
   * @param image image to be written
   * @param fileName name of file to be created
   * @exception IOException if an error occurs during writing
   */
  public static void writeImage(BufferedImage image, String fileName) throws IOException {
    if (fileName == null) return;

    int offset = fileName.lastIndexOf(".");
    String type = offset == -1 ? "png" : fileName.substring(offset + 1);

    ImageIO.write(image, type, new File(fileName));
  }
示例#12
0
  public void initialize() {

    // openLevelFile images:
    try {
      boxSpriteSheet = ImageIO.read(new File("ItemContainer.png"));
      coinSpriteSheet = ImageIO.read(new File("Coin.png"));
    } catch (Exception e) {
    }

    if (openLevelFile == false) {
      try {
        loadLevel(initLevel);
      } catch (Exception e) {
        System.out.println(e);
      }
    } else {
      loadLevel(FileOpenDialog("Open ..."));
    }

    // create tile layer:
    renderTileLayer();

    // create bg layer:
    backgroundLayer = new VolatileImage[backgroundImage.length];

    // render layer:
    for (int i = 0; i < backgroundImage.length; i++) {
      renderBackgroundLayer(0);
      renderBackgroundLayer(1);
    }

    // create hardware accellerated rendering layer:
    renderImage =
        this.getGraphicsConfiguration()
            .createCompatibleVolatileImage(
                loadedLevel.getWidth() * 16,
                loadedLevel.getHeight() * 16,
                Transparency.TRANSLUCENT);
    Graphics2D g2d = renderImage.createGraphics();
    g2d.setComposite(AlphaComposite.Src);

    // Clear the image.
    g2d.setColor(new Color(0, 0, 0, 0));
    g2d.fillRect(0, 0, renderImage.getWidth(), renderImage.getHeight());
    g2d.setBackground(new Color(0, 0, 0, 0));
  }
  /** Open a file and load the image. */
  public void openFile() {
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new File("."));
    String[] extensions = ImageIO.getReaderFileSuffixes();
    chooser.setFileFilter(new FileNameExtensionFilter("Image files", extensions));
    int r = chooser.showOpenDialog(this);
    if (r != JFileChooser.APPROVE_OPTION) return;

    try {
      Image img = ImageIO.read(chooser.getSelectedFile());
      image =
          new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
      image.getGraphics().drawImage(img, 0, 0, null);
    } catch (IOException e) {
      JOptionPane.showMessageDialog(this, e);
    }
    repaint();
  }
示例#14
0
 public void paintComponent(Graphics g) {
   if (paint) {
     try {
       Rectangle vis = getVisibleRect();
       File fi = ImageLoader.getFile("images/inventoryback.png");
       BufferedImage bg = ImageIO.read(fi.toURL());
       g.drawImage(bg, vis.x, vis.y, null);
     } catch (Exception e) {
     }
   }
 }
示例#15
0
  public BufferedImage getImage(String Direct, String FName) {
    // JOptionPane.showMessageDialog(null, "GameCharacter");
    try {
      BufferedImage bg = ImageIO.read(getClass().getResource(Direct + FName));
      return bg;

    } catch (Exception e) {
      JOptionPane.showMessageDialog(null, getClass().toString());
    }
    return null;
  }
示例#16
0
  /**
   * Loads an image from a given image identifier.
   *
   * @param imageID The identifier of the image.
   * @return The image for the given identifier.
   */
  public static ImageIcon getImage(String imageID) {
    BufferedImage image = null;

    String path = IMAGE_RESOURCE_BUNDLE.getString(imageID);

    try {
      image = ImageIO.read(Resources.class.getClassLoader().getResourceAsStream(path));
    } catch (IOException e) {
      log.error("Failed to load image:" + path, e);
    }

    return new ImageIcon(image);
  }
    Sidebar() {
      super(BoxLayout.Y_AXIS);

      try {
        back =
            ImageIO.read(
                ClassLoader.getSystemClassLoader()
                    .getResource("org/madeirahs/editor/ui/help_sidebar.png"));
        scaleImage();
        setPreferredSize(new Dimension(back.getWidth(), back.getHeight()));
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
示例#18
0
文件: GuiClient.java 项目: x-mel/eva
  // we define the method for downloading when pressing on the download button
  public void qrvidlink() {
    try {
      System.setSecurityManager(new SecurityManager());

      ipadd = tfIP.getText();
      Interface client = (Interface) Naming.lookup("rmi://" + ipadd + "/getvid");

      // Get the String entered into the TextField tfInput, convert to int
      link = tfInput.getText();
      vlink = client.getvid(link);

      // here we receive the image serialized into bytes from the server and
      // saved it on the client as png image
      byte[] bytimg = client.qrvid(vlink);
      BufferedImage img = ImageIO.read(new ByteArrayInputStream(bytimg));
      File outputfile = new File("qrcode.png");
      ImageIO.write(img, "png", outputfile);

      // img= new ImageIcon(bytimg.toByteArray());
    } catch (Exception e) {
      System.out.println("[System] Server failed: " + e);
    }
  }
示例#19
0
 public MainPanel() {
   super(new BorderLayout());
   BufferedImage bi = null;
   try {
     bi = ImageIO.read(getClass().getResource("test.jpg"));
   } catch (IOException ioe) {
     ioe.printStackTrace();
   }
   bufferedImage = bi;
   List<AbstractAction> list =
       Arrays.asList(
           new AbstractAction("NONE") {
             @Override
             public void actionPerformed(ActionEvent e) {
               mode = Flip.NONE;
               repaint();
             }
           },
           new AbstractAction("VERTICAL") {
             @Override
             public void actionPerformed(ActionEvent e) {
               mode = Flip.VERTICAL;
               repaint();
             }
           },
           new AbstractAction("HORIZONTAL") {
             @Override
             public void actionPerformed(ActionEvent e) {
               mode = Flip.HORIZONTAL;
               repaint();
             }
           });
   Box box = Box.createHorizontalBox();
   box.add(Box.createHorizontalGlue());
   box.add(new JLabel("Flip: "));
   for (AbstractAction a : list) {
     JRadioButton rb = new JRadioButton(a);
     if (bg.getButtonCount() == 0) {
       rb.setSelected(true);
     }
     box.add(rb);
     bg.add(rb);
     box.add(Box.createHorizontalStrut(5));
   }
   add(p);
   add(box, BorderLayout.SOUTH);
   setOpaque(false);
   setPreferredSize(new Dimension(320, 240));
 }
示例#20
0
  public ImageFont(String pathToImage, int numCols, int numRows) {
    try {
      tilesImg = convertToARGB(ImageIO.read(new File(pathToImage)));

      this.imgW = tilesImg.getWidth();
      this.imgH = tilesImg.getHeight();
      this.numCols = numCols;
      this.numRows = numRows;
      this.numTiles = numCols * numRows;
      this.tW = this.imgW / this.numCols;
      this.tH = this.imgH / this.numRows;

      this.tiles = new BufferedImage[this.numTiles];

      for (int i = 0; i < numCols; i++) {
        for (int j = 0; j < numRows; j++) {
          tiles[(numCols * j) + i] = tilesImg.getSubimage(i * tW, j * tH, tW, tH);
        }
      }
    } catch (IOException e) {
      System.out.println("Couldn't load the image: " + e);
    }
  }
 private void writeToFile(File selectedFile, ImageWriterSpiFileFilter ff) {
   try {
     ImageOutputStream ios = ImageIO.createImageOutputStream(selectedFile);
     ImageWriter iw = ff.getImageWriterSpi().createWriterInstance();
     iw.setOutput(ios);
     ImageWriteParam iwp = iw.getDefaultWriteParam();
     if (iwp.canWriteCompressed()) {
       iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
       // set maximum image quality
       iwp.setCompressionQuality(1.f);
     }
     Image image = viewerPanel.getImage();
     BufferedImage bufferedImage;
     if (viewerPanel.getImage() instanceof BufferedImage)
       bufferedImage = (BufferedImage) viewerPanel.getImage();
     else {
       bufferedImage =
           new BufferedImage(
               image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
       bufferedImage.createGraphics().drawImage(image, 0, 0, null);
     }
     iw.write(null, new IIOImage(bufferedImage, null, null), iwp);
     iw.dispose();
     ios.close();
   } catch (IOException ioe) {
     JOptionPane.showMessageDialog(
         viewerPanel,
         messagesBundle.getString(
             "ImageViewerPanelSaveAction." + "Error_during_image_saving_message_7"),
         //$NON-NLS-1$
         messagesBundle.getString("ImageViewerPanelSaveAction." + "Error_dialog_title_8"),
         //$NON-NLS-1$
         JOptionPane.ERROR_MESSAGE);
     ioe.printStackTrace();
   }
 }
示例#22
0
  /**
   * Creates an instance of <tt>ShowPreviewDialog</tt>
   *
   * @param chatPanel The <tt>ChatConversationPanel</tt> that is associated with this dialog.
   */
  ShowPreviewDialog(final ChatConversationPanel chatPanel) {
    this.chatPanel = chatPanel;

    this.setTitle(
        GuiActivator.getResources().getI18NString("service.gui.SHOW_PREVIEW_DIALOG_TITLE"));
    okButton = new JButton(GuiActivator.getResources().getI18NString("service.gui.OK"));
    cancelButton = new JButton(GuiActivator.getResources().getI18NString("service.gui.CANCEL"));

    JPanel mainPanel = new TransparentPanel();
    mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
    mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    // mainPanel.setPreferredSize(new Dimension(200, 150));
    this.getContentPane().add(mainPanel);

    JTextPane descriptionMsg = new JTextPane();
    descriptionMsg.setEditable(false);
    descriptionMsg.setOpaque(false);
    descriptionMsg.setText(
        GuiActivator.getResources().getI18NString("service.gui.SHOW_PREVIEW_WARNING_DESCRIPTION"));

    Icon warningIcon = null;
    try {
      warningIcon =
          new ImageIcon(
              ImageIO.read(
                  GuiActivator.getResources().getImageURL("service.gui.icons.WARNING_ICON")));
    } catch (IOException e) {
      logger.debug("failed to load the warning icon");
    }
    JLabel warningSign = new JLabel(warningIcon);

    JPanel warningPanel = new TransparentPanel();
    warningPanel.setLayout(new BoxLayout(warningPanel, BoxLayout.X_AXIS));
    warningPanel.add(warningSign);
    warningPanel.add(Box.createHorizontalStrut(10));
    warningPanel.add(descriptionMsg);

    enableReplacement =
        new JCheckBox(
            GuiActivator.getResources()
                .getI18NString("plugin.chatconfig.replacement.ENABLE_REPLACEMENT_STATUS"));
    enableReplacement.setOpaque(false);
    enableReplacement.setSelected(cfg.getBoolean(ReplacementProperty.REPLACEMENT_ENABLE, true));
    enableReplacementProposal =
        new JCheckBox(
            GuiActivator.getResources()
                .getI18NString("plugin.chatconfig.replacement.ENABLE_REPLACEMENT_PROPOSAL"));
    enableReplacementProposal.setOpaque(false);

    JPanel checkBoxPanel = new TransparentPanel();
    checkBoxPanel.setLayout(new BoxLayout(checkBoxPanel, BoxLayout.Y_AXIS));
    checkBoxPanel.add(enableReplacement);
    checkBoxPanel.add(enableReplacementProposal);

    JPanel buttonsPanel = new TransparentPanel(new FlowLayout(FlowLayout.CENTER));
    buttonsPanel.add(okButton);
    buttonsPanel.add(cancelButton);

    mainPanel.add(warningPanel);
    mainPanel.add(Box.createVerticalStrut(10));
    mainPanel.add(checkBoxPanel);
    mainPanel.add(buttonsPanel);

    okButton.addActionListener(this);
    cancelButton.addActionListener(this);

    this.setPreferredSize(new Dimension(390, 230));
  }
示例#23
0
  public static void loadLevel(File levelFile) {

    // clean up old loads:
    loadedLevel.clean();

    if (levelFile != null) {
      GameObject[] go = new GameObject[0];

      try {
        loadedLevel = new Level(levelFile.getPath());
        camera = loadedLevel.getCamera();
        go = loadedLevel.getGameObjects();
      } catch (Exception e) {
        System.out.println(e);
      }

      // Reset numberOf ...
      numberOfBoxes = 0;
      numberOfSprites = 0;
      numberOfTiles = 0;

      for (int i = 0; i < actor.length; i++) {
        actor[i] = null;
      }

      backgroundImage = new Image[2];

      try {
        tileSheet = ImageIO.read(new File(loadedLevel.levelName + "/tilesheet.png"));
        backgroundImage[0] = ImageIO.read(new File(loadedLevel.levelName + "/bg0.png"));
        backgroundImage[1] = ImageIO.read(new File(loadedLevel.levelName + "/bg1.png"));
      } catch (Exception e) {
        System.out.println("ERROR loading images: " + e);
      }

      int MapWidth = loadedLevel.getWidth();
      int MapHeight = loadedLevel.getHeight();

      for (int y = 0; y < MapHeight; y++) {
        for (int x = 0; x < MapWidth; x++) {
          // Number entered in the position represents tileNumber;
          // position of the sprite x*16, y*16

          // get char at position X/Y in the levelLoaded string
          char CharAtXY =
              loadedLevel.level.substring(MapWidth * y, loadedLevel.level.length()).charAt(x);

          // Load objects into the engine/game
          for (int i = 0; i < go.length; i++) {
            if (CharAtXY == go[i].objectChar) {
              try {
                invoke(
                    "game.objects." + go[i].name,
                    "new" + go[i].name,
                    new Class[] {Point.class},
                    new Object[] {new Point(x * 16, y * 16)});
              } catch (Exception e) {
                System.out.println("ERROR trying to invoke method: " + e);
              }
            }
          }

          // Load tiles into engine/game
          // 48 = '0' , 57 = '9'
          if ((int) CharAtXY >= 48 && (int) CharAtXY <= 57) {
            tileObject[gameMain.numberOfTiles] = new WorldTile(Integer.parseInt(CharAtXY + ""));
            tileObject[gameMain.numberOfTiles - 1].sprite.setPosition(x * 16, y * 16);
          }
        }
      }

      // clean up:
      loadedLevel.clean();

      // additional game-specific loading options:
      camera.forceSetPosition(new Point(mario.spawn.x, camera.prefHeight));
      pCoin = new PopupCoin(new Point(-80, -80));

      levelLoaded = true;
    } else {
      System.out.println("Loading cancelled...");
    }
  }
示例#24
0
  private void makeMenuScreen() {
    menu = new JPanel();
    menu.setBackground(Color.BLACK);
    menu.setLayout(null);
    menu.setBounds(0, 0, width, height);

    try {
      BufferedImage menuIMG =
          ImageIO.read(this.getClass().getResource("/Resources/MenuBackground.png"));
      // BufferedImage menuIMG = ImageIO.read(new
      // File("M:/ComputerProgrammingJava/InsaneMouse_03/src/Resources/MenuBackground.png"));
      menuIMGL =
          new JLabel(
              new ImageIcon(
                  menuIMG.getScaledInstance(
                      (int) (width * 0.8), (int) (height * 0.8), Image.SCALE_SMOOTH)));
      menuIMGL.setBounds(0, 0, width, height);
    } catch (Exception e) {
    }

    highscoreL = new JLabel(String.valueOf(highscore));
    highscoreL.setBackground(Color.darkGray);
    highscoreL.setBounds((width / 2) + 100, (height / 2) + 70, 500, 100);
    highscoreL.setForeground(Color.white);

    easy = new JButton("Easy");
    hard = new JButton("Hard");

    easy.addActionListener(this);
    hard.addActionListener(this);

    easy.setBounds((width / 2) - 60, (height / 2) - 50, 120, 20);
    hard.setBounds((width / 2) - 60, height / 2 - 10, 120, 20);

    onePlayerRB = new JRadioButton("One Player");
    twoPlayerRB = new JRadioButton("Two Player");
    mouseRB = new JRadioButton("Mouse (Player 1)");
    keyboardRB = new JRadioButton("Keyboard (Player 1)");
    keyboardSpeedS1 = new JSlider(JSlider.HORIZONTAL, 10, 300, 50);
    keyboardSpeedS2 = new JSlider(JSlider.HORIZONTAL, 10, 300, 50);
    musicCB = new JCheckBox("Music");

    onePlayerRB.setBackground(null);
    twoPlayerRB.setBackground(null);
    mouseRB.setBackground(null);
    keyboardRB.setBackground(null);
    keyboardSpeedS1.setBackground(null);
    keyboardSpeedS2.setBackground(null);
    musicCB.setBackground(null);

    onePlayerRB.setForeground(Color.WHITE);
    twoPlayerRB.setForeground(Color.WHITE);
    mouseRB.setForeground(Color.WHITE);
    keyboardRB.setForeground(Color.WHITE);
    keyboardSpeedS1.setForeground(Color.WHITE);
    keyboardSpeedS2.setForeground(Color.WHITE);
    musicCB.setForeground(Color.WHITE);

    ButtonGroup playerChoice = new ButtonGroup();
    playerChoice.add(onePlayerRB);
    playerChoice.add(twoPlayerRB);
    onePlayerRB.setSelected(true);

    ButtonGroup peripheralChoice = new ButtonGroup();
    peripheralChoice.add(mouseRB);
    peripheralChoice.add(keyboardRB);
    mouseRB.setSelected(true);

    musicCB.setSelected(true);

    onePlayerRB.setBounds((width / 2) + 100, (height / 2) - 50, 100, 20);
    twoPlayerRB.setBounds((width / 2) + 100, (height / 2) - 30, 100, 20);
    mouseRB.setBounds((width / 2) + 100, (height / 2), 200, 20);
    keyboardRB.setBounds((width / 2) + 100, (height / 2) + 20, 200, 20);
    keyboardSpeedS1.setBounds(width / 2 - 120, height / 2 + 100, 200, 50);
    keyboardSpeedS2.setBounds(width / 2 - 120, height / 2 + 183, 200, 50);
    musicCB.setBounds((width / 2) + 100, (height / 2) + 50, 100, 20);

    keyboardSpeedL1 = new JLabel("Keyboard Speed (Player One)");
    keyboardSpeedL1.setForeground(Color.WHITE);
    keyboardSpeedL1.setBounds(width / 2 - 113, height / 2 + 67, 200, 50);

    keyboardSpeedL2 = new JLabel("Keyboard Speed (Player Two)");
    keyboardSpeedL2.setForeground(Color.WHITE);
    keyboardSpeedL2.setBounds(width / 2 - 113, height / 2 + 150, 200, 50);

    howTo = new JButton("How To Play");
    howTo.addActionListener(this);
    howTo.setBounds((width / 2) - 60, height / 2 + 30, 120, 20);

    try {
      BufferedImage howToIMG = ImageIO.read(this.getClass().getResource("/Resources/HowTo.png"));
      // BufferedImage howToIMG = ImageIO.read(new
      // File("M:/ComputerProgrammingJava/InsaneMouse_03/src/Resources/HowTo.png"));
      howToIMGL = new JLabel(new ImageIcon(howToIMG));
      howToIMGL.setBounds(
          width / 2 - howToIMG.getWidth() / 2,
          height / 2 - howToIMG.getHeight() / 2,
          howToIMG.getWidth(),
          howToIMG.getHeight());
    } catch (Exception e) {
    }

    howToBack = new JButton("X");
    howToBack.setBounds(
        (int) (width / 2 + width * 0.25) - 50, (int) (height / 2 - height * 0.25), 50, 50);
    howToBack.setBackground(Color.BLACK);
    howToBack.setForeground(Color.WHITE);
    howToBack.addActionListener(this);

    menu.add(easy);
    menu.add(hard);
    menu.add(howTo);
    menu.add(highscoreL);
    menu.add(onePlayerRB);
    menu.add(twoPlayerRB);
    menu.add(mouseRB);
    menu.add(keyboardRB);
    menu.add(keyboardSpeedL1);
    menu.add(keyboardSpeedL2);
    menu.add(keyboardSpeedS1);
    menu.add(keyboardSpeedS2);
    menu.add(musicCB);
    menu.add(menuIMGL);

    back = new JButton("Back");
    back.setBounds(width / 2 - 40, height / 2, 100, 20);
    back.addActionListener(this);
    back.setVisible(false);
    this.add(back);
  }
示例#25
0
  protected void filePNG() {

    JFileChooser chooser = null;
    File pngFile = null;
    if (currentFile == null) {
      chooser = new JFileChooser(startDirectory);
    } else {
      pngFile = new File(currentFile.getName() + ".png");
      chooser = new JFileChooser(pngFile);
      if (!currentFile.isDirectory()) {
        chooser.setSelectedFile(currentFile);
      }
    }

    if (pngFile == null) return;
    try {
      BufferedImage image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
      paint(image.getGraphics());
      ImageIO.write(image, "png", pngFile);
    } catch (Exception e) {
    }
    return;
    /*		JFileChooser chooser = null;
    		File pngFile = null;
    		if (currentFile == null) {
    			chooser = new JFileChooser(startDirectory);
    		} else {
    			pngFile = new File(currentFile.getName()+".png");
    			chooser = new JFileChooser(pngFile);
    			if (!currentFile.isDirectory()) {
    				chooser.setSelectedFile(currentFile);
    			}
    		}
    		int returnVal = chooser.showSaveDialog(gw);
    		if (returnVal == JFileChooser.APPROVE_OPTION) {
    			File pngFile = chooser.getSelectedFile();

    			int maxX = Integer.MIN_VALUE;
    			int minX = Integer.MAX_VALUE;
    			int maxY = Integer.MIN_VALUE;
    			int minY = Integer.MAX_VALUE;

    			while(Node node : getNodes()) {
    				if(node.getX() > maxX) {
    					maxX = node.getX();
    				}
    				if(node.getX() < minX) {
    					minX = node.getX();
    				}
    				if(node.getY() > maxY) {
    					maxY = node.getY();
    				}
    				if(node.getY() < minY) {
    					minY = node.getY();
    				}
    			}

    			BufferedImage image = new BufferedImage(maxX-minX+50,maxY-minY+50,BufferedImage.TYPE_INT_RGB);



    			ImageIO.write(image,"png",pngFile);
    		}
    */ }
  // Constructor connection receiving a socket number
  public ClientGUI(String host, int port, int udpPort) {

    super("Clash of Clans");
    defaultPort = port;
    defaultUDPPort = udpPort;
    defaultHost = host;

    // the server name and the port number
    JPanel serverAndPort = new JPanel(new GridLayout(1, 5, 1, 3));
    tfServer = new JTextField(host);
    tfPort = new JTextField("" + port);
    tfPort.setHorizontalAlignment(SwingConstants.RIGHT);

    // CHAT COMPONENTS
    chatStatus = new JLabel("Please login first", SwingConstants.LEFT);
    chatField = new JTextField(18);
    chatField.setBackground(Color.WHITE);

    JPanel chatControls = new JPanel();
    chatControls.add(chatStatus);
    chatControls.add(chatField);
    chatControls.setBounds(0, 0, 200, 50);

    chatArea = new JTextArea("Welcome to the Chat room\n", 80, 80);
    chatArea.setEditable(false);
    JScrollPane jsp = new JScrollPane(chatArea);
    jsp.setBounds(0, 50, 200, 550);

    JPanel chatPanel = new JPanel(null);
    chatPanel.setSize(1000, 600);
    chatPanel.add(chatControls);
    chatPanel.add(jsp);

    // LOGIN COMPONENTS
    mainLogin = new MainPanel();
    mainLogin.add(new JLabel("Main Login"));

    usernameField = new JTextField("user", 15);
    passwordField = new JTextField("password", 15);
    login = new CButton("Login");
    login.addActionListener(this);

    sideLogin = new SidePanel(new FlowLayout(FlowLayout.LEFT));
    sideLogin.add(usernameField);
    sideLogin.add(passwordField);
    sideLogin.add(login);

    // MAIN MENU COMPONENTS
    mainMenu = new MainPanel();
    mmLabel = new JLabel("Main Menu");
    timer = new javax.swing.Timer(1000, this);
    mainMenu.add(mmLabel);

    sideMenu = new SidePanel(new FlowLayout(FlowLayout.LEFT));
    cmButton = new CButton("Customize Map");
    tmButton = new CButton("Troop Movement");
    gsButton = new CButton("Game Start");
    logout = new CButton("Logout");
    cmButton.addActionListener(this);
    tmButton.addActionListener(this);
    gsButton.addActionListener(this);
    logout.addActionListener(this);
    sideMenu.add(cmButton);
    // sideMenu.add(tmButton);
    sideMenu.add(gsButton);
    sideMenu.add(logout);

    // CM COMPONENTS
    mainCM = new MainPanel(new GridLayout(mapSize, mapSize));
    tiles = new Tile[mapSize][mapSize];
    int tileSize = mainCM.getWidth() / mapSize;
    for (int i = 0; i < mapSize; i++) {
      tiles[i] = new Tile[mapSize];
      for (int j = 0; j < mapSize; j++) {
        tiles[i][j] = new Tile(i, j);
        tiles[i][j].setPreferredSize(new Dimension(tileSize, tileSize));
        tiles[i][j].setSize(tileSize, tileSize);
        tiles[i][j].addActionListener(this);

        if ((i + j) % 2 == 0) tiles[i][j].setBackground(new Color(102, 255, 51));
        else tiles[i][j].setBackground(new Color(51, 204, 51));

        mainCM.add(tiles[i][j]);
      }
    }

    sideCM = new SidePanel(new FlowLayout(FlowLayout.LEFT));
    cmBack = new CButton("Main Menu");
    cmBack.setSize(150, 30);
    cmBack.setPreferredSize(new Dimension(150, 30));
    cmBack.addActionListener(this);
    sideCM.add(cmBack);

    // TM COMPONENTS
    mainTM = new MainPanel(null);
    mapTM = new Map(600);
    mapTM.setPreferredSize(new Dimension(600, 600));
    mapTM.setSize(600, 600);
    mapTM.setBounds(0, 0, 600, 600);
    mainTM.add(mapTM);

    sideTM = new SidePanel(new FlowLayout(FlowLayout.LEFT));
    tmBack = new CButton("Main Menu");
    tmBack.setSize(150, 30);
    tmBack.setPreferredSize(new Dimension(150, 30));
    tmBack.addActionListener(this);
    sideTM.add(tmBack);

    JRadioButton button;
    ButtonGroup group;

    ub = new ArrayList<JRadioButton>();
    group = new ButtonGroup();

    button = new JRadioButton("Barbarian");
    button.addActionListener(this);
    ub.add(button);
    sideTM.add(button);
    group.add(button);

    button = new JRadioButton("Archer");
    button.addActionListener(this);
    ub.add(button);
    sideTM.add(button);
    group.add(button);

    createBuildings();
    bb = new ArrayList<JRadioButton>();

    group = new ButtonGroup();

    JRadioButton removeButton = new JRadioButton("Remove Building");
    bb.add(removeButton);
    sideCM.add(removeButton);
    group.add(removeButton);

    for (int i = 0; i < bList.size(); i++) {
      button = new JRadioButton(bList.get(i).getName() + '-' + bList.get(i).getQuantity());
      bb.add(button);
      sideCM.add(button);
      group.add(button);
    }

    mainPanels = new MainPanel(new CardLayout());
    mainPanels.add(mainLogin, "Login");
    mainPanels.add(mainMenu, "Menu");
    mainPanels.add(mainCM, "CM");
    mainPanels.add(mainTM, "TM");

    sidePanels = new SidePanel(new CardLayout());
    sidePanels.add(sideLogin, "Login");
    sidePanels.add(sideMenu, "Menu");
    sidePanels.add(sideCM, "CM");
    sidePanels.add(sideTM, "TM");

    JPanel mainPanel = new JPanel(null);
    mainPanel.setSize(1000, 600);
    mainPanel.add(sidePanels);
    mainPanel.add(mainPanels);
    mainPanel.add(chatPanel);

    add(mainPanel, BorderLayout.CENTER);

    try {
      setIconImage(ImageIO.read(new File("images/logo.png")));
    } catch (IOException exc) {
      exc.printStackTrace();
    }

    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(1000, 600);
    setVisible(true);
    setResizable(false);
    chatField.requestFocus();
  }
示例#27
0
  public void write() {

    int navg = 8;
    //		int nshift=3;
    bookend = 8;

    numPgs = pdffile.getNumPages();

    files = new File[numPgs];

    int[] pixelsi = null;
    long[] sum = null;
    long[][] hist = null;
    BufferedImage bimage = null;

    //		BufferedImage simage = null;
    //	    float data[] = { 0.0625f, 0.125f, 0.0625f, 0.125f, 0.25f, 0.125f,
    //	            0.0625f, 0.125f, 0.0625f };
    //	    Kernel kernel = new Kernel(3, 3, data);
    //	    ConvolveOp convolve = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);

    done(0);
    for (int i = 0; i < numPgs; i++) {
      if (i > MAXPAGE) break;
      PDFPage page = getPage(i);
      if (i == 0) {
        w = (int) page.getBBox().getWidth();
        h = (int) page.getBBox().getHeight();
        rect = new Rectangle(0, 0, w, h);
        // w /= 2; h /=2;
        bimage = new BufferedImage(w, h, BufferedImage.TYPE_3BYTE_BGR);
        // simage = new BufferedImage(w, h, BufferedImage.TYPE_3BYTE_BGR);
        pixelsi = new int[h * w];
        sum = new long[h * w];
        hist = new long[navg][h * w];
        for (int j = 0; j < h * w; j++) {
          sum[j] = 0;
        }
        page1.countDown();
      }

      // generate page image
      Image image = pdffile.getPage(i).getImage(w, h, rect, null, true, true);
      // force complete loading
      image = new ImageIcon(image).getImage();
      // Copy image to buffered image
      Graphics g = bimage.createGraphics();
      // Paint the image onto the buffered image
      g.drawImage(image, 0, 0, null);
      g.dispose();

      // extract pixels into array
      bimage.getRGB(0, 0, w, h, pixelsi, 0, w);
      // Accumulate rolling averages
      int im = i % navg;
      int ii = i - navg / 2; // middle of averaging range
      for (int j = 0; j < h * w; j++) {
        int p = pixelsi[j], q = 0;

        // Expand packed 8x3 pixel to 16x3
        long r = 0, r2 = 0;
        r |= (p & 0xff);
        r <<= 16;
        p >>= 8;
        r |= (p & 0xff);
        r <<= 16;
        p >>= 8;
        r |= (p & 0xff);
        r = ~r;
        sum[j] += r; // rolling sum
        if (i >= navg) { // we have enough to average
          sum[j] -= hist[im][j]; // roll off the old
          hist[im][j] = r;
          r2 = (3 * sum[j] / navg + r) / 4;
          r = ~r2;
        } else {
          hist[im][j] = r;
        }

        // Repack averaged pixel
        q |= (r & 0xff);
        q <<= 8;
        r >>= 16;
        q |= (r & 0xff);
        q <<= 8;
        r >>= 16;
        q |= (r & 0xff);

        //	Average over number of images frames with a non-background pixel in this location.
        //  Note that we sum in complement space, so background is zero.
        //				if(i>=navg)
        //				nfg[j] -= fghist[im][j];
        //			nfg[j] += (fghist[im][j] = (q==-1) ? 0 : 1);
        //
        //				// If all pixels in history were background, this is easy...
        //				if(nfg[j]==0)
        //					q = -1;
        //
        //				else {
        //
        //					if(i>=navg) sum[k]-=hist[im][k];
        //					hist[im][k] = ~(p&0xff);
        //					sum[k] += hist[im][k];
        //					if(i>=navg)
        //						q += ~(((sum[k]/nfg[j])*3 + hist[iim][k])>>2);
        //					else if(i>=navg/2)
        //						q += ~(sum[k]/nfg[j] + hist[i-navg/2][k])>>1;
        //					else
        //						q += ~(sum[k]/nfg[j]);
        //					k++; q<<=8; p>>=8;
        //
        //					if(i>=navg) sum[k]-=hist[im][k];
        //					hist[im][k] = ~(p&0xff);
        //					sum[k] += hist[im][k];
        //					if(i>=navg)
        //						q += ~(((sum[k]/nfg[j])*3 + hist[iim][k])>>2);
        //				else if(i>=navg/2)
        //				q += ~((sum[k]/nfg[j] + hist[i-navg/2][k])>>1);
        //			else
        //				q += ~(sum[k]/nfg[j]);
        //			k++; q<<=8; p>>=8;
        //
        //					if(i>=navg) sum[k]-=hist[im][k];
        //					hist[im][k] = ~(p&0xff);
        //					sum[k] += hist[im][k];
        //					if(i>=navg)
        //						q += ~(((sum[k]/nfg[j])*3 + hist[iim][k])>>2);
        //					else if(i>=navg/2)
        //						q += ~((sum[k]/nfg[j] + hist[i-navg/2][k])>>1);
        //					else
        //						q += ~(sum[k]/nfg[j]);
        //					k++;
        //				}

        pixelsi[j] = q;
      }

      bimage = new BufferedImage(w, h, BufferedImage.TYPE_3BYTE_BGR);
      bimage.setRGB(0, 0, w, h, pixelsi, 0, w);

      // save it as a file
      if (i >= navg) {
        try {
          ImageIO.write(bimage, "png", imageFile(0, ii + 1));
        } catch (Exception e) {
          throw new RuntimeException(e.getMessage());
        }
      }

      done(ii + 1);
      // System.err.println("Page " + i + " " + (System.currentTimeMillis()-t0)/1000.);

      if (terminated) {
        System.err.println("Prematurely terminated");
        for (File f : files) f.delete();
        tmpdir.delete();
        break;
      }
    }
  }
示例#28
0
 public void setImage(String filename) throws IOException {
   setImage(ImageIO.read(new File(filename)));
 }
  public void insertBuilding(int i, int j, int index) {

    if (!tiles[i][j].getValue().equals("")) {
      JOptionPane.showMessageDialog(null, "There is already a building here");
      return;
    }

    String temp = bb.get(index).getText();
    String[] parts = temp.split("-");

    int newQ = Integer.parseInt(parts[1]) - 1;
    if (newQ < 0) return;

    Building tB = bList.get(0);
    for (int b = 0; b < bList.size(); b++) {
      if (bList.get(b).getName().equals(parts[0])) {
        tB = bList.get(b);
        // System.out.println("here");
        break;
      }
    }

    Image image = null;
    BufferedImage buffered;
    try {
      image = ImageIO.read(new File("images/" + tB.getName().replace(" ", "_") + ".png"));
      System.out.println("Loaded image");
    } catch (IOException e) {
      System.out.println("Failed to load image");
    }
    buffered = (BufferedImage) image;

    for (int c = 0; c < tB.getQWidth(); c++) {
      for (int r = 0; r < tB.getQHeight(); r++) {
        if (i + c == 40 || j + r == 40) {
          JOptionPane.showMessageDialog(null, "Placing a building here would be out of bounds");
          return;
        }

        if (!tiles[i + c][j + r].getValue().equals("")) {
          JOptionPane.showMessageDialog(null, "Placing a building here will result to a overlap");
          return;
        }
      }
    }

    double w = buffered.getWidth() / tB.getQWidth();
    double h = buffered.getHeight() / tB.getQHeight();

    for (int c = 0; c < tB.getQWidth(); c++) {
      for (int r = 0; r < tB.getQHeight(); r++) {
        tiles[i + c][j + r].setBackground(new Color(51, 204, 51));
        tiles[i + c][j + r].setIcon(
            new ImageIcon(
                resize(
                    buffered.getSubimage((int) w * r, (int) h * c, (int) w, (int) h),
                    tiles[i + c][j + r].getWidth(),
                    tiles[i + c][j + r].getHeight())));

        String tValue = (c == 0 && r == 0) ? tB.getName() : i + "-" + j;
        // System.out.println(tValue);
        tiles[i + c][j + r].setValue(tValue);
      }
    }

    // tiles[i][j].setBackground(Color.BLUE);
    bb.get(index).setText(parts[0] + "-" + newQ);
  }
示例#30
0
  public erosion(String nombre) {

    imageName = nombre;

    // BufferedImage image2;
    String aux;

    // int ancho=image.getWidth();

    // BufferedImage image = ImageIO.read( new File( imageName ) );
    try {
      image = ImageIO.read(new File(imageName));
    } catch (IOException e) {
      System.out.println("image missing");
    }

    try {
      image2 = ImageIO.read(new File(imageName));
    } catch (IOException e) {
      System.out.println("image missing");
    }

    int k;
    int a;
    int b;
    int i;
    int j;

    int rojo;
    int verde;
    int azul;

    int promedio;
    try {
      int ancho, alto;
      alto = image.getHeight();
      ancho = image.getWidth();
      for (i = 0; i < ancho; i++) {
        for (j = 0; j < alto; j++) {
          k = image.getRGB(i, j);
          k = 0xFFFFFF + k;

          rojo = k / 0x10000;

          k = k % 0x10000;
          verde = k / 0x100;

          k = k % 0x100;
          azul = k;

          if (rojo < 0) rojo = 255 + rojo;
          if (verde < 0) verde = 255 + verde;
          if (azul < 0) azul = 255 + azul;

          promedio = azul + verde + rojo;
          promedio = promedio / 3;
          /*if(promedio<0)
          promedio=promedio+128;*/

          rojo = promedio;
          verde = promedio;
          azul = promedio;
          // printf("")

          if (promedio >= 128) promedio = 255;
          else promedio = 0;
          k = promedio + promedio * 0x100 + promedio * 0x10000;

          this.image.setRGB(i, j, k);
        }
      }
    } catch (Exception e) {
      System.out.printf("n");
    }
    //
    try {
      int ancho, alto;
      alto = image2.getHeight();
      ancho = image2.getWidth();
      for (i = 0; i < ancho; i++) {
        for (j = 0; j < alto; j++) {
          k = image2.getRGB(i, j);
          k = 0xFFFFFF + k;

          rojo = k / 0x10000;

          k = k % 0x10000;
          verde = k / 0x100;

          k = k % 0x100;
          azul = k;

          if (rojo < 0) rojo = 255 + rojo;
          if (verde < 0) verde = 255 + verde;
          if (azul < 0) azul = 255 + azul;

          promedio = azul + verde + rojo;
          promedio = promedio / 3;
          /*if(promedio<0)
          promedio=promedio+128;*/

          rojo = promedio;
          verde = promedio;
          azul = promedio;
          // printf("")

          k = promedio + promedio * 0x100 + promedio * 0x10000;

          this.image2.setRGB(i, j, k);
        }
      }
    } catch (Exception e) {
      System.out.printf("n");
    }

    //
    try {
      int ancho, alto;
      alto = image.getHeight();
      ancho = image.getWidth();
      for (i = 0; i < ancho; i++) {
        for (j = 0; j < alto; j++) {
          k = image.getRGB(i, j);
          k = 0xFFFFFF + k;

          rojo = k / 0x10000;

          k = k % 0x10000;
          verde = k / 0x100;

          k = k % 0x100;
          azul = k;

          if (rojo < 0) rojo = 255 + rojo;
          if (verde < 0) verde = 255 + verde;
          if (azul < 0) azul = 255 + azul;

          /*promedio=azul+verde+rojo;
          promedio=promedio/3;
          /*if(promedio<0)
           promedio=promedio+128;*/

          if (i < ancho - 2) {
            if (rojo >= 128) {
              k = image.getRGB(i + 1, j);
              k = 0xFFFFFF + k;

              rojo = k / 0x10000;

              k = k % 0x10000;
              verde = k / 0x100;

              k = k % 0x100;
              azul = k;

              if (rojo < 0) rojo = 255 + rojo;
              if (verde < 0) verde = 255 + verde;
              if (azul < 0) azul = 255 + azul;

              if (rojo >= 128) {
                k = image.getRGB(i + 2, j);
                k = 0xFFFFFF + k;

                rojo = k / 0x10000;

                k = k % 0x10000;
                verde = k / 0x100;

                k = k % 0x100;
                azul = k;

                if (rojo < 0) rojo = 255 + rojo;
                if (verde < 0) verde = 255 + verde;
                if (azul < 0) azul = 255 + azul;
                if (rojo < 128) {
                  k = 0;
                  this.image2.setRGB(i, j, k);
                  this.image2.setRGB(i + 1, j, k);
                  this.image2.setRGB(i + 2, j, k);
                }
              }

            } else {
              k = rojo + rojo * 0x100 + rojo * 0x10000;
              this.image2.setRGB(i, j, k);
            }
          }
        }
      }
    } catch (Exception e) {
      System.out.printf("n");
    }
    //

    /*else if(l==4)
    posterizacion();*/

    // Toolkit tool = Toolkit.getDefaultToolkit();
    // image = tool.getImage(imageName);

    // dialogo.setLocationRelativeTo(f);

  }