How To Scramble Image in Java - java

I found this source code from http://zetcode.com/tutorials/javagamestutorial/puzzle/
And I wanted to play around with it. It's a picture puzzle game, however when I run the program, it doesn't show up scrambled and I was wondering how will I go about this to get it scrambled? I'm still new to programming and I just wanted to play around with this to learn a bit. Thank you!
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Puzzle extends JFrame implements ActionListener {
private JPanel centerPanel;
private JButton button;
private JLabel label;
private Image source;
private Image image;
int[][] pos;
int width, height;
public Puzzle() {
pos = new int[][] {
{0, 1, 2},
{3, 4, 5},
{6, 7, 8},
{9, 10, 11}
};
centerPanel = new JPanel();
centerPanel.setLayout(new GridLayout(4, 4, 0, 0));
ImageIcon sid = new ImageIcon(Puzzle.class.getResource("icesid.jpg"));
source = sid.getImage();
width = sid.getIconWidth();
height = sid.getIconHeight();
add(Box.createRigidArea(new Dimension(0, 5)), BorderLayout.NORTH);
add(centerPanel, BorderLayout.CENTER);
for ( int i = 0; i < 4; i++) {
for ( int j = 0; j < 3; j++) {
if ( j == 2 && i == 3) {
label = new JLabel("");
centerPanel.add(label);
} else {
button = new JButton();
button.addActionListener(this);
centerPanel.add(button);
image = createImage(new FilteredImageSource(source.getSource(),
new CropImageFilter(j*width/3, i*height/4,
(width/3)+1, height/4)));
button.setIcon(new ImageIcon(image));
}
}
}
setSize(325, 275);
setTitle("Puzzle");
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new Puzzle();
}
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
Dimension size = button.getSize();
int labelX = label.getX();
int labelY = label.getY();
int buttonX = button.getX();
int buttonY = button.getY();
int buttonPosX = buttonX / size.width;
int buttonPosY = buttonY / size.height;
int buttonIndex = pos[buttonPosY][buttonPosX];
if (labelX == buttonX && (labelY - buttonY) == size.height ) {
int labelIndex = buttonIndex + 3;
centerPanel.remove(buttonIndex);
centerPanel.add(label, buttonIndex);
centerPanel.add(button,labelIndex);
centerPanel.validate();
}
if (labelX == buttonX && (labelY - buttonY) == -size.height ) {
int labelIndex = buttonIndex - 3;
centerPanel.remove(labelIndex);
centerPanel.add(button,labelIndex);
centerPanel.add(label, buttonIndex);
centerPanel.validate();
}
if (labelY == buttonY && (labelX - buttonX) == size.width ) {
int labelIndex = buttonIndex + 1;
centerPanel.remove(buttonIndex);
centerPanel.add(label, buttonIndex);
centerPanel.add(button,labelIndex);
centerPanel.validate();
}
if (labelY == buttonY && (labelX - buttonX) == -size.width ) {
int labelIndex = buttonIndex - 1;
centerPanel.remove(buttonIndex);
centerPanel.add(label, labelIndex);
centerPanel.add(button,labelIndex);
centerPanel.validate();
}
}
}

Create each Icon and add the Icon to an ArrayList.
Then you can use the Collections.shuffle(...) method
Then iterate through the shuffled ArrayList and create your buttons add add the Icons to each button.
Edit:
Simple example showing the concept:
import java.awt.*;
import java.util.*;
import javax.swing.*;
public class SSCCE extends JPanel
{
public SSCCE()
{
setLayout( new GridLayout(3, 4) );
ArrayList<Integer> numbers = new ArrayList<Integer>();
for (int i = 0; i < 12; i++)
numbers.add( new Integer(i) );
Collections.shuffle(numbers);
for (int i = 0; i < 12; i++)
add( new JLabel( "" + numbers.get(i) ) );
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new SSCCE());
frame.setLocationByPlatform( true );
frame.setSize(300, 300);
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}

