Last active
September 28, 2016 21:55
-
-
Save metropolian/60a7738c39f3c7ce70939d968bd32985 to your computer and use it in GitHub Desktop.
Java Assignments using Swing JFrame
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package assignments; | |
import java.awt.*; | |
import java.awt.event.ActionEvent; | |
import java.awt.event.ActionListener; | |
import javax.imageio.plugins.bmp.BMPImageWriteParam; | |
import javax.swing.*; | |
import javax.xml.bind.ParseConversionEvent; | |
public class BMR extends JFrame { | |
private JPanel panel; | |
private JPanel panelright; | |
private JLabel labelresult; | |
private JLabel labelgender; | |
private JRadioButton radiogenderfemale; | |
private JRadioButton radiogendermale; | |
private ButtonGroup radiogendergroup; | |
private JLabel labelage; | |
private JTextArea textyear; | |
private JLabel labelyears; | |
private JPanel panelgender; | |
private Container panelage; | |
private JPanel panelunit; | |
private JLabel labelunit; | |
private JRadioButton radiounitus; | |
private JRadioButton radiounitmetric; | |
private ButtonGroup radiounitgroup; | |
private JPanel panelweight; | |
private JLabel labelweight; | |
private JTextArea textweight; | |
private JLabel labelkg; | |
private JPanel panelheight; | |
private JLabel labelheight; | |
private JTextArea textheight; | |
private JLabel labelmeters; | |
public BMR() { | |
setTitle(getClass().getSimpleName()); | |
Container pane = getContentPane(); | |
pane.setLayout(new BorderLayout()); | |
GridBagConstraints gbc; | |
panel = new JPanel(); | |
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); | |
panel.setBorder(BorderFactory.createTitledBorder("Person Information")); | |
add(panel, BorderLayout.CENTER); | |
// gender | |
panelgender = new JPanel(new FlowLayout()); | |
panel.add(panelgender); | |
labelgender = new JLabel("Gender: "); | |
panelgender.add(labelgender); | |
radiogenderfemale = new JRadioButton("Female"); | |
radiogendermale = new JRadioButton("Male"); | |
panelgender.add(radiogenderfemale); | |
panelgender.add(radiogendermale); | |
radiogendergroup = new ButtonGroup(); | |
radiogendergroup.add(radiogenderfemale); | |
radiogendergroup.add(radiogendermale); | |
// age | |
panelage = new JPanel(new FlowLayout()); | |
panel.add(panelage); | |
labelage = new JLabel("Age: "); | |
textyear = new JTextArea(1, 5); | |
labelyears = new JLabel("years"); | |
panelage.add(labelage); | |
panelage.add(textyear); | |
panelage.add(labelyears); | |
// unit system | |
panelunit = new JPanel(new FlowLayout()); | |
panel.add(panelunit); | |
labelunit = new JLabel("Select unit systems: "); | |
panelunit.add(labelunit); | |
radiounitus = new JRadioButton("US"); | |
radiounitmetric = new JRadioButton("Metric"); | |
panelunit.add(radiounitus); | |
panelunit.add(radiounitmetric); | |
radiounitgroup = new ButtonGroup(); | |
radiounitgroup.add(radiounitus); | |
radiounitgroup.add(radiounitmetric); | |
// weight | |
panelweight = new JPanel(new FlowLayout()); | |
panel.add(panelweight); | |
labelweight = new JLabel("Weight: "); | |
textweight = new JTextArea(1, 5); | |
labelkg = new JLabel("Kilograms"); | |
panelweight.add(labelweight); | |
panelweight.add(textweight); | |
panelweight.add(labelkg); | |
// height | |
panelheight = new JPanel(new FlowLayout()); | |
panel.add(panelheight); | |
labelheight = new JLabel("Height: "); | |
textheight = new JTextArea(1, 5); | |
labelmeters = new JLabel("Meters"); | |
panelheight.add(labelheight); | |
panelheight.add(textheight); | |
panelheight.add(labelmeters); | |
// right button | |
panelright = new JPanel(); | |
JButton btcalc = new JButton("Calculate"); | |
panelright.add(btcalc); | |
add(panelright, BorderLayout.EAST); | |
btcalc.addActionListener(new ActionListener() { | |
@Override | |
public void actionPerformed(ActionEvent e) { | |
calculate(); | |
} | |
}); | |
labelresult = new JLabel("---"); | |
add(labelresult, BorderLayout.SOUTH); | |
pack(); | |
setSize(500, 500); | |
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | |
setLocationRelativeTo(null); | |
setVisible(true); | |
} | |
public void calculate(){ | |
int gender = 0; | |
if (radiogenderfemale.isSelected()) | |
gender = 1; | |
else if (radiogendermale.isSelected()) | |
gender = 2; | |
int ut = 0; | |
if (radiounitus.isSelected()) | |
ut = 1; | |
else if (radiounitmetric.isSelected()) | |
ut = 2; | |
float age = floatValue(textyear.getText() , 0); | |
float w = floatValue(textweight.getText(), 0); | |
float h = floatValue(textheight.getText(), 0); | |
float bmr = 0; | |
// convert to us | |
if (ut == 2) { | |
h *= 39.37; | |
w *= 2.205; | |
} | |
if (gender == 1) { | |
bmr = (float) (((4.7 * h) + 4.35 * w - 4.7 * age) + 655.0); | |
} else if (gender == 2) { | |
bmr = (float) ((12.7 * h + 6.23 * w - 6.8 * age) + 66.0); | |
} | |
String msg = ""; | |
if ((ut == 0) || (gender == 0) || (age == 0) || (w == 0) || (h == 0)) { | |
msg = "Please enter correct value."; | |
} else { | |
msg = "Your BMR is : " + String.valueOf(bmr); | |
} | |
labelresult.setText(msg); | |
JOptionPane.showMessageDialog(this, msg); | |
} | |
public float floatValue(String text, float def){ | |
try { | |
return Float.parseFloat(text); | |
} catch (Exception e) { | |
} | |
return def; | |
} | |
public static void main(String[] args) { | |
/** IMPJ-MAIN */ | |
// set look and feel to the system look and feel | |
try { | |
// UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); | |
} catch (Exception ex) { | |
ex.printStackTrace(); | |
} | |
SwingUtilities.invokeLater(new Runnable() { | |
@Override | |
public void run() { | |
new BMR().setVisible(true); | |
} | |
}); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package assignments; | |
import java.awt.*; | |
import java.awt.event.ActionEvent; | |
import java.awt.event.ActionListener; | |
import javax.swing.*; | |
public class Flower extends JFrame { | |
public Timer animtimer; | |
public FlowerPanel panel; | |
public Flower() { | |
setTitle(getClass().getSimpleName()); | |
Container pane = getContentPane(); | |
pane.setLayout(new GridBagLayout()); | |
GridBagConstraints gbc; | |
panel = new FlowerPanel(); | |
gbc = new GridBagConstraints(); | |
gbc.gridx = 0; | |
gbc.gridy = 0; | |
gbc.weightx = 1; | |
gbc.weighty = 5; | |
gbc.fill = GridBagConstraints.BOTH; | |
add(panel, gbc); | |
JButton bt_animation = new JButton("Toggle Animation"); | |
gbc = new GridBagConstraints(); | |
gbc.gridx = 0; | |
gbc.gridy = 1; | |
gbc.weightx = 1; | |
gbc.weighty = 1; | |
gbc.fill = GridBagConstraints.BOTH; | |
add(bt_animation, gbc); | |
animtimer = new Timer(300, new ActionListener() { | |
@Override | |
public void actionPerformed(ActionEvent e) { | |
drawAnimation(); | |
} | |
} ); | |
bt_animation.addActionListener(new ActionListener() { | |
@Override | |
public void actionPerformed(ActionEvent e) { | |
toggleAnimation(); | |
} | |
}); | |
pack(); | |
setSize(500, 500); | |
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | |
setLocationRelativeTo(null); | |
setVisible(true); | |
reset(Color.RED, 10); | |
} | |
public void toggleAnimation() { | |
if (!animtimer.isRunning()) { | |
animtimer.start(); | |
} else { | |
animtimer.stop(); | |
} | |
} | |
public void reset(Color color, int petal) { | |
panel.color = color; | |
panel.maxpetals = petal; | |
panel.petals = petal; | |
} | |
public int getNoPetalLeft() { | |
return panel.petals; | |
} | |
public void drawAnimation(){ | |
if (panel.petals > 0) { | |
panel.petals--; | |
} else { | |
reset(panel.color, panel.maxpetals); | |
} | |
panel.repaint(); | |
} | |
public class FlowerPanel extends JPanel | |
{ | |
public Color color = Color.GREEN; | |
public int maxpetals = 10; | |
public int petals = 10; | |
public FlowerPanel() { | |
} | |
public void paintComponent(Graphics g) { | |
super.paintComponent(g); | |
Graphics2D g2d = (Graphics2D) g.create(); | |
int width = getWidth(); | |
int height = getHeight(); | |
int cx = width / 2; | |
int cy = height / 2; | |
g2d.setColor(color); | |
int ps = 360 / maxpetals; | |
int cnt = 0; | |
for(int a = 360; a > 0; a -= ps ) { | |
if (cnt >= petals) | |
break; | |
g2d.fillArc(0, 0, width, height, a, ps / 2); | |
cnt++; | |
} | |
g2d.dispose(); | |
} | |
} | |
public static void main(String[] args) { | |
/** IMPJ-MAIN */ | |
// set look and feel to the system look and feel | |
try { | |
// UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); | |
} catch (Exception ex) { | |
ex.printStackTrace(); | |
} | |
SwingUtilities.invokeLater(new Runnable() { | |
@Override | |
public void run() { | |
new BMR().setVisible(true); | |
} | |
}); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package assignments; | |
import java.awt.*; | |
import java.awt.event.ActionEvent; | |
import java.awt.event.ActionListener; | |
import javax.swing.*; | |
/** | |
* This program demonstrates how to use JPanel in Swing. | |
* @author www.codejava.net | |
*/ | |
public class Flower2 extends JFrame { | |
public Timer animtimer; | |
public FlowerPanel panel; | |
public JPanel panelconfig; | |
private JLabel labelpedal; | |
private JSlider sliderpedal; | |
private JLabel labelcolor; | |
private JButton btnewflower; | |
private JComboBox<String> comboboxcolor; | |
public Flower2() { | |
setTitle(getClass().getSimpleName()); | |
Container pane = getContentPane(); | |
pane.setLayout(new GridBagLayout()); | |
GridBagConstraints gbc; | |
panel = new FlowerPanel(); | |
gbc = new GridBagConstraints(); | |
gbc.gridx = 0; | |
gbc.gridy = 0; | |
gbc.weightx = 1; | |
gbc.weighty = 5; | |
gbc.fill = GridBagConstraints.BOTH; | |
add(panel, gbc); | |
// bound panel | |
panelconfig = new JPanel(); | |
panelconfig.setBorder(BorderFactory.createTitledBorder("Flower Types")); | |
labelpedal = new JLabel("Max Pedal No:"); | |
panelconfig.add(labelpedal); | |
sliderpedal = new JSlider(5, 12, 5); | |
sliderpedal.setPaintTicks(true); | |
sliderpedal.setPaintLabels(true); | |
sliderpedal.setMajorTickSpacing(1); | |
sliderpedal.setMinorTickSpacing(1); | |
panelconfig.add(sliderpedal); | |
labelcolor = new JLabel("Color:"); | |
panelconfig.add(labelcolor); | |
String[] colors = new String[] {"Blue", "Green", "Red"}; | |
comboboxcolor = new JComboBox<>(colors); | |
panelconfig.add(comboboxcolor); | |
btnewflower = new JButton("New Flower"); | |
btnewflower.addActionListener(new ActionListener() { | |
@Override | |
public void actionPerformed(ActionEvent e) { | |
Color color = Color.BLACK; | |
switch (comboboxcolor.getSelectedIndex()) { | |
case 0: | |
color = Color.BLUE; | |
break; | |
case 1: | |
color = Color.GREEN; | |
break; | |
case 2: | |
color = Color.RED; | |
break; | |
} | |
int petals = sliderpedal.getValue(); | |
reset(color, petals); | |
} | |
}); | |
panelconfig.add(btnewflower); | |
gbc = new GridBagConstraints(); | |
gbc.gridx = 0; | |
gbc.gridy = 1; | |
gbc.weightx = 1; | |
gbc.weighty = 1; | |
gbc.fill = GridBagConstraints.BOTH; | |
add(panelconfig, gbc); | |
animtimer = new Timer(300, new ActionListener() { | |
@Override | |
public void actionPerformed(ActionEvent e) { | |
drawAnimation(); | |
} | |
} ); | |
pack(); | |
setSize(500, 500); | |
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | |
setLocationRelativeTo(null); | |
setVisible(true); | |
reset(Color.RED, 10); | |
} | |
public void toggleAnimation() { | |
if (!animtimer.isRunning()) { | |
animtimer.start(); | |
} else { | |
animtimer.stop(); | |
} | |
} | |
public void reset(Color color, int petal) { | |
panel.color = color; | |
panel.maxpetals = petal; | |
panel.petals = petal; | |
panel.repaint(); | |
} | |
public int getNoPetalLeft() { | |
return panel.petals; | |
} | |
public void drawAnimation(){ | |
if (panel.petals > 0) { | |
panel.petals--; | |
} else { | |
reset(panel.color, panel.maxpetals); | |
} | |
panel.repaint(); | |
} | |
public class FlowerPanel extends JPanel | |
{ | |
public Color color = Color.GREEN; | |
public int maxpetals = 10; | |
public int petals = 10; | |
public FlowerPanel() { | |
} | |
public void paintComponent(Graphics g) { | |
super.paintComponent(g); | |
Graphics2D g2d = (Graphics2D) g.create(); | |
int width = getWidth(); | |
int height = getHeight(); | |
int cx = width / 2; | |
int cy = height / 2; | |
g2d.setColor(color); | |
int ps = 360 / maxpetals; | |
int cnt = 0; | |
for(int a = 360; a > 0; a -= ps ) { | |
if (cnt >= petals) | |
break; | |
g2d.fillArc(0, 0, width, height, a, ps / 2); | |
cnt++; | |
} | |
g2d.dispose(); | |
} | |
} | |
public static void main(String[] args) { | |
/** IMPJ-MAIN */ | |
// set look and feel to the system look and feel | |
try { | |
// UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); | |
} catch (Exception ex) { | |
ex.printStackTrace(); | |
} | |
SwingUtilities.invokeLater(new Runnable() { | |
@Override | |
public void run() { | |
new Flower2().setVisible(true); | |
} | |
}); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package assignments; | |
import java.awt.*; | |
import java.awt.event.ActionEvent; | |
import java.awt.event.ActionListener; | |
import java.awt.image.BufferedImage; | |
import java.awt.image.ImageObserver; | |
import java.io.Console; | |
import java.io.File; | |
import java.nio.file.Paths; | |
import java.security.cert.PKIXCertPathBuilderResult; | |
import javax.imageio.ImageIO; | |
import javax.swing.*; | |
public class LoveMeNot extends JFrame { | |
public Timer animtimer; | |
public FlowerPanel panelflower; | |
public JPanel panelconfig; | |
private JLabel labelpedal; | |
private JSlider sliderpedal; | |
private JLabel labelcolor; | |
private JButton btnewflower; | |
private JComboBox<String> comboboxcolor; | |
private Panel paneltop; | |
private Panel panelresult; | |
private JButton btdrawpedal; | |
private ImagePanel panelresultimage; | |
private Boolean loveme = false; | |
public LoveMeNot() { | |
setTitle(getClass().getSimpleName()); | |
Container pane = getContentPane(); | |
pane.setLayout(new GridBagLayout()); | |
GridBagConstraints gbc; | |
paneltop = new Panel(new GridLayout(1, 2)); | |
gbc = new GridBagConstraints(); | |
gbc.gridx = 0; | |
gbc.gridy = 0; | |
gbc.weightx = 1; | |
gbc.weighty = 5; | |
gbc.fill = GridBagConstraints.BOTH; | |
add(paneltop, gbc); | |
panelflower = new FlowerPanel(); | |
paneltop.add(panelflower); | |
panelresult = new Panel(new GridBagLayout()); | |
btdrawpedal = new JButton("Pull one pedal ..."); | |
btdrawpedal.addActionListener(new ActionListener() { | |
@Override | |
public void actionPerformed(ActionEvent e) { | |
pullPedal(); | |
} | |
}); | |
gbc = new GridBagConstraints(); | |
gbc.gridx = 0; | |
gbc.gridy = 0; | |
gbc.weightx = 1; | |
gbc.weighty = 1; | |
gbc.insets = new Insets(20, 20, 20, 20); | |
gbc.fill = GridBagConstraints.BOTH; | |
panelresult.add(btdrawpedal, gbc); | |
panelresultimage = new ImagePanel(); | |
//panelresultimage.setPicture(Paths.get(".").toAbsolutePath() + "/test.jpg"); | |
gbc = new GridBagConstraints(); | |
gbc.gridx = 0; | |
gbc.gridy = 1; | |
gbc.weightx = 1; | |
gbc.weighty = 5; | |
gbc.fill = GridBagConstraints.BOTH; | |
panelresult.add(panelresultimage, gbc); | |
paneltop.add(panelresult, gbc); | |
// bound panel | |
panelconfig = new JPanel(); | |
panelconfig.setBorder(BorderFactory.createTitledBorder("Flower Types")); | |
labelpedal = new JLabel("Max Pedal No:"); | |
panelconfig.add(labelpedal); | |
sliderpedal = new JSlider(5, 12, 5); | |
sliderpedal.setPaintTicks(true); | |
sliderpedal.setPaintLabels(true); | |
sliderpedal.setMajorTickSpacing(1); | |
sliderpedal.setMinorTickSpacing(1); | |
panelconfig.add(sliderpedal); | |
labelcolor = new JLabel("Color:"); | |
panelconfig.add(labelcolor); | |
String[] colors = new String[] {"Blue", "Green", "Red"}; | |
comboboxcolor = new JComboBox<>(colors); | |
panelconfig.add(comboboxcolor); | |
btnewflower = new JButton("New Flower"); | |
btnewflower.addActionListener(new ActionListener() { | |
@Override | |
public void actionPerformed(ActionEvent e) { | |
Color color = Color.BLACK; | |
switch (comboboxcolor.getSelectedIndex()) { | |
case 0: | |
color = Color.BLUE; | |
break; | |
case 1: | |
color = Color.GREEN; | |
break; | |
case 2: | |
color = Color.RED; | |
break; | |
} | |
int petals = sliderpedal.getValue(); | |
reset(color, petals); | |
} | |
}); | |
panelconfig.add(btnewflower); | |
gbc = new GridBagConstraints(); | |
gbc.gridx = 0; | |
gbc.gridy = 1; | |
gbc.weightx = 1; | |
gbc.weighty = 1; | |
gbc.fill = GridBagConstraints.BOTH; | |
add(panelconfig, gbc); | |
animtimer = new Timer(300, new ActionListener() { | |
@Override | |
public void actionPerformed(ActionEvent e) { | |
drawAnimation(); | |
} | |
} ); | |
pack(); | |
setSize(1000, 500); | |
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | |
setLocationRelativeTo(null); | |
setVisible(true); | |
reset(Color.RED, 10); | |
} | |
protected void pullPedal() { | |
if (panelflower.petals > 0) { | |
loveme = !loveme; | |
panelflower.petals--; | |
panelflower.repaint(); | |
String fname = Paths.get(".").toAbsolutePath() + "/"; | |
if (loveme) | |
fname += "loveme.png"; | |
else | |
fname += "notloveme.png"; | |
panelresultimage.setPicture(fname); | |
} | |
if (panelflower.petals == 0) { | |
String msg = ""; | |
if (loveme) | |
msg = "That person love me!"; | |
else | |
msg = "That person love me NOT!"; | |
JOptionPane.showMessageDialog(this, msg); | |
} | |
} | |
public void toggleAnimation() { | |
if (!animtimer.isRunning()) { | |
animtimer.start(); | |
} else { | |
animtimer.stop(); | |
} | |
} | |
public void reset(Color color, int petal) { | |
panelflower.color = color; | |
panelflower.maxpetals = petal; | |
panelflower.petals = petal; | |
panelflower.repaint(); | |
} | |
public int getNoPetalLeft() { | |
return panelflower.petals; | |
} | |
public void drawAnimation(){ | |
if (panelflower.petals > 0) { | |
panelflower.petals--; | |
} else { | |
reset(panelflower.color, panelflower.maxpetals); | |
} | |
panelflower.repaint(); | |
} | |
public class FlowerPanel extends JPanel | |
{ | |
public Color color = Color.GREEN; | |
public int maxpetals = 10; | |
public int petals = 10; | |
public FlowerPanel() { | |
} | |
public void paintComponent(Graphics g) { | |
super.paintComponent(g); | |
Graphics2D g2d = (Graphics2D) g.create(); | |
int width = getWidth(); | |
int height = getHeight(); | |
int cx = width / 2; | |
int cy = height / 2; | |
g2d.setColor(color); | |
int ps = 360 / maxpetals; | |
int cnt = 0; | |
for(int a = 360; a > 0; a -= ps ) { | |
if (cnt >= petals) | |
break; | |
g2d.fillArc(0, 0, width, height, a, ps / 2); | |
cnt++; | |
} | |
g2d.dispose(); | |
} | |
} | |
public class ImagePanel extends JPanel | |
{ | |
private BufferedImage image; | |
public void setPicture(String fname) { | |
try { | |
File file = new File(fname); | |
System.out.println(fname); | |
image = ImageIO.read(file); | |
repaint(); | |
} catch (Exception e) { | |
// TODO: handle exception | |
System.out.println(e.toString()); | |
} | |
} | |
@Override | |
protected void paintComponent(Graphics g) { | |
// TODO Auto-generated method stub | |
super.paintComponent(g); | |
//g.setColor(Color.BLACK); | |
//g.fillRect(0, 0, getWidth(), getHeight()); | |
if (image != null) { | |
g.drawImage(image, 0, 0, getWidth(), getHeight(), null); | |
} | |
} | |
} | |
public static void main(String[] args) { | |
/** IMPJ-MAIN */ | |
// set look and feel to the system look and feel | |
try { | |
// UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); | |
} catch (Exception ex) { | |
ex.printStackTrace(); | |
} | |
SwingUtilities.invokeLater(new Runnable() { | |
@Override | |
public void run() { | |
new LoveMeNot().setVisible(true); | |
} | |
}); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package assignments; | |
import java.awt.*; | |
import java.awt.event.ActionEvent; | |
import java.awt.event.ActionListener; | |
import java.util.Random; | |
import javax.imageio.plugins.bmp.BMPImageWriteParam; | |
import javax.swing.*; | |
import javax.xml.bind.ParseConversionEvent; | |
import org.omg.CORBA.portable.ApplicationException; | |
import org.omg.PortableServer.ServantRetentionPolicyValue; | |
public class SliderGame extends JFrame { | |
private JMenuBar menubar; | |
private JMenu menugame; | |
private JMenuItem menuquit; | |
private JMenuItem menurandom; | |
private SliderGameFrame panelslider; | |
private JButton btrandom; | |
private JPanel panelbottom; | |
private int cols = 3; | |
private int rows = 3; | |
private int[][] board; | |
public SliderGame() { | |
setTitle(getClass().getSimpleName()); | |
Container pane = getContentPane(); | |
pane.setLayout(new BorderLayout()); | |
// menubar | |
menubar = new JMenuBar(); | |
setJMenuBar(menubar); | |
menugame = new JMenu("Game"); | |
menubar.add(menugame); | |
menurandom = new JMenuItem("Random"); | |
menurandom.addActionListener(new ActionListener() { | |
@Override | |
public void actionPerformed(ActionEvent e) { | |
randomBoard(); | |
} | |
}); | |
menugame.add(menurandom); | |
menuquit = new JMenuItem("Quit"); | |
menuquit.addActionListener(new ActionListener() { | |
@Override | |
public void actionPerformed(ActionEvent e) { | |
System.exit(0); | |
} | |
}); | |
menugame.add(menuquit); | |
// game slider panel | |
panelslider = new SliderGameFrame(rows, cols); | |
add(panelslider, BorderLayout.CENTER); | |
panelslider.setButtonActionListener(new ActionListener() { | |
@Override | |
public void actionPerformed(ActionEvent e) { | |
String[] cmd = e.getActionCommand().split("|"); | |
int x = Integer.parseInt(cmd[0]); | |
int y = Integer.parseInt(cmd[2]); | |
//JOptionPane.showMessageDialog(null, cmd[0] + cmd[2]); | |
moveNo(y, x); | |
} | |
}); | |
// bottom panel | |
panelbottom = new JPanel(); | |
btrandom = new JButton("Random"); | |
btrandom.addActionListener(new ActionListener() { | |
@Override | |
public void actionPerformed(ActionEvent e) { | |
randomBoard(); | |
} | |
}); | |
panelbottom.add(btrandom); | |
add(panelbottom, BorderLayout.SOUTH); | |
pack(); | |
setSize(640, 640); | |
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | |
setLocationRelativeTo(null); | |
setVisible(true); | |
} | |
public int getBoardAt(int row, int col) { | |
if ((row >= 0) && (row < rows)) { | |
if ((col >= 0) && (col < cols)) { | |
return board[row][col]; | |
} | |
} | |
return -5; | |
} | |
public void shuffleArray(int[] ar) | |
{ | |
// If running on Java 6 or older, use `new Random()` on RHS here | |
Random rnd = new Random(); | |
for (int i = ar.length - 1; i > 0; i--) | |
{ | |
int index = rnd.nextInt(i + 1); | |
// Simple swap | |
int a = ar[index]; | |
ar[index] = ar[i]; | |
ar[i] = a; | |
} | |
} | |
public void randomBoard() { | |
int sz = rows * cols; | |
int[] lists = new int[sz]; | |
for(int i = 0; i < sz; i++) { | |
if (i == sz -1 ) | |
lists[i] = -1; | |
else | |
lists[i] = i+1; | |
} | |
//shuffleArray(lists); | |
int i = 0; | |
board = new int[rows][cols]; | |
for(int y = 0; y < board.length; y++) { | |
for(int x = 0; x < board[y].length; x++) { | |
board[y][x] = lists[i++]; | |
} | |
} | |
panelslider.setData(board); | |
} | |
public boolean checkCorrect() { | |
int sz = (rows * cols); | |
int i = 0; | |
for(int y = 0; y < board.length; y++) { | |
for(int x = 0; x < board[y].length; x++) { | |
int v = board[y][x]; | |
if (i == sz -1) { | |
if (board[y][x] != -1) { | |
return false; | |
} | |
} else if (board[y][x] != i+1) { | |
return false; | |
} | |
i++; | |
} | |
} | |
return true; | |
} | |
public void moveNo(int row, int col) { | |
int v = getBoardAt(row, col); | |
//System.out.println(String.valueOf(row)+"/"+String.valueOf(col)+"="+String.valueOf(v)); | |
if (v > 0) { | |
if (getBoardAt(row-1, col) == -1) { | |
board[row][col] = board[row-1][col]; | |
board[row-1][col] = v; | |
} else if (getBoardAt(row+1, col) == -1) { | |
board[row][col] = board[row+1][col]; | |
board[row+1][col] = v; | |
} else if (getBoardAt(row, col-1) == -1) { | |
board[row][col] = board[row][col-1]; | |
board[row][col-1] = v; | |
} else if (getBoardAt(row, col+1) == -1) { | |
board[row][col] = board[row][col+1]; | |
board[row][col+1] = v; | |
} else { | |
JOptionPane.showMessageDialog(null, "Invalid move!"); | |
} | |
} | |
panelslider.setData(board); | |
if (checkCorrect()) { | |
JOptionPane.showMessageDialog(null, "Congratulations!"); | |
} | |
} | |
public class SliderGameFrame extends JPanel { | |
public JButton[][] cells; | |
public SliderGameFrame(int rows, int cols) { | |
cells = new JButton[rows][cols]; | |
setLayout(new GridLayout(rows, cols)); | |
Font font = new Font("Tahoma", Font.BOLD, 24); | |
int value = 1; | |
for(int y = 0; y < cells.length; y++) { | |
for(int x = 0; x < cells[y].length; x++) { | |
JButton button = new JButton(String.valueOf(value)); | |
button.setFont(font); | |
button.setActionCommand(String.valueOf(x) + "|" + String.valueOf(y)); | |
cells[y][x] = button; | |
add(button); | |
value++; | |
} | |
} | |
} | |
public void setButtonActionListener(ActionListener listener) { | |
for(int y = 0; y < cells.length; y++) { | |
for(int x = 0; x < cells[y].length; x++) { | |
cells[y][x].addActionListener(listener); | |
} | |
} | |
} | |
public void setData(int[][] data) { | |
for(int y = 0; y < data.length; y++) { | |
for(int x = 0; x < data[y].length; x++) { | |
int value = data[y][x]; | |
String text = ""; | |
if (value > 0) | |
text = String.valueOf(value); | |
cells[y][x].setText(text); | |
} | |
} | |
} | |
} | |
public float floatValue(String text, float def){ | |
try { | |
return Float.parseFloat(text); | |
} catch (Exception e) { | |
} | |
return def; | |
} | |
public static void main(String[] args) { | |
/** IMPJ-MAIN */ | |
// set look and feel to the system look and feel | |
try { | |
// UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); | |
} catch (Exception ex) { | |
ex.printStackTrace(); | |
} | |
SwingUtilities.invokeLater(new Runnable() { | |
@Override | |
public void run() { | |
new SliderGame().setVisible(true); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment