2d icon arrays JAVA and printing out in JOptionpane box - java

How would I create a 2d icon array and print it out in a JOptionPane box. so Far I have this, but when I print it out it shows a bunch of BlockEmpty.png
public class iconarray{
public static void main (String [] args)
{
Icon blockempty = new ImageIcon("BlockEmpty.png");
Icon Board [] [] = new Icon [8] [8];
String GameBoard = "";
for (int count2 = 2; count2 <= 7; count2++)
{
for (int count3 = 1; count3 <= 7; count3++)
{
Board[count2][count3] = blockempty;
}
}
for (int count2 = 2; count2 <= 7; count2++)
{
for (int count3 = 1; count3 <= 7; count3++)
{
GameBoard = GameBoard + Board[count2][count3];
}
GameBoard = GameBoard + "\n";
}
JOptionPane.showMessageDialog(null, "", "Connect 4", JOptionPane.PLAIN_MESSAGE, blockempty);
}
}

In order to display a Icon or Image, you first need some way to render it. Icons and Images don't have the means to render them selves (per se), but require another component that can render them.
Something else a lot of people forget, is JOptionPane is capable of display components.
For example:
Icon brick = new ImageIcon(BoardOption.class.getResource("/images.jpg"));
JPanel wall = new JPanel(new GridLayout(8, 8, 0, 0));
JLabel bricks[][] = new JLabel[8][8];
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
bricks[y][x] = new JLabel(brick);
wall.add(bricks[y][x]);
}
}
JOptionPane.showMessageDialog(null, wall, "Another brick in the wall", JOptionPane.PLAIN_MESSAGE, null);
Take a look at How to use icons for more details.

Related

How to get the index of label mouse clicked in JLabel [ ] [ ]?

I've got a two dimension array of JLabel components and I want to get the place where the mouse clicked in the label like this.
Jlabel [x] [y] // I want this x & y
How should I do that?
I've tried this but I get nothing!
new MouseAdapter(){
public void mousePressed(MouseEvent e){
int a=e.getX();
int b=e.getY();
MainBoard.ML.label=MainBoard.disk1[a][b];
Color c=MainBoard.ML.label.getForeground();
if(color==1)
MainBoard.ML.label.setForeground(Color.black);
else
MainBoard.ML.label.setForeground(Color.white);
new Play(a,b,color);
new Player2(r);
MainBoard.disk1[a][b].addMouseListener(new ML1(a,b));
}
};
I want to get the x & y index of the label array.
Untested and uncompiled code to locate x and y you are seeking is below.
Note that method getX() of class MouseEvent gets the location of the mouse pointer on the computer screen and not the x from your array. Similarly for method getY(). That's why you get nothing.
In the below code I add the same MouseListener to all the JLabels.
The MouseEvent contains the JLabel that the mouse was clicked on and method getSource() of class MouseEvent returns it. Then you need to iterate through your array of JLabels and see which one matches the MouseEvent source.
int rows = // number of rows in 2D array
int cols = // number of cols in 2D array
final JLabel[][] labels = new JLabel[rows][cols]
MouseListener ml = new MouseAdapter() {
public void mousePressed(MouseEvent me) {
Object src = me.getSource();
int x = -1;
int y = -1;
for (int i = 0; i < labels.length(); i++) {
for (int j = 0; j < labels[i].length; j++) {
if (src == labels[i][j]) {
x = i;
y = j;
break;
}
}
if (x >= 0) {
break;
}
}
if (x > 0) {
System.out.printf("JLabel[%d][%d] was clicked.%n", x, y);
}
else {
System.out.println("Could not find clicked label.");
}
}
}
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
labels[row][col] = new JLabel(row + "," + col);
labels[row][col].addMouseListener(ml);
}
}

Cannot find symbol - method setColor(java.awt.Color)?