Related

How to overlap images in a JFrame

I can't get two images to overlap each other in a JFrame. I have tried using one JPanel and two JPanels, and nothing has worked. I have looked into trying out JLayeredPane(s), but to no avail. I have lots of classes that interact so I don't know if showing my code will help, but here is my not-fully-implemented code:
import javax.swing.JLabel;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLayeredPane;
import javax.swing.ImageIcon;
import java.awt.Graphics2D;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import java.io.IOException;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
public class MazeDisplay implements KeyListener
{
static JFrame window;
static JPanel backPanel, userPanel;
JLabel user, cpu, maze1, maze2;
User u;
public MazeDisplay(String x, Cell[][] maize1, Cell[][] maize2) throws IOException
{
maze1 = new JLabel(new ImageIcon(createMazeImage(maize1)));
maze2 = new JLabel(new ImageIcon(createMazeImage(maize2)));
user = new JLabel(new ImageIcon("user.png"));
cpu = new JLabel(new ImageIcon("cpu.png"));
u = new User(maize1);
window = new JFrame(x);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(400, 400, 986, 509);
backPanel = (JPanel) window.getContentPane();
backPanel.setLayout(null);
maze1.setBounds(0, 0, 480, 480);
maze2.setBounds(500, 0, 480, 480);
backPanel.add(maze1);
backPanel.add(maze2);
userPanel = new JPanel(null);
user.setBounds(0, 0, 30, 30);
cpu.setBounds(500, 0, 30, 30);
userPanel.add(user);
userPanel.add(cpu);
window.add(userPanel);
window.setResizable(false);
window.setVisible(true);
}
public void keyPressed(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
public boolean isLegal(int dir)
{
boolean ret = false; Cell[][] maze = u.getMaize();
if(0 <= u.xPos() && u.xPos() < maze.length && 0 <= u.yPos() && u.yPos() < maze.length)
{
if(dir == 0) ret = (maze[u.xPos()][u.yPos()].isOpen(dir) && maze[u.xPos()][u.yPos()-1].isOpenO(dir));
else if(dir == 1) ret = (maze[u.xPos()][u.yPos()].isOpen(dir) && maze[u.xPos()+1][u.yPos()].isOpenO(dir));
else if(dir == 2) ret = (maze[u.xPos()][u.yPos()].isOpen(dir) && maze[u.xPos()][u.yPos()+1].isOpenO(dir));
else if(dir == 3) ret = (maze[u.xPos()][u.yPos()].isOpen(dir) && maze[u.xPos()-1][u.yPos()].isOpenO(dir));
}
return ret;
}
public static BufferedImage createMazeImage(Cell[][] maze) throws IOException
{
BufferedImage[][] iMaze = new BufferedImage[maze.length][maze.length];
for(int i = 0; i < iMaze.length; i++)
for(int j = 0; j < iMaze.length; j++)
{
String cellDir = maze[i][j] + ".png";
iMaze[i][j] = new BufferedImage(30, 30, BufferedImage.TYPE_INT_RGB);
Graphics2D icon = iMaze[i][j].createGraphics();
icon.drawImage(ImageIO.read(new File(cellDir)), 0, 0, null);
}
int xOff = 0, yOff = 0;
BufferedImage mazeImage = new BufferedImage(maze.length * 30, maze.length * 30, BufferedImage.TYPE_INT_RGB);
Graphics2D g = mazeImage.createGraphics();
for(int r = 0; r < iMaze.length; r++)
{
for(int c = 0; c < iMaze.length; c++)
{
g.drawImage(iMaze[r][c], xOff, yOff, null);
yOff += 30;
}
yOff = 0;
xOff += 30;
}
return mazeImage;
}
public static void main(String[] args) throws IOException
{
MazeGen g = new MazeGen(16);
MazeGen h = new MazeGen(16);
MazeDisplay m = new MazeDisplay("Maze Game", g.getMaze(), h.getMaze());
}
}
Edit: My apologies for being so vague, I was extremely tired and irritated at the time. Even though I was vague, the help was very much appreciated, as I got it working using GridBagLayout as MadProgrammer suggested.
So, this is a really quick example.
It makes use of a GridBagLayout to allow two components to occupy the same space at the same time. It then uses a simple Timer to update the location of the player, to demonstrate that the basic concept works.
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
public class TestPane extends JPanel {
private JLabel player;
public TestPane() throws IOException {
BufferedImage tileImg = ImageIO.read(getClass().getResource("Tile.jpg"));
BufferedImage playerImg = ImageIO.read(getClass().getResource("Mario.png"));
Icon tileIcon = new ImageIcon(tileImg);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
player = new JLabel(new ImageIcon(playerImg));
gbc.gridx = 0;
gbc.gridy = 0;
add(player, gbc);
for (int row = 0; row < 10; row++) {
for (int col = 0; col < 10; col++) {
gbc.gridx = col;
gbc.gridy = row;
add(new JLabel(tileIcon), gbc);
}
}
Timer timer = new Timer(500, new ActionListener() {
private int x = 0;
private int y = 0;
#Override
public void actionPerformed(ActionEvent e) {
x++;
if (x > 9) {
x = 0;
y++;
}
if (y > 9) {
y = 0;
}
GridBagLayout layout = (GridBagLayout) getLayout();
GridBagConstraints gbc = layout.getConstraints(player);
gbc.gridx = x;
gbc.gridy = y;
layout.setConstraints(player, gbc);
revalidate();
}
});
timer.start();
}
}
}
Because of the way that the API works, components are displayed in LIFO order, this means that the player component must be added first.
You could also combine this with a JLayeredPane which would give you control over the z-ordering of the components
Disclaimer...
While this solution does work, it's not very easy to maintain or manage. A better solution would be to follow a custom painting route, this will give you much more control over what is painted and when and where.
Take a look at Performing Custom Painting for some basic details
Layered panes should work fine if well-implemented, here is more information about it, how to use it and some examples and codes for it:
https://docs.oracle.com/javase/tutorial/uiswing/components/layeredpane.html

