0
/**
 * Created on Sep 3, 2012
 * @author cskim -- hufs.ac.kr, Dept of CSE
 * Copy Right -- Free for Educational Purpose
 */
package assignment_01;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

/**
 * @author cskim
 *
  */


 public class NxNImageLabel extends JFrame implements ActionListener { ///////

private JPanel contentPane;

private static final int PROWS = 16; /////////
private static final int PSIZE = PROWS*PROWS;
private ImageIcon[] btnOneImage = new ImageIcon[PSIZE];//////
 private BufferedImage[] imageData = new BufferedImage[PSIZE];///////

private JButton[] tiles = new JButton[PSIZE]; /////////////////
private BufferedImage tileImage = null;

int scrHeight = 0;
int scrWidth = 0;
int bwidth = 0;
int bheight = 0;
/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            try {
                NxNImageLabel frame = new NxNImageLabel();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public NxNImageLabel() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 500, 500);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(new GridLayout(PROWS, PROWS, 0, 0));
    initialize();
}



void initialize(){
    scrHeight = this.getHeight();
    scrWidth = this.getWidth();
    //System.out.println("w="+scrWidth+" h="+scrHeight);
    try {
        tileImage = ImageIO
                .read(getClass().getResource("/images/dambee.jpg"));/////
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    int pwidth = tileImage.getWidth()/PROWS;
    int pheight =  tileImage.getHeight()/PROWS;
    bwidth = scrWidth/PROWS;
    bheight = scrHeight/PROWS;

    for (int i=0; i<PROWS; ++i){
        for (int j=0; j<PROWS; ++j){
         imageData[PROWS*i+j] = 
           tileImage.getSubimage(j*pwidth, i*pheight, pwidth, pheight);
        }
     }

    //////////////////////////////////////////////////////
    for(int i=0;i<PSIZE;++i){
      tiles[i] = new JButton();
      tiles[i].setIcon(new ImageIcon(imageData[i]));
      tiles[i].addActionListener(this);///////
      contentPane.add(tiles[i]);
    }//end of actionperformed

    }
    //////////////////////////////////////////////////////

  /*  ImageIcon tileIcon = new ImageIcon(tileImage.getScaledInstance(bwidth, bheight, Image.SCALE_SMOOTH));
    for (int i=0; i<PSIZE; ++i){
        tiles[i] = new JButton(); ///////
        tiles[i].setIcon(tileIcon);
        tiles[i].addActionListener(this);///////
        contentPane.add(tiles[i]);
    }*/


public int clickCount = 0;/////
@Override
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    JButton button = (JButton) e.getSource();
      BufferedImage imageData2 = (BufferedImage) ((ImageIcon)button.getIcon()).getImage();
      Color bcol = getAverageColor(imageData2);
      button.setIcon(new ImageIcon(OneColorBufferedImage.getBufferedImage(bwidth, bheight, bcol)));

        clickCount++;
        if (clickCount % 2 == 0) {
            //button.setIcon(new ImageIcon(OneColorBufferedImage.getBufferedImage(bwidth, bheight, bcol)));
            button.setIcon(new ImageIcon(OneImageButton.class.getResource("/images/dambee.jpg")));
        } else {
            button.setIcon(new ImageIcon(OneImageButton.class.getResource("/images/kiss.jpg")));
        }
        System.out.println(clickCount);

}
 Color getAverageColor(BufferedImage tile){
      int twidth = tile.getWidth();
      int theight =  tile.getHeight();
      double pixSize = twidth*theight;
      double sumRed = 0;
      double sumGreen = 0;
      double sumBlue = 0;
      Color pixColor = null;
      for (int i=0; i<theight; ++i){
       for (int j=0; j<twidth; ++j){
        pixColor = new Color(tile.getRGB(i,j));
        sumRed += pixColor.getRed();
        sumGreen += pixColor.getGreen();
        sumBlue += pixColor.getBlue();
       }
      }
      int avgRed = (int)(sumRed/pixSize);
      int avgGreen = (int)(sumGreen/pixSize);
      int avgBlue = (int)(sumBlue/pixSize);
      return new Color(avgRed, avgGreen, avgBlue);
   }
  }

I am trying to make 16x16 image label with clickable jbutton. If I click once, it should be changed mosaic image and then click twice, it should be changed original image and click three times it should be returned mosaic image. I have trouble in public void actionPerformed function, if else part. I think that if part is corrected but I don't know how to complete else part. Can anyone help me?

Anptk
  • 1,125
  • 2
  • 17
  • 28
Jo Jay
  • 123
  • 1
  • 3
  • 14
  • what trouble do you have? – Stultuske Oct 05 '15 at 07:00
  • I edited!! I don't know how to complete else statement... – Jo Jay Oct 05 '15 at 07:04
  • 1
    I'm afraid StackOverflow is not designed to do your homework. What you need to do is to narrow your problem down to a specific question that can be useful for others. "how to complete else statement" is hardly valuable for anyone but you. – alf Oct 05 '15 at 07:08

2 Answers2

2

Maybe replace the if/else with a ternary:

String imgUrl = clickCount % 2 == 0 ? "/images/dambee.jpg" : "/images/kiss.jpg";
button.setIcon(new ImageIcon(OneImageButton.class.getResource(imgUrl)));

The ternary operator (? and :) can be understood pretty much through the English words then and else.

So the right hand side of the first line reads "Does clickCount % 2 equal 0? If so, return "/images/dambee.jpg", else return "/images/kiss.jpg".

You can also insert a couple of line breaks into line one, for further clarity:

String imgUrl = clickCount % 2 == 0
    ? "/images/dambee.jpg"
    : "/images/kiss.jpg";

I think either way is fine, and both preferable to the if/else solution. After all, the assigning of an icon happens in both logical branches - it's just the particular url that is dependent on the clickCount.

I remember being a bit confused by the ternary operator when I started out programming, so it's perfectly fine to feel a bit uncomfortable with it at first. But it's probably a good idea to get into the habit of using it, as you're bound to see it many times throughout your days as a coder :)

Christofer Ohlsson
  • 3,097
  • 4
  • 39
  • 56
  • 1
    compact and neat code...gud +1..but i think you must have to write little explanation OP is a beginner.. – SSH Oct 05 '15 at 07:10
0

you should keep click counter for all buttons seperately. so define a click counter array.

private int[] btnClicks = new int[PSIZE];//////

and then, you should find which button is clicked in actionperformed

public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    JButton button = (JButton) e.getSource();
.
.
for(int i=0;i<PSIZE;++i){
  if (tiles[i] == button){
   btnClicks[i] ++;
   if (btnClicks[i]t % 2 == 0) {
            button.setIcon(new ImageIcon(OneImageButton.class.getResource("/images/dambee.jpg")));
        } else {
            BufferedImage img = ImageIO.read(...); // learn how to load images from resource. "/images/kiss.jpg"
            int w = button.getWidth();
            int h = button.getHeight();
            img = img.getSubimage(w*(i/16), h*(i%16), w, h);
            button.setIcon(img);
        }

    }
  }
}

ref: How to draw part of a large BufferedImage?

Community
  • 1
  • 1
Adem
  • 9,402
  • 9
  • 43
  • 58
  • oh... sorry it worked!!!! thanks!!! – Jo Jay Oct 05 '15 at 09:30
  • can i ask one more thing? if i wanna make original image with chucked size in else statement, how can I do? – Jo Jay Oct 05 '15 at 09:31
  • I edited my code. you should cut image for button, and use it. read reference link that how you can cut image. I did not try this code, calculation might need some minor update – Adem Oct 05 '15 at 12:52