I am attempting to create a new color palette for an image turned to gray scale, and then apply the palette to the gray scale image. I began the method that I wanted to use to apply the palette, but I ran into the error mentioned in the title. I used "java.awt.Color" already in my code, so I am not sure why I am getting the error. Also, as you will see, I placed a color inside the parenthesis.
/**
* This program takes an image, converts it to grayscale, and uses a color palette to create new colors for the image.
*
* #author Dylan Hubbs
* #version 08/02/16
*/
import java.awt.Color ;
class ColorPalette
{
public void grayscaleEffect(Picture pictureObj)
{
int redValue = 0; int greenValue = 0; int blueValue = 0;
Pixel grayscaleTargetPixel = new Pixel(pictureObj, 0,0);
Color grayscalePixelColor = null;
for(int y=0; y < pictureObj.getHeight(); y++)
{
for(int x = 0; x < pictureObj.getWidth(); x++)
{
grayscaleTargetPixel = pictureObj.getPixel(x,y);
grayscalePixelColor = grayscaleTargetPixel.getColor(); //gets the color of the target pixel
grayscalePixelColor = new Color((grayscaleTargetPixel.getRed() + grayscaleTargetPixel.getGreen() + grayscaleTargetPixel.getBlue()) / 3, (grayscaleTargetPixel.getRed() + grayscaleTargetPixel.getGreen() + grayscaleTargetPixel.getBlue()) / 3, (grayscaleTargetPixel.getRed() + grayscaleTargetPixel.getGreen() + grayscaleTargetPixel.getBlue()) / 3);
grayscaleTargetPixel.setColor(grayscalePixelColor); //sets the new color of the target pixel
}//end of the inner for loop
}//end of the outer for loop
pictureObj.explore(); //explore the Picture object which is now the altered image
pictureObj.write("grayscaleWashingtonMonument.jpg"); //write the altered Picture object to a new file
pictureObj.show();
}
public void paletteEffect(Picture pictureObj)
{
int redValue = 0; int greenValue = 0; int blueValue = 0;
Pixel paletteTargetPixel = new Pixel(pictureObj, 0,0);
Color palettePixelColor = null;
Color [] palette = {Color.RED, Color.BLUE, Color.CYAN, Color.GREEN, Color.YELLOW, Color.GRAY, Color.PINK, Color.ORANGE};
for(int y=0; y < pictureObj.getHeight(); y++)
{
for(int x = 0; x < pictureObj.getWidth(); x++)
{
paletteTargetPixel = pictureObj.getPixel(x,y);
palettePixelColor = paletteTargetPixel.getColor();
if(paletteTargetPixel.getRed() >= 1 && paletteTargetPixel.getRed() <= 31)
palettePixelColor.setColor(palette[0]);
else if(paletteTargetPixel.getRed() >= 32 && paletteTargetPixel.getRed() <= 62)
palettePixelColor.setColor(palette[1]);
else if(paletteTargetPixel.retRed() >= 63 && paletteTargetPixel.getRed() <=93)
palettePixelColor.setColor(palette[2]);
}
}
}
}
public class ColorPaletteTester
{
public static void main(String[] args)
{
Picture pictureObj = new Picture("washingtonmonument.jpg"); //creates a new Picture object representing the file in the parameter list
pictureObj.explore();
ColorPalette cp = new ColorPalette();
cp.grayscaleEffect(pictureObj);
cp.paletteEffect(pictureObj);
}
}
So, the error is coming at
palettePixelColor.setColor(palette[0]);
Does anyone know why this would be happening?
palettePixelColor is declared as java.awt.Color, which happens to be an immutable class with no setters. Depending on what Pixel is, it may have such a method.
You are probably trying to do something like
palettePixelColor = palette[0];
or
paletteTargetPixel.setColor(palette[0]);

Java half of JButtons stop working in JPanel