Drawing a game board in java

I am referencing this link, however this won't ultimately fix my problem (i.e I run my program from someone else's computer). How to deal with "java.lang.OutOfMemoryError: Java heap space" error (64MB heap size). Right now, I have a game board that has 10x10 squares, but I need to increase this to 100x100, but when I do, I get this error. What is the best way to increase my game board size while avoiding this error? Current output is below, Code should compile and run. Thanks!
GameBoard Class:
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.*;
public class GameBoard {
private final JPanel board = new JPanel(new BorderLayout(3, 3));
private JButton[][] c1squares = new JButton[10][10];
private JPanel c1Board, c2Board;
private final JLabel messagec1 = new JLabel("Player 1 Board");
JToolBar tool = new JToolBar();
Insets Margin = new Insets(0,0,0,0);
int squares = 10;
int space = 100;
ImageIcon icon = new ImageIcon(new BufferedImage(space, space, BufferedImage.TYPE_INT_ARGB));
GameBoard() {
initializeGui();
}
public final void initializeGui() {
board.setBorder(new EmptyBorder(5, 5, 5, 5));
tool.setFloatable(false);
board.add(tool, BorderLayout.PAGE_START);
tool.add(messagec1);
c1Board = new JPanel(new GridLayout(0, 10));
c1Board.setBorder(new LineBorder(Color.BLACK));
board.add(c1Board);
for (int i = 1; i < c1squares.length; i++) {
for (int j = 0; j < c1squares[i].length; j++) {
JButton b = new JButton();
b.setMargin(Margin);
b.setIcon(icon);
if ((j % 2 == 1 && i % 2 == 1) || (j % 2 == 0 && i % 2 == 0)) {
b.setBackground(Color.WHITE);
} else {
b.setBackground(Color.BLACK);
}
c1squares[j][i] = b;
}
}
for (int i = 1; i < squares; i++) {
for (int j = 0; j < squares; j++) {
c1Board.add(c1squares[j][i]);
}
}
public final JComponent getGui() {
return board;
}
public final JComponent getGui2() {
return board2;
}
}
BattleShipFinal Class:
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class BattleshipFinal {
public static void main(String[] args) {
GameBoard gb = new GameBoard();
JFrame frame = new JFrame("Battleship - Server");
frame.add(gb.getGui());
frame.setLocationByPlatform(true);
frame.setMinimumSize(frame.getSize());
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(900,900));
frame.setMinimumSize(new Dimension(900,900));
frame.setLocation(50,50);
frame.pack();
frame.setVisible(true);
}
}
In case you are curious, and to illustrate what people said in the comments, you could have a custom JPanel painting the squares.
If you ever need to respond to mouse events, add a MouseListener to your panel, which will take care of the selected square (haven't added that part, but the selected field inside the Square class is a hint).
I removed stuff from your code, just to demonstrate this painting part.
GameBoard :
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class GameBoard {
private JPanel board;
private final Square[][] c1squares = new Square[10][10];
GameBoard() {
initializeGui();
}
public final void initializeGui() {
for (int i = 0; i < c1squares.length; i++) {
for (int j = 0; j < c1squares[i].length; j++) {
Square square = new Square();
if ((j % 2 == 1 && i % 2 == 1) || (j % 2 == 0 && i % 2 == 0)) {
square.setBackground(Color.WHITE);
} else {
square.setBackground(Color.BLACK);
}
c1squares[i][j] = square;
}
}
board = new BoardPanel(c1squares);
board.setBorder(new EmptyBorder(5, 5, 5, 5));
}
public final JComponent getGui() {
return board;
}
private class BoardPanel extends JPanel {
Square[][] squares;
public BoardPanel(final Square[][] squares) {
this.squares = squares;
}
#Override
public void paintComponent(final Graphics g) {
super.paintComponent(g);
int width = getWidth();
int height = getHeight();
for (int i = 0; i < squares.length; i++) {
for (int j = 0; j < squares[i].length; j++) {
Square currentSquare = squares[i][j];
System.out.println("Managing square " + i + " " + j);
g.setColor(currentSquare.getBackground());
g.fillRect(i * width / squares.length, j * height / squares.length, width / squares.length,
height / squares.length);
}
}
}
}
private class Square {
boolean isSelected;
Color background;
public boolean isSelected() {
return isSelected;
}
public void setSelected(final boolean isSelected) {
this.isSelected = isSelected;
}
public Color getBackground() {
return background;
}
public void setBackground(final Color background) {
this.background = background;
}
}
}
BattleshipFinal :
import java.awt.Dimension;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class BattleshipFinal {
public static void main(final String[] args) {
GameBoard gb = new GameBoard();
JFrame frame = new JFrame("Battleship - Server");
JComponent board = gb.getGui();
frame.add(board);
frame.setLocationByPlatform(true);
//frame.setMinimumSize(frame.getSize());
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
//frame.setPreferredSize(new Dimension(100, 100));
board.setMinimumSize(new Dimension(100, 100));
board.setPreferredSize(new Dimension(100, 100));
frame.setMinimumSize(new Dimension(100, 100));
frame.setLocation(50, 50);
frame.pack();
frame.setVisible(true);
}
}
Okay, I figured out the solution for this. Here is the output:
The way I fixed this was by changing these lines of code:
private JButton[][] c1squares = new JButton[100][100];
int squares = 100;
int space = 1000;
c1Board = new JPanel(new GridLayout(0, 100));

How to reset the value within a class?

I tried to remodel a program that i found but i cant proceed
i want to create a reset/new game
i tried calling the class and
dispose the current output after clicking the button 'new game' and creating a new output resulting the class to return to default value.
but i cant make it work. Please help
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Puzzle_Act3 puzzle = new Puzzle_Act3();
puzzle.setVisible(true);
newGameBut.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
puzzle.dispose();
puzzle = new Puzzle_Act3(); //********************************************how to make this work
puzzle.setVisible(true); //********************************become new again
}
});
}
});
}
here is the full code
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
class MyButton extends JButton {
private boolean isLastButton;
public MyButton() {
super();
initUI();
}
public MyButton(Image image) {
super(new ImageIcon(image));
initUI();
}
private void initUI() {
isLastButton = false;
BorderFactory.createLineBorder(Color.LIGHT_GRAY);
addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));
}
#Override
public void mouseExited(MouseEvent e) {
setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
}
});
}
public void setLastButton() {
isLastButton = true;
}
public boolean isLastButton() {
return isLastButton;
}
}
public class Puzzle_Act3 extends JFrame {
private JPanel panel; // Init
private BufferedImage source;
private ArrayList<MyButton> buttons;
ArrayList<Point> solution = new ArrayList();
private Image image;
private MyButton lastButton;
private int width, height;
private final int DESIRED_WIDTH = 310;
private BufferedImage resized;
JPanel controlPanel;
JLabel display; //try init
static JButton newGameBut;
public Puzzle_Act3() {
initUI();
}
private void initUI() {
solution.add(new Point(0, 0));
solution.add(new Point(0, 1));
solution.add(new Point(0, 2));
solution.add(new Point(1, 0));
solution.add(new Point(1, 1));
solution.add(new Point(1, 2));
solution.add(new Point(2, 0));
solution.add(new Point(2, 1));
solution.add(new Point(2, 2));
solution.add(new Point(3, 0));
solution.add(new Point(3, 1));
solution.add(new Point(3, 2));
buttons = new ArrayList();
panel = new JPanel();
panel.setBorder(BorderFactory.createLineBorder(Color.ORANGE));
add(Box.createRigidArea(new Dimension(0, 25)), BorderLayout.NORTH);
panel.setLayout(new GridLayout(4, 3, 0, 0)); //setPanel();
//insert
newGameBut = new JButton("new game"); //new game/reset
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
display = new JLabel("move: "+ count);
controlPanel.add(display);
controlPanel.add(newGameBut);
this.setLayout(new BorderLayout());
this.add(controlPanel, BorderLayout.NORTH);
try {
source = loadImage();
int h = getNewHeight(source.getWidth(), source.getHeight());
resized = resizeImage(source, DESIRED_WIDTH, h,
BufferedImage.TYPE_INT_ARGB);
} catch (IOException ex) {
Logger.getLogger(Puzzle_Act3.class.getName()).log(
Level.SEVERE, null, ex);
}
width = resized.getWidth(null);
height = resized.getHeight(null);
add(panel, BorderLayout.CENTER);
for (int i = 0; i < 4; i++) { //column
for (int j = 0; j < 3; j++) { //row
image = createImage(new FilteredImageSource(resized.getSource(),
new CropImageFilter(j * width / 3, i * height / 4,
(width / 3), height / 4)));
MyButton button = new MyButton(image);
button.putClientProperty("position", new Point(i, j));
if (i == 3 && j == 2) {
lastButton = new MyButton();
lastButton.setBorderPainted(false);
lastButton.setContentAreaFilled(false);
lastButton.setLastButton();
lastButton.putClientProperty("position", new Point(i, j));
} else {
buttons.add(button);
}
}
}
Collections.shuffle(buttons);
buttons.add(lastButton);
for (int i = 0; i < 12; i++) {
MyButton btn = buttons.get(i);
panel.add(btn);
btn.setBorder(BorderFactory.createLineBorder(Color.gray));
btn.addActionListener(new ClickAction());
}
pack();
setTitle("Puzzle - ccuison");
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private int getNewHeight(int w, int h) {
double ratio = DESIRED_WIDTH / (double) w;
int newHeight = (int) (h * ratio);
return newHeight;
}
private BufferedImage loadImage() throws IOException {
BufferedImage bimg = ImageIO.read(new File("myArtWork.png"));
return bimg;
}
private BufferedImage resizeImage(BufferedImage originalImage, int width,
int height, int type) throws IOException {
BufferedImage resizedImage = new BufferedImage(width, height, type);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, width, height, null);
g.dispose();
return resizedImage;
}
int count;
private class ClickAction extends AbstractAction {
#Override
public void actionPerformed(ActionEvent e) { //Clicks
count = count+1;
display.setText("move: "+count);
System.out.println(count);
checkButton(e);
checkSolution();
}
private void checkButton(ActionEvent e) {
int lidx = 0;
for (MyButton button : buttons) {
if (button.isLastButton()) {
lidx = buttons.indexOf(button);
}
}
JButton button = (JButton) e.getSource();
int bidx = buttons.indexOf(button);
if ((bidx - 1 == lidx) || (bidx + 1 == lidx)
|| (bidx - 3 == lidx) || (bidx + 3 == lidx)) {
Collections.swap(buttons, bidx, lidx);
updateButtons();
}
}
private void updateButtons() {
panel.removeAll();
for (JComponent btn : buttons) {
panel.add(btn);
}
panel.validate();
}
}
private void checkSolution() {
ArrayList<Point> current = new ArrayList();
for (JComponent btn : buttons) {
current.add((Point) btn.getClientProperty("position"));
}
if (compareList(solution, current)) { //WIN
JOptionPane.showMessageDialog(panel, "Finished",
"Congratulation", JOptionPane.INFORMATION_MESSAGE);
Puzzle_Act3 puzzle = new Puzzle_Act3();
puzzle.dispose();
puzzle.setVisible(true);
}
}
public static boolean compareList(List ls1, List ls2) {
return ls1.toString().contentEquals(ls2.toString());
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Puzzle_Act3 puzzle = new Puzzle_Act3();
puzzle.setVisible(true);
newGameBut.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
puzzle.dispose();
puzzle = new Puzzle_Act3(); //********************************************how to make this work
puzzle.setVisible(true); //********************************become new again
}
});
}
});
}
}
Try to also include the properties of the previous class (that is, the one you're disposing) to the new class, in that way, the new class appears like the old one but with the default properties present!
Something like this would do for me!
public class Welcome {
static GUI run = new GUI ();
public static void main (String [] args) {
run.setPreferredSize(new Dimension(800, 500));
run.setResizable(false);
run.setVisible(true);
run.setLocation(250,150);
run.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
ImageIcon img = new ImageIcon("C:/Users/hp/documents/MyLogo.png");
run.setIconImage(img.getImage());
run.setTitle( "Pearl Math-Whiz");
run.pack();
}
then, for the reset button's actionlistener, do something like this
run.dispose();
GUI ran = new GUI();
ran.setPreferredSize(new Dimension(800, 500));
ran.setResizable(false);
ran.setVisible(true);
ran.setLocation(250,150);
ran.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
ImageIcon img = new ImageIcon("C:/Users/hp/documents/MyLogo.png");
ran.setIconImage(img.getImage());
ran.setTitle( "Pearl Math-Whiz");
ran.pack();
}

Converting Point to Button

Is it possible to convert from point to JButton in java, just as you convert from int to string .. Any help is acceptable, please I need help on it. Thanks!
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.*;
import java.awt.*;
#SuppressWarnings("serial")
public class Beginner extends JPanel {
static JButton quest;
Random rand = new Random();
int n = 10;
static List <Point> points = new ArrayList<Point> ();
public Beginner() {
int radius = 200;
Point center = new Point (250, 250);
double angle = Math.toRadians(360 / n);
points.add(center);
for (int i = 0; i < n; i++) {
double theta = i * angle;
int dx = (int) (radius * Math.sin(theta));
int dy = (int) (radius * Math.cos(theta));
Point p = new Point (center.x + dx , center.y + dy);
points.add(p);
}
draw (points);
}
public void draw (List<Point> points) {
JPanel panels = new JPanel();
SpringLayout spring = new SpringLayout();
int count = 1;
for (Point point: points) {
quest = new JButton("Question " + count);
quest.setForeground(Color.BLACK);
Font fonte = new Font("Script MT Bold", Font.PLAIN, 20);
quest.setFont(fonte);
add (quest);
count++;
spring.putConstraint(SpringLayout.WEST, quest, point.x, SpringLayout.WEST, panels );
spring.putConstraint(SpringLayout.NORTH, quest, point.y, SpringLayout.NORTH, panels );
setLayout(spring);
panels.setOpaque(false);
panels.setVisible(true);
panels.setLocation(5,5);
add(panels);
quest.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent p) {
JButton source = (JButton) p.getSource();
//where the problem lies
if (source.equals(points.get(0))) {
//some action....
}
}
});
}
}
public static void main(String [] args){
JFrame frame = new JFrame();
//set JFrame properties
JButton start = new JButton ("CLick here to start");
start.addActionListener(new ActionListener(){
public void actionPerformed (ActionEvent et) {
Beginner novice = new Beginner();
//set Beginner properties (remember it extends JPanel);
}
});
} }
Probbaly you will need to add the missing lines into your code just like this, I've just tested it and it works.
Import the Point class from awt package.
Use the main method to execute your code by creating a new instance of the class.
Also you need to extend the JFrame class to be able to call the setLayout and add methods.
package javaapplication6;
import java.awt.Color;
import java.awt.Font;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.SpringLayout;
import javax.swing.JFrame;
public class Beginner extends JFrame {
Random rand = new Random();
int n = 10;
static List<Point> points = new ArrayList<Point>();
public Beginner() {
int radius = 200;
Point center = new Point(250, 250);
double angle = Math.toRadians(360 / n);
points.add(center);
for (int i = 0; i < n; i++) {
double theta = i * angle;
int dx = (int) (radius * Math.sin(theta));
int dy = (int) (radius * Math.cos(theta));
Point p = new Point(center.x + dx, center.y + dy);
points.add(p);
}
draw(points);
}
public void draw(List<Point> points) {
JPanel panels = new JPanel();
SpringLayout spring = new SpringLayout();
int count = 1;
for (Point point : points) {
JButton quest = new JButton("Question " + count);
quest.setForeground(Color.BLACK);
Font fonte = new Font("Script MT Bold", Font.PLAIN, 20);
quest.setFont(fonte);
quest.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent et) {
System.out.println(quest.getText());
//do something else
}
});
add(quest);
spring.putConstraint(SpringLayout.WEST, quest, point.x, SpringLayout.WEST, panels);
spring.putConstraint(SpringLayout.NORTH, quest, point.y, SpringLayout.NORTH, panels);
setLayout(spring);
panels.setOpaque(false);
panels.setVisible(true);
panels.setLocation(5, 5);
add(panels);
count++;
}
setSize(700, 700);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new Beginner();
}
}

