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();
}
Related
I'm new to Java Programming. Recently I'm developing a mini game with JSWing. However, after coding for awhile the in-game FPS dropped terribly. When I tracked it on Task Manager I had result like this:
Can someone tell me what's wrong? I only used loops, JLabel with icons, Paint Graphics methods, mouseMotionEvent in my code.
Here is the code in the main game
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Game extends JPanel {
int numb = 2;
int pts = 5;
Kitty[] Kitties = new Kitty[4];
public Game() {
for (int i = 0; i < Kitties.length; i++)
Kitties[i] = new Kitty();
}
#Override
public void paint(Graphics graphics) {
BufferedImage img = null;
try {
img = ImageIO.read(getClass().getResourceAsStream("city.jpg"));
} catch (IOException e) {
System.out.println("java io");
}
graphics.drawImage(img, 0, 0, null);
//paints square objects to the screen
for (int i = 0; i < numb;i++) {
Kitties[i].paint(graphics);
}
}
public void update(TheJPanel frame) {
if (frame.a >= 0 && frame.a < 500) numb = 2;
if (frame.a>= 500) numb = 3;
for (int i = 0; i< numb; i++) {
int disty = 500 - Kitties[i].squareYLocation;
int distx = Kitties[i].squareXLocation - frame.x;
if ( Kitties[i].squareYLocation < 600 && disty <= 5 && disty >= -80 && distx < 260 && distx > -100){
frame.a +=pts;
if (Kitties[i].kittype == 6) frame.a += pts;
if (frame.a >= 500) {
Kitties[i].fallSpeed = Kitties[i].FallSpeedlvl2();
pts = 10;
}
Kitties[i].squareYLocation = -200;
Kitties[i].generateKittype();
Kitties[i].generateRandomXLocation();
Kitties[i].generateRandomFallSpeed();
frame.point.setText("Point:" + String.valueOf(frame.a));
frame.lives.setText("Lives:" + String.valueOf(frame.count));
}
if(Kitties[i].squareYLocation > 610){
frame.count--;
Kitties[i].generateKittype();
Kitties[i].generateRandomXLocation();
Kitties[i].generateRandomFallSpeed();
Kitties[i].squareYLocation = -200;
}
if (Kitties[i].squareYLocation >=605) frame.catFall(Kitties[i].squareXLocation);
if(Kitties[i].squareYLocation <= 610){
Kitties[i].squareYLocation += Kitties[i].fallSpeed;
}
}
}
public static void main(String[] args) throws InterruptedException {
Game game = new Game();
TheJPanel frame = new TheJPanel();
frame.add(game);
frame.setVisible(true);
frame.setSize(1000, 1000);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setTitle("Saving kitties");
frame.setResizable(false);
frame.setLocationRelativeTo(null);
while (frame.count>0) {
game.update(frame);
game.repaint();
Thread.sleep(4);
}
if (frame.count == 0) {
JOptionPane.showMessageDialog(null, "You lost!", "Game over!", JOptionPane.ERROR_MESSAGE);
game.setVisible(false);
frame.getContentPane().removeAll();
frame.getContentPane().repaint();
frame.bask.setVisible(false);
frame.background.setVisible(false);
}
}
}
Here is the code for the main Jframe
package game;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.File;
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;
/**
*
* #author Imba Store
*/
public class TheJPanel extends JFrame implements MouseMotionListener {
protected int x;
protected int a = 0;
protected int count = 20;
protected JLabel bask = new JLabel();
protected JLabel background = new JLabel();
protected JLabel point = new JLabel();
protected JLabel lives = new JLabel();
Timer fall;
protected int time =0;
public TheJPanel() {
this.addMouseMotionListener(this);
InitContent();
}
protected void InitContent() {
Icon img = new ImageIcon(getClass().getResource("basket.png"));
bask.setIcon(img);
Icon themes = new ImageIcon(getClass().getResource("city2.png"));
background.setIcon(themes);
background.setBounds(0, 699, 1000, 300);
point.setFont(new java.awt.Font("Trebuchet MS", 1, 35));
point.setText("Point:" + String.valueOf(a));
point.setBounds(20,908,240,50);
point.setForeground(Color.white);
lives.setBounds(800, 908,200,50);
lives.setFont(new java.awt.Font("Trebuchet MS", 1, 35));
lives.setForeground(Color.white);
lives.setText("Point:" + String.valueOf(count));
point.setOpaque(false);
add(point);
add(lives);
add(bask);
add(background);
bask.setSize(400,148);
}
#Override
public void mouseMoved (MouseEvent me)
{
x = me.getX();
background.setBounds(0, 699, 1000, 300);
bask.setBounds(x, 700, 400, 148);
}
#Override
public void mouseDragged (MouseEvent me)
{
}
public void catFall(int getX){
Icon fell = new ImageIcon(getClass().getResource("kitty-fall.png"));
JLabel fellcat = new JLabel();
fellcat.setIcon(fell);
fellcat.setBounds(getX, 760, 220, 220);
add(fellcat);
add(background);
fall = new Timer(1500, new ActionListener(){
#Override
public void actionPerformed(ActionEvent ae) {
getContentPane().remove(fellcat);
}
});
fall.setRepeats(false);
fall.start();
}
}
And this is the class for the falling cats
package game;
/**
*
* #author Imba Store
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
public final class Kitty extends JLabel {
protected int squareXLocation;
protected int squareYLocation = -200;
protected int fallSpeed = 1;
protected int kittype;
Random rand = new Random();
public int generateRandomXLocation(){
return squareXLocation = rand.nextInt(800);
}
public int generateRandomFallSpeed(){
return fallSpeed = rand.ints(3, 4).findFirst().getAsInt();
}
public int FallSpeedlvl2() {
return fallSpeed = rand.ints(3,7).findFirst().getAsInt();
}
public int generateKittype() {
return kittype = rand.ints(1,8).findFirst().getAsInt();
}
#Override
public void paint(Graphics g) {
BufferedImage img = null;
BufferedImage thugcat = null;
try {
img = ImageIO.read(getClass().getResourceAsStream("kitty.png"));
thugcat = ImageIO.read(getClass().getResourceAsStream("thug-kitty.png"));
} catch (IOException e) {
System.out.println("Java IO");
}
if (kittype == 6) {
g.drawImage(thugcat, squareXLocation, squareYLocation, null);
}
else g.drawImage(img, squareXLocation,squareYLocation,null);
}
public Kitty(){
generateRandomXLocation();
generateRandomFallSpeed();
generateKittype();
}
public void paint(Graphics graphics) {
BufferedImage img = null;
try {
img = ImageIO.read(getClass().getResourceAsStream("city.jpg"));
Custom painting is done by overriding paintComponent(...) not paint(). The first statement should then be super.paintComponent().
A painting method is for painting only. Don't do I/O in the painting method. This will cause the image to be read every time you repaint the panel.
Thread.sleep(4);
Sleeping for 4ms is not enough. That will attempt to repaint 250 times a second which is too often. There is no need for the frame rate to be that fast.
Kitty[] Kitties = new Kitty[4];
Variable names should not start with an upper case character. Most of your names are correct. Be consistent!
point.setBounds(20,908,240,50);
Don't use setBounds(). Swing was designed to be used with layout managers. Set a layout manager for you background and then add the components.
public int FallSpeedlvl2() {
Methods should NOT start with an upper case character. Again, most are correct. Be Consistent!!!
I want to know how to manage the rgb values to change the background colour of a JFrame dynamically, by now i can only change from green to blue and versa vice; this are the colours that i need:
The rgb of these colours can be found here
Here's my sample code of how to change from green to blue dynamically:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class ChangeColor {
public ChangeColor() {
JFrame frame = new JFrame();
frame.add(new ColorPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public class ColorPanel extends JPanel {
private static final int DELAY = 30;
private static final int INCREMENT = 15;
private Color currentColor = Color.BLUE;
boolean isBlue = true;
boolean isGreen = false;
private int r,g,b;
private Timer timer = null;
private JButton greenButton = null;
private JButton blueButton = null;
public ColorPanel() {
r = 0; g = 0; b = 255;
greenButton = createGreenButton();
blueButton = createBlueButton();
timer = new Timer(DELAY, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (isBlue) {
if (b == 0) {
stopTimer();
enableButtons();
} else {
blueToGreen();
setColor(new Color(r, b, g));
}
}
if (isGreen) {
if (g == 0) {
stopTimer();
enableButtons();
} else {
greenToBlue();
setColor(new Color(r, b, g));
}
}
repaint();
}
});
add(blueButton);
add(greenButton);
}
public JButton createBlueButton() {
JButton button = new JButton("BLUE");
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
if (currentColor != new Color(0, 255, 0)) {
System.out.println("turn blue");
isBlue = true;
isGreen = false;
diableButtons();
startTimer();
}
}
});
return button;
}
public void diableButtons() {
blueButton.setEnabled(false);
greenButton.setEnabled(false);
}
public void enableButtons() {
blueButton.setEnabled(true);
greenButton.setEnabled(true);
}
public JButton createGreenButton() {
JButton button = new JButton("GREEN");
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
if (currentColor != new Color(0, 0, 255)) {
System.out.println("turn green");
isGreen = true;
isBlue = false;
diableButtons();
startTimer();
}
}
});
return button;
}
private void blueToGreen() {
b -= INCREMENT;
g += INCREMENT;
}
private void greenToBlue() {
g -= INCREMENT;
b += INCREMENT;
}
public void setColor(Color color) {
this.currentColor = color;
}
public void startTimer() {
timer.start();
}
public void stopTimer() {
timer.stop();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(currentColor);
g.fillRect(0, 0, getWidth(), getHeight());
}
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
new ChangeColor();
}
});
}
}
The code has some bugs, and it's not the most robust code, so that if you can improve it, i'll be thanked
Here's the output of the sample code:
Your current approach is indeed not easily generalizable. The hard-coded parts of the buttons for "blue" and "green", and especially the special methods like blueToGreen make it impossible to extend the number of colors with reasonable effort. (You don't want to create methods blueToYellow, blueToRed, blueToTheThirdColorFromThisListForWhichIDontKnowAName ...).
There are many possible ways of generalizing this. You did not say much about the intended structure and responsibilities. But you should at least create a method that can interpolate between two arbitrary colors with a given number of steps. In the code snippet below, this is done in the ´createColorsArrayArgb` method, which creates an array of ARGB colors from an arbitrary sequence of colors (I needed this recently). But you can probably boil it down to 2 colors, if you want to.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class ChangeColor
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new ChangeColor();
}
});
}
public ChangeColor()
{
JFrame frame = new JFrame();
ColorPanel colorPanel = new ColorPanel(Color.BLUE);
ColorInterpolator ci = new ColorInterpolator(colorPanel, Color.BLUE);
colorPanel.addColorButton(createButton("Blue", Color.BLUE, ci));
colorPanel.addColorButton(createButton("Green", Color.GREEN, ci));
colorPanel.addColorButton(createButton("Red", Color.RED, ci));
colorPanel.addColorButton(createButton("Cyan", Color.CYAN, ci));
colorPanel.addColorButton(createButton("Yellow", Color.YELLOW, ci));
colorPanel.addColorButton(createButton("Magenta", Color.MAGENTA, ci));
frame.add(colorPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static JButton createButton(String name, final Color color,
final ColorInterpolator colorInterpolator)
{
JButton button = new JButton(name);
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
colorInterpolator.interpolateTo(color);
}
});
return button;
}
/**
* Creates an array with the given number of elements, that contains the
* ARGB representations of colors that are linearly interpolated between the
* given colors
*
* #param steps The number of steps (the size of the resulting array)
* #param colors The colors to interpolate between
* #return The array with ARGB colors
*/
static int[] createColorsArrayArgb(int steps, Color... colors)
{
int result[] = new int[steps];
double normalizing = 1.0 / (steps - 1);
int numSegments = colors.length - 1;
double segmentSize = 1.0 / (colors.length - 1);
for (int i = 0; i < steps; i++)
{
double relative = i * normalizing;
int i0 = Math.min(numSegments, (int) (relative * numSegments));
int i1 = Math.min(numSegments, i0 + 1);
double local = (relative - i0 * segmentSize) * numSegments;
Color c0 = colors[i0];
int r0 = c0.getRed();
int g0 = c0.getGreen();
int b0 = c0.getBlue();
Color c1 = colors[i1];
int r1 = c1.getRed();
int g1 = c1.getGreen();
int b1 = c1.getBlue();
int dr = r1 - r0;
int dg = g1 - g0;
int db = b1 - b0;
int r = (int) (r0 + local * dr);
int g = (int) (g0 + local * dg);
int b = (int) (b0 + local * db);
int argb = (0xFF << 24) | (r << 16) | (g << 8) | (b << 0);
result[i] = argb;
}
return result;
}
}
class ColorInterpolator
{
private static final int DELAY = 20;
private Color currentColor;
private int currentIndex = 0;
private int currentColorsArgb[];
private final Timer timer;
private final ColorPanel colorPanel;
ColorInterpolator(final ColorPanel colorPanel, Color initialColor)
{
this.colorPanel = colorPanel;
currentColor = initialColor;
currentColorsArgb = new int[]{ initialColor.getRGB() };
timer = new Timer(DELAY, new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
currentIndex++;
if (currentIndex >= currentColorsArgb.length-1)
{
timer.stop();
colorPanel.enableButtons();
}
else
{
int argb = currentColorsArgb[currentIndex];
currentColor = new Color(argb);
colorPanel.setColor(currentColor);
}
}
});
}
void interpolateTo(Color targetColor)
{
colorPanel.diableButtons();
currentColorsArgb = ChangeColor.createColorsArrayArgb(
40, currentColor, targetColor);
currentIndex = 0;
timer.start();
}
}
class ColorPanel extends JPanel
{
private Color currentColor;
private List<JButton> buttons;
public ColorPanel(Color initialColor)
{
currentColor = initialColor;
buttons = new ArrayList<JButton>();
}
void addColorButton(JButton button)
{
buttons.add(button);
add(button);
}
public void diableButtons()
{
for (JButton button : buttons)
{
button.setEnabled(false);
}
}
public void enableButtons()
{
for (JButton button : buttons)
{
button.setEnabled(true);
}
}
public void setColor(Color color)
{
currentColor = color;
repaint();
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(currentColor);
g.fillRect(0, 0, getWidth(), getHeight());
}
#Override
public Dimension getPreferredSize()
{
return new Dimension(600, 300);
}
}
For simplicity, you might look at doing the fade calculation in HSB color coordinates. The example below interpolates between the two hues, green and blue, but you can pass saturation and brightness, too. The color lookup table, clut, is precomputed and used in the timer's listener. Some related examples are seen here.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedList;
import java.util.Queue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
/**
* #see https://stackoverflow.com/a/24718561/230513
*/
public class HSBTest {
private static final float greenHue = 2 / 6f;
private static final float blueHue = 4 / 6f;
private void display() {
JFrame f = new JFrame("HSBTest");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Fader fader = new Fader(greenHue, blueHue);
f.add(fader);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
fader.start();
}
private static class Fader extends JPanel implements ActionListener {
private final float N = 32;
private final Queue<Color> clut = new LinkedList<Color>();
Timer t = new Timer(50, this);
public Fader(float h1, float h2) {
float d = (h2 - h1) / N;
for (int i = 0; i < N; i++) {
clut.add(Color.getHSBColor(h1 + d * i, 1, 1));
}
for (int i = 0; i < N; i++) {
clut.add(Color.getHSBColor(h2 - d * i, 1, 1));
}
}
private void start() {
t.start();
}
#Override
public void actionPerformed(ActionEvent e) {
this.setBackground(clut.peek());
clut.add(clut.remove());
}
#Override
public Dimension getPreferredSize() {
return new Dimension(256, 128);
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new HSBTest().display();
}
});
}
}
public void actionPerformed(ActionEvent e) {
List<Color> colors = new ArrayList<Color>();
colors.add(new Color(0,0,255);
colors.add(new Color(255,0,0);
colors.add(new Color(0,255,0);
// add your other colors
for(Color c : colors){
setColor(c)
Thread.sleep(1000); //wait 1 second to change the color
repaint();
}
}
I want to create a draggable component contains a shape (circle) and a text (JLabel) under it. But i dont get the shape and text in the jpanel. I attached the code below.
SubMapViewer Class
package test;
import com.businesslense.topology.client.config.Condition;
import com.businesslense.topology.client.config.ConfigReader;
import com.businesslense.topology.client.config.NodeConfig;
import com.businesslense.topology.client.config.Parameter;
import java.awt.Color;
import java.awt.Graphics;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public class SubMapViewer extends JLayeredPane {
#Override
public void paint(Graphics grphcs) {
super.paint(grphcs); //To change body of generated methods, choose Tools | Templates.
System.out.println("Paint called");
}
public void showMap() {
Runnable gui = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JFrame f = new JFrame("Draggable Components");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(300, 300);
f.setLocationRelativeTo(null);
JLayeredPane panel = new SubMapViewer();
panel.setLayout(null);
NodeComponent nodeComponent = new NodeComponent(50);
JPanel jPanel = new JPanel();
jPanel.setSize(100, 100);
jPanel.setBorder(javax.swing.BorderFactory.createLineBorder(Color.BLACK, 2));
jPanel.add(nodeComponent);
jPanel.setVisible(true);
Draggable d2 = new Draggable(jPanel, 200, 150);
panel.add(d2);
f.add(panel);
f.setVisible(true);
}
};
//GUI must start on EventDispatchThread:
SwingUtilities.invokeLater(gui);
}
Properties getDisplayProperties(Properties properties) {
//List<String> menuList = new ArrayList<>();
List<com.businesslense.topology.client.config.NodeConfig> nodeConfigs = ConfigReader.getData().getNodeConfig();
outer:
for (Iterator<NodeConfig> it = nodeConfigs.iterator(); it.hasNext();) {
NodeConfig nodeConfig = it.next();
List<Condition> conditions = nodeConfig.getCondtion();
boolean match = false;
for (Iterator<Condition> it1 = conditions.iterator(); it1.hasNext();) {
Condition condition = it1.next();
if (condition.getValue().equalsIgnoreCase("" + properties.get(condition.getName()))) {
match = true;
} else {
continue outer;
}
}
if (match) {
Properties displayProperties = new Properties();
for (Iterator<Parameter> it1 = nodeConfig.getParameter().iterator(); it1.hasNext();) {
Parameter parameter = it1.next();
displayProperties.put(parameter.getName(), parameter.getValue());
}
return displayProperties;
}
}
return null;
}
public static void main(String[] arv) {
SubMapViewer subMapViewer = new SubMapViewer();
subMapViewer.showMap();
}
}
NodeComponent Class
package test;
import com.businesslense.topology.client.marker.DefaultNodeComponent;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.apache.log4j.Logger;
public class NodeComponent extends JPanel {
private String name;
private Integer size;
static Logger logger = Logger.getLogger(DefaultNodeComponent.class.getName());
public NodeComponent(Integer size) {
setLayout(null);
setSize(size , size * 2);
this.size = size;
this.name = "ICON NAME";
JLabel textLabel = new JLabel(name);
textLabel.setLocation(size, 10);
add(textLabel);
}
#Override
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
int shapePaddingVal = (size * 5) / 100;
int shapeRadius = (size * 90) / 100;
Color shapeColor = Color.BLACK;
g2d.setColor(shapeColor);
g2d.setStroke(new BasicStroke(2));
g2d.drawOval(shapePaddingVal, shapePaddingVal, shapeRadius/2, shapeRadius/2);
g2d.setColor(Color.BLACK);
g2d.setStroke(new BasicStroke(0, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
}
}
Draggable Class
package test;
/*
* Draggable.java
*/
import java.awt.*;
import javax.swing.*;
import java.awt.event.MouseEvent;
import javax.swing.border.Border;
import javax.swing.event.MouseInputAdapter;
public class Draggable extends JComponent {
private Point pointPressed;
private JComponent draggable;
public Draggable(final JComponent component, final int x, final int y) {
draggable = component;
// draggable.setCursor(draggable.getCursor());
setCursor(new Cursor(Cursor.HAND_CURSOR));
setLocation(x, y);
setSize(component.getPreferredSize());
setLayout(new BorderLayout());
add(component);
MouseInputAdapter mouseAdapter = new MouseHandler();
addMouseMotionListener(mouseAdapter);
addMouseListener(mouseAdapter);
}
#Override
public void setBorder(final Border border) {
super.setBorder(border);
if (border != null) {
Dimension size = draggable.getPreferredSize();
Insets insets = border.getBorderInsets(this);
size.width += (insets.left + insets.right + 5);
size.height += (insets.top + insets.bottom);
setSize(size);
}
}
private class MouseHandler extends MouseInputAdapter {
#Override
public void mouseDragged(final MouseEvent e) {
Point pointDragged = e.getPoint();
Point loc = getLocation();
loc.translate(pointDragged.x - pointPressed.x,
pointDragged.y - pointPressed.y);
setLocation(loc);
}
#Override
public void mousePressed(final MouseEvent e) {
pointPressed = e.getPoint();
}
}
}
I want to create a draggable component contains a shape (circle) and a text (JLabel) under it
Why don't you use use a JLabel with an Icon and text?
NodeComponent nodeComponent = new NodeComponent(50);
JPanel jPanel = new JPanel();
jPanel.setSize(100, 100);
jPanel.add(nodeComponent);
By default a JPanel uses a FlowLayout, which respects the components "preferred size". Your NodeComponent class should override the getPreferredSize() method to return a realistic value. Another reason for just using a JLabel since it will determine the preferred size for you based on the Icon and text.
JLabel textLabel = new JLabel(name);
textLabel.setLocation(size, 10);
add(textLabel);
You are adding the label to the component which uses a null layout. Since the size is zero, the text will not display.
I'm not sure how I would fix the errors in my program and how I would highlight the option the user is hovering on. I want it to highlight the code for each position, i.e position 1 would be highlighted(as a different color) to start game,etc. and up/down would change position and I would change the position with up ,down, left, right. This is what I have so far. At the moment its bugged and when compiled with my window it comes out as:
Which works for the main game and altered for this titleboard, what am I doing wrong and how do I fix it?
TitleBoard class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.ArrayList;
//sound + file opening
import java.io.*;
import javax.sound.sampled.*;
public class TitleBoard extends JPanel implements ActionListener{
private ArrayList<String> OptionList;
private Image background;
private ImageIcon bgImageIcon;
private String cheatString;
private int position;
private Timer timer;
public TitleBoard(){
setFocusable(true);
addKeyListener(new TAdapter());
bgImageIcon = new ImageIcon("");
background = bgImageIcon.getImage();
String[] options = {"Start Game","Options","Quit"};
OptionList = new ArrayList<String>();
optionSetup(options);
position = 1;
timer = new Timer(8, this);
timer.start();
/*
1 mod 3 =>1 highlight on start
2 mod 3 =>2 highlight on options
3 mod 3 =>0 highlight on quit
*/
try{
Font numFont = Font.createFont(Font.TRUETYPE_FONT,new File("TwistedStallions.ttf"));
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(numFont);
setFont(numFont.deriveFont(24f)); //adjusthislater
}catch(IOException|FontFormatException e){
e.printStackTrace();
}
}
private void optionSetup(String[] s){
for(int i=0; i<s.length;i++) {
OptionList.add(s[i]);
}
}
public void paint(Graphics g){
super.paint(g);
Graphics g2d = (Graphics2D)g;
g2d.drawImage(background,0,0,this);
for (int i=0;i<OptionList.size();i++){
g2d.drawString(OptionList.get(i),200,120+120*i);
}/*
g2d.drawString(OptionList.get(1),400,240);
g2d.drawString(OptionList.get(2),400,360);
//instructions on start screen maybe??
//800x500
//highlighting*/
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
public void actionPerformed(ActionEvent e){
repaint();
}
public class TAdapter extends KeyAdapter {
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_UP||
e.getKeyCode() == KeyEvent.VK_RIGHT){
position++;
}
if(e.getKeyCode() == KeyEvent.VK_DOWN||
e.getKeyCode() == KeyEvent.VK_LEFT){
position--;
}
}
}
}
Window Class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Window extends JFrame{
public Window(){
int width = 800, height = 600;
//TO DO: make a panel in TITLE MODE
///////////////////////////////////
//panel in GAME MODE.
add(new TitleBoard());
//set default close
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(width,height);
//centers window
setLocationRelativeTo(null);
setTitle("Title");
setResizable(false);
setVisible(true);
}
public static void main(String[] args){
new Window();
}
}
There are any number of ways you might achieve this, for example, you could use some kind of delegation model.
That is, rather then trying to mange of each element in a single method (or methods), you could devise a delegate which provide a simple interface method that the paint method would call and it would know how to do the rest.
For example, Swing uses this type of concept with it's cell renderers for JList, JTable and JTree.
For example...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class MyAwesomeMenu {
public static void main(String[] args) {
new MyAwesomeMenu();
}
public MyAwesomeMenu() {
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 {
private List<String> menuItems;
private String selectMenuItem;
private String focusedItem;
private MenuItemPainter painter;
private Map<String, Rectangle> menuBounds;
public TestPane() {
setBackground(Color.BLACK);
painter = new SimpleMenuItemPainter();
menuItems = new ArrayList<>(25);
menuItems.add("Start Game");
menuItems.add("Options");
menuItems.add("Exit");
selectMenuItem = menuItems.get(0);
MouseAdapter ma = new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
String newItem = null;
for (String text : menuItems) {
Rectangle bounds = menuBounds.get(text);
if (bounds.contains(e.getPoint())) {
newItem = text;
break;
}
}
if (newItem != null && !newItem.equals(selectMenuItem)) {
selectMenuItem = newItem;
repaint();
}
}
#Override
public void mouseMoved(MouseEvent e) {
focusedItem = null;
for (String text : menuItems) {
Rectangle bounds = menuBounds.get(text);
if (bounds.contains(e.getPoint())) {
focusedItem = text;
repaint();
break;
}
}
}
};
addMouseListener(ma);
addMouseMotionListener(ma);
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "arrowDown");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "arrowUp");
am.put("arrowDown", new MenuAction(1));
am.put("arrowUp", new MenuAction(-1));
}
#Override
public void invalidate() {
menuBounds = null;
super.invalidate();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
if (menuBounds == null) {
menuBounds = new HashMap<>(menuItems.size());
int width = 0;
int height = 0;
for (String text : menuItems) {
Dimension dim = painter.getPreferredSize(g2d, text);
width = Math.max(width, dim.width);
height = Math.max(height, dim.height);
}
int x = (getWidth() - (width + 10)) / 2;
int totalHeight = (height + 10) * menuItems.size();
totalHeight += 5 * (menuItems.size() - 1);
int y = (getHeight() - totalHeight) / 2;
for (String text : menuItems) {
menuBounds.put(text, new Rectangle(x, y, width + 10, height + 10));
y += height + 10 + 5;
}
}
for (String text : menuItems) {
Rectangle bounds = menuBounds.get(text);
boolean isSelected = text.equals(selectMenuItem);
boolean isFocused = text.equals(focusedItem);
painter.paint(g2d, text, bounds, isSelected, isFocused);
}
g2d.dispose();
}
public class MenuAction extends AbstractAction {
private final int delta;
public MenuAction(int delta) {
this.delta = delta;
}
#Override
public void actionPerformed(ActionEvent e) {
int index = menuItems.indexOf(selectMenuItem);
if (index < 0) {
selectMenuItem = menuItems.get(0);
}
index += delta;
if (index < 0) {
selectMenuItem = menuItems.get(menuItems.size() - 1);
} else if (index >= menuItems.size()) {
selectMenuItem = menuItems.get(0);
} else {
selectMenuItem = menuItems.get(index);
}
repaint();
}
}
}
public interface MenuItemPainter {
public void paint(Graphics2D g2d, String text, Rectangle bounds, boolean isSelected, boolean isFocused);
public Dimension getPreferredSize(Graphics2D g2d, String text);
}
public class SimpleMenuItemPainter implements MenuItemPainter {
public Dimension getPreferredSize(Graphics2D g2d, String text) {
return g2d.getFontMetrics().getStringBounds(text, g2d).getBounds().getSize();
}
#Override
public void paint(Graphics2D g2d, String text, Rectangle bounds, boolean isSelected, boolean isFocused) {
FontMetrics fm = g2d.getFontMetrics();
if (isSelected) {
paintBackground(g2d, bounds, Color.BLUE, Color.WHITE);
} else if (isFocused) {
paintBackground(g2d, bounds, Color.MAGENTA, Color.BLACK);
} else {
paintBackground(g2d, bounds, Color.DARK_GRAY, Color.LIGHT_GRAY);
}
int x = bounds.x + ((bounds.width - fm.stringWidth(text)) / 2);
int y = bounds.y + ((bounds.height - fm.getHeight()) / 2) + fm.getAscent();
g2d.setColor(isSelected ? Color.WHITE : Color.LIGHT_GRAY);
g2d.drawString(text, x, y);
}
protected void paintBackground(Graphics2D g2d, Rectangle bounds, Color background, Color foreground) {
g2d.setColor(background);
g2d.fill(bounds);
g2d.setColor(foreground);
g2d.draw(bounds);
}
}
}
For here, you could add ActionListener
When a GUI needs a button, use a JButton! The JButton API allows the possibility to add icons for many different circumstances. This example shows different icons for the standard icon, the hover icon, and the pressed icon. Your GUI would obviously use icons with text on them for the required effect.
The icons are pulled directly (hot-linked) from Example images for code and mark-up Q&As.
Standard
Hover over triangle
Press triangle
Code
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.net.URL;
public class IconHoverFocusIndication {
// the GUI as seen by the user (without frame)
// swap the 1 and 0 for single column
JPanel gui = new JPanel(new GridLayout(1,0,50,50));
public static final int GREEN = 0, YELLOW = 1, RED = 2;
String[][] urls = {
{
"http://i.stack.imgur.com/T5uTa.png",
"http://i.stack.imgur.com/IHARa.png",
"http://i.stack.imgur.com/wCF8S.png"
},
{
"http://i.stack.imgur.com/gYxHm.png",
"http://i.stack.imgur.com/8BGfi.png",
"http://i.stack.imgur.com/5v2TX.png"
},
{
"http://i.stack.imgur.com/1lgtq.png",
"http://i.stack.imgur.com/6ZXhi.png",
"http://i.stack.imgur.com/F0JHK.png"
}
};
IconHoverFocusIndication() throws Exception {
// adjust to requirement..
gui.setBorder(new EmptyBorder(15, 30, 15, 30));
gui.setBackground(Color.BLACK);
Insets zeroMargin = new Insets(0,0,0,0);
for (int ii = 0; ii < 3; ii++) {
JButton b = new JButton();
b.setBorderPainted(false);
b.setMargin(zeroMargin);
b.setContentAreaFilled(false);
gui.add(b);
URL url1 = new URL(urls[ii][GREEN]);
BufferedImage bi1 = ImageIO.read(url1);
b.setIcon(new ImageIcon(bi1));
URL url2 = new URL(urls[ii][YELLOW]);
BufferedImage bi2 = ImageIO.read(url2);
b.setRolloverIcon(new ImageIcon(bi2));
URL url3 = new URL(urls[ii][RED]);
BufferedImage bi3 = ImageIO.read(url3);
b.setPressedIcon(new ImageIcon(bi3));
}
}
public JComponent getGUI() {
return gui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
IconHoverFocusIndication ihfi =
new IconHoverFocusIndication();
JFrame f = new JFrame("Button Icons");
f.add(ihfi.getGUI());
// Ensures JVM closes after frame(s) closed and
// all non-daemon threads are finished
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// See https://stackoverflow.com/a/7143398/418556 for demo.
f.setLocationByPlatform(true);
// ensures the frame is the minimum size it needs to be
// in order display the components within it
f.pack();
// should be done last, to avoid flickering, moving,
// resizing artifacts.
f.setVisible(true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency
SwingUtilities.invokeLater(r);
}
}
I'm working on a memory game and I want to set it up so I click the first "card", then the second and if they are not the same the second card shows for a few seconds then they return to the "non-flipped" position.
I tried using SwingWorker, Thread.sleep and SwingTimer but I cant get it to work. With Thread.sleep the second card wont "flip" if it's a duplicate it waits the amount of sleep time and disappears. If its not a match it waits "face down" and after the sleep timer the first card does flip back. This happens regardless of where I place the Thread.sleep.
With Swing Timer it only appears to "change the timer" while I'm interacting with the cards so I end up flipping 8 cards before it activates.
I've had no luck with SwingWorker and I'm not even sure it will work for what I'm looking for.
This is the code I have:
class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
for(int index = 0; index < arraySize; index++)
{
if(button[index] == e.getSource())
{
button[index].setText(String.valueOf(cards.get(index)));
button[index].setEnabled(false);
number[counter]=cards.get(index);
if (counter == 0)
{
counter++;
}
else if (counter == 1)
{
if (number[0] == number[1])
{
for(int i = 0; i < arraySize; i++)
{
if(!button[i].isEnabled())
{
button[i].setVisible(false);
}
}
}
else
{
for(int i = 0; i < arraySize; i++)
{
if(!button[i].isEnabled())
{
button[i].setEnabled(true);
button[i].setText("Card");
}
}
}
counter = 0;
}
}
}
}
}
Basically what I need is for this code to execute when the counter == 1, and the card is not a match:
button[index].setText(String.valueOf(cards.get(index)));
button[index].setEnabled(false);
Then a pause so the card is revealed for that time, and finally it resumes to returning the card to its face down position.
This is what I tried with Thread.sleep():
class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
for(int index = 0; index < arraySize; index++)
{
if(button[index] == e.getSource())
{
button[index].setText(String.valueOf(cards.get(index)));
button[index].setEnabled(false);
number[counter]=cards.get(index);
if (counter == 0)
{
counter++;
}
else if (counter == 1)
{
if (number[0] == number[1])
{
for(int i = 0; i < arraySize; i++)
{
if(!button[i].isEnabled())
{
button[i].setVisible(false);
}
}
}
else
{
try
{
Thread.sleep(800);
}
catch (InterruptedException e1)
{
e1.printStackTrace();
}
for(int i = 0; i < arraySize; i++)
{
if(!button[i].isEnabled())
{
button[i].setEnabled(true);
button[i].setText("Card");
}
}
}
counter = 0;
}
}
}
}
}
Thanks in advance for any advice
Use javax.swing.Timer to schedule a future event to trigger. This will allow you to make changes to the UI safely, as the timer is triggered within the context of the Event Dispatching Thread.
The problem with been able to flip multiple cards simultaneously has more to do with you not setting up a state that prevents the user from flipping cards then the use of timers.
The following example basically only allows one card to be flipped per group at a time.
Once a card has been flipped in both groups, the timer is started. When it is triggered, the cards are reset.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.LinearGradientPaint;
import java.awt.Point;
import java.awt.Rectangle;
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.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.LineBorder;
public class FlipCards {
public static void main(String[] args) {
new FlipCards();
}
public FlipCards() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class Card extends JPanel {
private BufferedImage image;
private boolean flipped = false;
private Dimension prefSize;
public Card(BufferedImage image, Dimension prefSize) {
setBorder(new LineBorder(Color.DARK_GRAY));
this.image = image;
this.prefSize = prefSize;
}
#Override
public Dimension getPreferredSize() {
return prefSize;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
LinearGradientPaint lgp = new LinearGradientPaint(
new Point(0, 0),
new Point(0, getHeight()),
new float[]{0f, 1f},
new Color[]{Color.WHITE, Color.GRAY});
g2d.setPaint(lgp);
g2d.fill(new Rectangle(0, 0, getWidth(), getHeight()));
if (flipped && image != null) {
int x = (getWidth() - image.getWidth()) / 2;
int y = (getHeight() - image.getHeight()) / 2;
g2d.drawImage(image, x, y, this);
}
g2d.dispose();
}
public void setFlipped(boolean flipped) {
this.flipped = flipped;
repaint();
}
}
public class CardsPane extends JPanel {
private Card flippedCard = null;
public CardsPane(List<BufferedImage> images, Dimension prefSize) {
setLayout(new GridBagLayout());
MouseAdapter mouseHandler = new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (flippedCard == null) {
Card card = (Card) e.getComponent();
card.setFlipped(true);
flippedCard = card;
firePropertyChange("flippedCard", null, card);
}
}
};
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(4, 4, 4, 4);
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 0.25f;
for (BufferedImage img : images) {
Card card = new Card(img, prefSize);
card.addMouseListener(mouseHandler);
add(card, gbc);
}
}
public Card getFlippedCard() {
return flippedCard;
}
public void reset() {
if (flippedCard != null) {
flippedCard.setFlipped(false);
flippedCard = null;
}
}
}
public class TestPane extends JPanel {
private CardsPane topCards;
private CardsPane bottomCards;
private Timer resetTimer;
public TestPane() {
resetTimer = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
topCards.reset();
bottomCards.reset();
}
});
resetTimer.setRepeats(false);
resetTimer.setCoalesce(true);
PropertyChangeListener propertyChangeHandler = new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
Card top = topCards.getFlippedCard();
Card bottom = bottomCards.getFlippedCard();
if (top != null && bottom != null) {
resetTimer.start();
}
}
};
BufferedImage[] images = new BufferedImage[4];
try {
images[0] = ImageIO.read(new File("./Card01.png"));
images[1] = ImageIO.read(new File("./Card02.jpg"));
images[2] = ImageIO.read(new File("./Card03.jpg"));
images[3] = ImageIO.read(new File("./Card04.png"));
Dimension prefSize = getMaxBounds(images);
List<BufferedImage> topImages = new ArrayList<>(Arrays.asList(images));
Random rnd = new Random(System.currentTimeMillis());
int rotate = (int) Math.round((rnd.nextFloat() * 200) - 50);
Collections.rotate(topImages, rotate);
topCards = new CardsPane(topImages, prefSize);
topCards.addPropertyChangeListener("flippedCard", propertyChangeHandler);
List<BufferedImage> botImages = new ArrayList<>(Arrays.asList(images));
int botRotate = (int) Math.round((rnd.nextFloat() * 200) - 50);
Collections.rotate(botImages, botRotate);
bottomCards = new CardsPane(botImages, prefSize);
bottomCards.addPropertyChangeListener("flippedCard", propertyChangeHandler);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(4, 4, 4, 4);
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(topCards, gbc);
add(bottomCards, gbc);
} catch (Exception e) {
e.printStackTrace();
}
}
protected Dimension getMaxBounds(BufferedImage[] images) {
int width = 0;
int height = 0;
for (BufferedImage img : images) {
width = Math.max(width, img.getWidth());
height = Math.max(height, img.getHeight());
}
return new Dimension(width, height);
}
}
}