I'm trying to make a unit conversion program using Jbuttons in a jpanel. So far when I run the program however, the first window pops up, I select "Length". Now, it shows 8 buttons on each side, after selecting one of those, half of the buttons will no longer work, only the right column of each side works.
public class Gui extends JFrame {
private JButton Subject[] = new JButton[8];
private String SubjNames[] = {"Length", "Mass", "Currency", "Temperature", "Time", "Speed", "Data", "Cooking"};
private JButton Length1[] = new JButton[8];
private JButton Length2[] = new JButton[8];
private String LengNames[] = {"inches", "feet", "yards", "miles", "millimeters", "centimeters", "meters", "kilometers"};
private JTextField convertedFrom;
private JTextField amountFrom;
private JTextField convertedTo;
private JTextField amountTo;
private String from;
private String CTo;
private String ATo;
private int SubjectLocX = 40;
private int SubjectLocY = 50;
private int Length1LocX = 40;
private int Length1LocY = 150;
private int Length2LocX = 330;
private int Length2LocY = 150;
private int t = 0;
public Gui (){
super("Converter");
setLayout(null);
System.out.println("yes");
for (int i = 0; i<8; i++) {
Subject[i] = new JButton(SubjNames[i]);
Subject[i].setLocation(SubjectLocX,SubjectLocY);
Subject[i].setSize(200,50);
add(Subject[i]);
if (i < 3) {
SubjectLocX = 40;
SubjectLocY += 100;
} else if (i == 3) {
SubjectLocX = 330;
SubjectLocY = 50;
} else if (i > 3) {
SubjectLocY += 100;
}
}
HandlerClass handler = new HandlerClass();
for (int i = 0; i<8; i++) {
Subject[i].addActionListener(handler);
}
for (int i = 0; i<8; i++) {
Length1[i] = new JButton(SubjNames[i]);
Length2[i] = new JButton(SubjNames[i]);
}
for (int i = 0; i<8; i++) {
Length1[i].addActionListener(handler);
Length2[i].addActionListener(handler);
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600,500);
setLocation(400,200);
setVisible(true);
}
public void Step2() {
for (int i = 0; i<8; i++) {
remove(Subject[i]);
}
for (int i = 0; i<8; i++) {
remove(Length1[i]);
remove(Length2[i]);
}
HandlerClass handler = new HandlerClass();
convertedFrom = new JTextField(from, 20);
convertedFrom.setEditable(false);
convertedFrom.setLocation(40,50);
convertedFrom.setSize(200,30);
add(convertedFrom);
convertedTo = new JTextField(CTo, 20);
convertedTo.setEditable(false);
convertedTo.setLocation(330,50);
convertedTo.setSize(200,30);
add(convertedTo);
amountFrom = new JTextField("amount", 20);
amountFrom.setLocation(40,100);
amountFrom.setSize(200,30);
add(amountFrom);
amountTo = new JTextField(ATo, 20);
amountTo.setEditable(false);
amountTo.setLocation(330,100);
amountTo.setSize(200,30);
add(amountTo);
for (int i = 0; i<8; i++) {
Length1[i].setLocation(Length1LocX, Length1LocY);
Length1[i].setSize(90, 50);
add(Length1[i]);
if (i < 3) {
Length1LocX = 40;
Length1LocY += 100;
} else if (i == 3) {
Length1LocX = 150;
Length1LocY = 150;
} else if (i > 3) {
Length1LocY += 100;
}
Length2[i].setLocation(Length2LocX, Length2LocY);
Length2[i].setSize(90, 50);
add(Length2[i]);
if (i < 3) {
Length2LocX = 330;
Length2LocY += 100;
} else if (i == 3) {
Length2LocX = 440;
Length2LocY = 150;
} else if (i > 3) {
Length2LocY += 100;
}
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600,600);
setLocation(400,200);
setVisible(true);
}
private class HandlerClass implements ActionListener {
public void actionPerformed(ActionEvent event) {
for (int i = 0; i<8; i++) {
if (event.getSource() == Length1[i]) {
from = event.getActionCommand();
}
if (event.getSource() == Length2[i]) {
CTo = event.getActionCommand();
}
}
Step2();
}
}
}`
(Note: I didn't include imports or main method in code above, but is in real program). The constructor creates the JButtons and actionlisteners. The step2() method is where the Buttons size and location and window is created and recreated. (Length1 and Length2 JButtons are what is messing up here). I don't know why half the buttons stop working after the second time though.
When you select one of the 16 buttons, method Step2() will be called again and this will relocate your buttons, without resetting your locationvalues. When you reset the locationvariables in the Step2() method, the buttons will work. Like this:
step2()
Length1LocX = 40;
Length1LocY = 150;
Length2LocX = 330;
Length2LocY = 150;
[rest of method....]
But off course you don't want to call step2() every time a button is clicked.....
You are creating and adding JTextField UI items, and adding them multiple times at the same location, and never removing them:
convertedFrom
amountFrom
convertedTo
amountTo
These will be stacked on top or underneath previous ones; the user may add text to the top ones and the program may write to or read from the obscured ones beneath, which will stop the program from functioning as intended.

Java checkerboard, odd/even % 2 panel

I have successfully got a checkerboard to be put together using colored panels, but only when the user will input odd numbers for the rows and columns. Otherwise when inputing even numbers it just shows alternating colored columns. I'm struggling to figure out how to write a short segment that checks to see if it's odd or even by using the %2=0, with the result of even changing the color. Below is my code. Thanks, and take it easy on me I'm very new to programming! :-)
Also, I've created a separate ColorPanel class to build the colored panel, and then pull into into my main program. I didn't bother putting that code below.
import javax.swing.*;
import java.awt.*;
public class Checkerboard extends JPanel{
public static void main(String[] args) {
JFrame chBoard = new JFrame();
chBoard.setTitle("Checkerboard");
chBoard.setSize(800,800);
chBoard.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String inputStr = JOptionPane.showInputDialog("Number of rows", "5");
if (inputStr == null) return;
int row = Integer.parseInt(inputStr);
inputStr = JOptionPane.showInputDialog("Number of columns", "5");
if (inputStr == null) return;
int col = Integer.parseInt(inputStr);
Container pane = chBoard.getContentPane();
pane.setLayout(new GridLayout(row, col));
Color BoxColor = Color.red;
for ( int counter = 1; counter <= row * col; counter++ )
{
if (BoxColor == Color.red)
BoxColor = Color.black;
else
BoxColor = Color.red;
ColorPanel panel = new ColorPanel(BoxColor);
pane.add(panel);
}
chBoard.setVisible(true);
}
}
Change your loop to:
for ( int x = 0; x < row; x++ ) {
for(int y = 0; y < col; y++) {
if((x + y)%2 == 0) {
BoxColor = Color.red;
} else {
BoxColor = Color.black;
}
...
}
}
Like I said, I'm new to programming but I'm really enjoying the learning experience. I hope this helps other people in their learning experience.
Anyways, I suppose I created more work for myself with the separate ColorPanel class. So instead of creating a separate ColorPanel class to build the colored panel, I just changed it to use the preexisting JPanel class to create the panel inside the main program. So instead of:
ColorPanel panel = new ColorPanel(BoxColor);
+ the ColorPanel class...
I put:
JPanel panel = new JPanel();
panel.setBackground(BoxColor);
within the main program and deleted the additional ColorPanel class.
Sorry for the redundancy, just wanting to explain myself clearly.
Also, thanks to Jason he really helped me figure out the idea of using the two
int x & y
to count the
row & col
and then add them together which enabled me to use the
%2=0
to figure out whether I was on the odd or even panel.
Hope this helps someone! :-)
Final code looks like this:
import javax.swing.*;
import java.awt.*;
public class Checkerboard extends JPanel{
public static void main(String[] args) {
JFrame chBoard = new JFrame();
chBoard.setTitle("Checkerboard");
chBoard.setSize(800,800);
chBoard.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String inputStr = JOptionPane.showInputDialog("Number of rows", "5");
if (inputStr == null) return;
int row = Integer.parseInt(inputStr);
inputStr = JOptionPane.showInputDialog("Number of columns", "5");
if (inputStr == null) return;
int col = Integer.parseInt(inputStr);
Container pane = chBoard.getContentPane();
pane.setLayout(new GridLayout(row, col));
Color BoxColor = Color.red;
for ( int x = 0; x < row; x++ ) {
for(int y = 0; y < col; y++) {
if((x + y)%2 == 0) {
BoxColor = Color.red;}
else{
BoxColor = Color.black;}
JPanel panel = new JPanel();
panel.setBackground(BoxColor);
pane.add(panel);
}
chBoard.setVisible(true);
}
}
}

java Checker board issues

so i have this program that asks a user for a number of rows and columns and then makes it into a checker board but my issue is that it only works with odd numbers like if the user was to put in 9 and 9 again it would display a checkered board but if a even number is inputted it just shows columns of white and black
import javax.swing.*;
import java.awt.*;
public class Checkers {
public static void main(String[] args) {
JFrame theGUI = new JFrame();
theGUI.setTitle("Checkers");
String inputStr = JOptionPane.showInputDialog("Number of rows");
if (inputStr == null) return;
int rows = Integer.parseInt(inputStr);
inputStr = JOptionPane.showInputDialog("Number of Columns");
if (inputStr == null) return;
int cols = Integer.parseInt(inputStr);
theGUI.setSize(cols * 50 , rows * 50);
theGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container pane = theGUI.getContentPane();
pane.setLayout(new GridLayout(rows, cols));
for (int i = 1; i <= rows * cols ;i ++) {
if(i % 2 == 0){
ColorPanel panel = new ColorPanel(Color.white);
pane.add(panel);
}else{
ColorPanel panel = new ColorPanel(Color.black);
pane.add(panel);
}
}
theGUI.setVisible(true);
}
}
Your example identifies even numbers in a single loop. Instead, use nested loops to identify alternating tiles:
g.setColor(Color.lightGray);
…
for (int row = 0; row < h; row++) {
for (int col = 0; col < w; col++) {
if ((row + col) % 2 == 0) {
g.fillRect(col * TILE, row * TILE, TILE, TILE);
}
}
}
A complete example is seen here.

Categories

Resources