Making a Grid on a JFrame and filling with random colours

for(int i = 0; i < sizex/10; i++)
{
for(int u = 0; u < sizey/10; u++)
{
JPanel temp = new JPanel();
//temp.setSize(10, 10);
temp.setBounds(i*10,u*10, 10, 10);
//temp.setLocation(i*10, u*10);
Random r = new Random();
int rand = r.nextInt(4-0);
if(rand == 0)
{
temp.setBackground(Color.GREEN);
}
else if(rand == 1)
{
temp.setBackground(Color.BLUE);
}
else if(rand == 2)
{
temp.setBackground(Color.RED);
}
else if(rand == 3)
{
temp.setBackground(Color.MAGENTA);
}
frame.add(temp);
}
}
In my code here the logic behind it works(in my head) and this code works if I instead divide sizex and y by 100 and making the size of the box 100 instead of 10.
In the case that it is currently in it produces boxes which seem to be the right size but there are only a few down the side of the application instead of a full screen.
Here is a pic of the app:
You could...
Use a GridLayout...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class RandomCells {
public static void main(String[] args) {
new RandomCells();
}
public RandomCells() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridLayout(10, 10, 0, 0));
Random rnd = new Random();
Color[] colors = new Color[]{Color.GREEN, Color.BLUE, Color.RED, Color.MAGENTA};
for (int col = 0; col < 10; col++) {
for (int row = 0; row < 10; row++) {
JPanel cell = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(10, 10);
}
};
int color = rnd.nextInt(4);
cell.setBackground(colors[color]);
add(cell);
}
}
}
}
}
See How to Use GridLayout for more details
Or you could...
Use a GridBagLayout...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class RandomCells {
public static void main(String[] args) {
new RandomCells();
}
public RandomCells() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
Random rnd = new Random();
Color[] colors = new Color[]{Color.GREEN, Color.BLUE, Color.RED, Color.MAGENTA};
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridy = 0;
for (int col = 0; col < 10; col++) {
gbc.gridx = 0;
for (int row = 0; row < 10; row++) {
JPanel cell = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(10, 10);
}
};
int color = rnd.nextInt(4);
cell.setBackground(colors[color]);
add(cell, gbc);
gbc.gridx++;
}
gbc.gridy++;
}
}
}
}
See How to Use GridBagLayout for more details.
What's the difference?
GridLayout will always size it's components evenly so that they fill the available space, so if your resize the window for example, all the panels will change size in an attempt to fill the available space.
GridBagLayout (in the configuration I've shown) will continue to honor the preferredSize of the panels, so as you resize the window, the panels won't change size
You can achieve this without using GridLayout and simply by redefining the paintComponent method of JPanel component and filling it with random colors in sequential rectangles like this :
Here's the code used to achieve the above image :
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
#SuppressWarnings("serial")
public class RandomPaint extends JFrame
{
private JPanel panel;
private int dx, dy;
private Random random;
private Color color;
public RandomPaint()
{
dx = 50;
dy = 50;
random = new Random();
setBounds(100, 100, 500, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel()
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
for (int i = 0; i < getHeight(); i = i + dx)
{
for (int j = 0; j < getWidth(); j = j + dy)
{
color = new Color(random.nextInt(255),
random.nextInt(255), random.nextInt(255));
g2d.setColor(color);
g2d.fillRect(j, i, dx, dy);
}
}
}
};
add(panel);
setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
try
{
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
}
catch (ClassNotFoundException | InstantiationException
| IllegalAccessException
| UnsupportedLookAndFeelException e)
{
}
new RandomPaint();
}
});
}
}
Code:
JFrame frame = new JFrame("example");
frame.setSize(100,100);
frame.setLayout(new GridLayout(10,10));
for(int i = 0; i < 100/10; i++)
{
for(int u = 0; u < 100/10; u++)
{
JPanel temp = new JPanel();
temp.setBounds(i*10,u*10, 10, 10);
Random r = new Random();
int rand = r.nextInt(4-0);
if(rand == 0)
{
temp.setBackground(Color.GREEN);
}
else if(rand == 1)
{
temp.setBackground(Color.BLUE);
}
else if(rand == 2)
{
temp.setBackground(Color.RED);
}
else if(rand == 3)
{
temp.setBackground(Color.MAGENTA);
}
frame.add(temp);
}
frame.setVisible(true);
}

Categories