Simulated Annealing Method won't execute - java

Currently i'm trying to create a stimulated annealing algorithm solving the traveling salesman problem as well as creating a gui for it. The initial cities(points) and lines display but I can't get the doSA() method to successfully run. Any ideas, sorta stumped.
class SAPanel extends JPanel implements ActionListener{
private static final long serialVersionUID = 1L;
private City city,city2,city3,city4,city5,city6,city7,city8,city9,city10,city11,city12,city13,city14,city15,city16,city17,city18,city19,city20;
private int temp;
private Tour best, currentSolution;
int delay = 10;
static int POINTWIDTH = 8;
static Color POINTCOLOR = Color.MAGENTA;
static Color LINECOLOR = Color.CYAN;
Timer timer = new Timer(delay, this);
private static double coolingRate = .006;
public void start(){
temp = 10000;
timer.start();
}
public void intiSA(){
city = new City(60, 200);
TourManager.addCity(city);
city2 = new City(180, 200);
TourManager.addCity(city2);
city3 = new City(80, 180);
TourManager.addCity(city3);
city4 = new City(140, 180);
TourManager.addCity(city4);
city5 = new City(20, 160);
TourManager.addCity(city5);
city6 = new City(100, 160);
TourManager.addCity(city6);
city7 = new City(200, 160);
TourManager.addCity(city7);
city8 = new City(140, 140);
TourManager.addCity(city8);
city9 = new City(40, 120);
TourManager.addCity(city9);
city10 = new City(100, 120);
TourManager.addCity(city10);
city11 = new City(180, 100);
TourManager.addCity(city11);
city12 = new City(60, 80);
TourManager.addCity(city12);
city13 = new City(120, 80);
TourManager.addCity(city13);
city14 = new City(180, 60);
TourManager.addCity(city14);
city15 = new City(20, 40);
TourManager.addCity(city15);
city16 = new City(100, 40);
TourManager.addCity(city16);
city17 = new City(200, 40);
TourManager.addCity(city17);
city18 = new City(20, 20);
TourManager.addCity(city18);
city19 = new City(60, 20);
TourManager.addCity(city19);
city20 = new City(160, 20);
TourManager.addCity(city20);
//Initialize initial solution
currentSolution = new Tour();
currentSolution.generateIndividual();
best = currentSolution;
System.out.println("Initial solution distance: " + currentSolution.getDistance());
}
//energy represents the total distance of each tour
public static double acceptanceProbability(int energy, int newEnergy, double temp){
//if currentSolution energy is larger than newEnergy, return 1.0
if(newEnergy < energy){
return 1.0;
}
//as temp decreases, acceptance of the new solution becomes more selective
return Math.exp((energy-newEnergy) / temp);
}
public void doSA(){
//set new solution as the current solution
Tour newSolution = new Tour(currentSolution.getTour());
//get two random points on the solution
int tourPos1 = (int)(newSolution.tourSize() * Math.random());
int tourPos2 = (int)(newSolution.tourSize() * Math.random());
//get two cities depending on the selected points
City citySwap1 = newSolution.getCity(tourPos1);
City citySwap2 = newSolution.getCity(tourPos2);
//swap the cities on the selected points
newSolution.setCity(tourPos1, citySwap2);
newSolution.setCity(tourPos2, citySwap1);
int currentEnergy = currentSolution.getDistance();
int neighborEnergy = currentSolution.getDistance();
//accept new solution as the current solution if greater than random number
if(acceptanceProbability(currentEnergy, neighborEnergy, temp) > Math.random()){
currentSolution = new Tour(newSolution.getTour());
}
//keep the current solution as best if distance is greater
if(currentSolution.getDistance() > newSolution.getDistance()){
best = new Tour(currentSolution.getTour());
}
repaint();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2= (Graphics2D)(g);
g2.setStroke(new BasicStroke(3));
for(int x =0;x<19;x++){
//draw lines connecting each city in solution
g2.setColor(LINECOLOR);
g2.drawLine(best.getCity(x).getX(), best.getCity(x).getY(), best.getCity(x+1).getX(), best.getCity(x+1).getY());
g2.setColor(POINTCOLOR);
//draw all points
g2.fillOval(best.getCity(x).getX() - POINTWIDTH/2, best.getCity(x).getY() - POINTWIDTH/2, POINTWIDTH, POINTWIDTH);
}
//draw last reminding line, connecting last city to first city.
g2.setColor(LINECOLOR);
g2.drawLine(best.getCity(19).getX(), best.getCity(19).getY(), best.getCity(0).getX(), best.getCity(0).getY());
g2.setColor(POINTCOLOR);
g2.fillOval(best.getCity(0).getX() - POINTWIDTH/2, best.getCity(0).getY() - POINTWIDTH/2, POINTWIDTH, POINTWIDTH);
}
public void actionPerformed(ActionEvent e){
temp *= coolingRate -1;
if(temp >1){
doSA();
System.out.println("Final solution distance: " + best.getDistance());
System.out.println("Tour: " + best);
}
else{
((Timer)e.getSource()).stop();
}
}
}

Could be your initial parameters: Simulated Annealing is very parameter sensitive and it requires 2 parameters (initial temp and cooldown schedule), which makes it hard to tweak them. In my implementation, I've reduced it to 1 parameter by basing the cooldown on the amount of time still available.
Could also be a bug in your acceptanceProbability method. Write a unit test, which covers the corner cases, to prove it's correct. Here's my test impl.

Related

JavaFX animation on canvas

I'm a newbie of Java. I tried to make a simple 'binary search tree' program. I have a problem during making so I'm looking for the answer.
When the program was looking for correct place where I added a number in, I wanted to put 'flickering' function during processing, but it works like this. enter image description here
(It's not flickering but just multiplying.)
How can I figure this problem out?
Here is 'add' method that I wrote in controller.
public void handleAddAction(ActionEvent event) {
System.out.println("add ? ?");
String key = addfield.getText();
int length = key.length();
if ( length > 0 ) {
boolean integerornot = isStringInteger(key, 10);
if ( integerornot == true ) {
int intkey = Integer.parseInt(key);
if (bst.size() > 10) {
Alert maxerror = new Alert(Alert.AlertType.WARNING);
maxerror.setTitle("Message");
maxerror.setHeaderText("The maximum number of nodes is 10.");
maxerror.showAndWait();
}else if(bst.contains(intkey)!=null) {
Alert duperror = new Alert(Alert.AlertType.WARNING);
duperror.setTitle("Message");
duperror.setHeaderText("Duplicated numbers cannot be added.");
duperror.showAndWait();
}else if (intkey>=0 && intkey <= 9) {
bst.insert(intkey);
addfield.setText("");
DoubleProperty x = new SimpleDoubleProperty();
DoubleProperty y = new SimpleDoubleProperty();
compareNode(bst.root,intkey);
gc.setStroke(Color.rgb(15, 76, 129));
gc.setFill(Color.WHITE);
gc.fillOval(width-10, height-15, 25, 25);
gc.strokeOval(width-10, height-15, 25, 25);
gc.setFill(Color.rgb(15, 76, 129));
gc.fillText(key, width, height);
if(bst.size()>1) {
gc.strokeLine(width-ratiowidth, height-50 +(25/2), width-ratiowidth, height -50 +(25/2) +10);
gc.strokeLine(width-ratiowidth, height-50 +(25/2)+10, width, height -50 +(25/2) +10);
gc.strokeLine(width, height-50 +(25/2) +10, width, height -(25/2));
gc.fillPolygon(new double [] {width-5, width, width+5}, new double[] {height -(25/2) -10, height -(25/2), height -(25/2)-10}, 3);
Timeline timeline = new Timeline(
new KeyFrame(Duration.seconds(0),
new KeyValue(x, width-ratiowidth),
new KeyValue(y, height-50)
),
new KeyFrame(Duration.millis(10),
new KeyValue(x, width),
new KeyValue(y, height)
)
);
// timeline.setCycleCount(Timeline.INDEFINITE);
AnimationTimer timer = new AnimationTimer() {
public void handle(long now) {
gc.setStroke(Color.BLUE);
gc.strokeOval(x.doubleValue(), y.doubleValue(), 30, 30);
}
} ;
timer.start();
timeline.play();
}
prekey = intkey;
height = 20;
width = 740;
ratiowidth = 740;
} else {
Alert inerror = new Alert(Alert.AlertType.WARNING);
inerror.setTitle("Message");
inerror.setHeaderText("Only numbers from 0 to 9 can be added.");
inerror.showAndWait();
}
}else {
Alert string = new Alert(Alert.AlertType.WARNING);
string.setTitle("Message");
string.setHeaderText("Please insert integer.");
string.showAndWait();
}
}else {
Alert noinput = new Alert(Alert.AlertType.WARNING);
noinput.setTitle("Message");
noinput.setHeaderText("You did not input anything! Please insert value.");
noinput.showAndWait();
}
addfield.setText("");
}
Thank you in advance :)

In Race Program, can not seem to declare winner when it collides with finish line- java

I am creating a code that contains moving graphics in a JPanel. It is a race code with 3 racers. Every time the timer goes through, there is a 75% chance they move, and a 25% chance they hold.
My problem is with getting the program to print out the winner in the system console. For some reason, it always says "Orange" is the winner, just because it is the last color I added.
The intersections are just when the runners touch the finish line. There are a few custom commands but those are just to draw the background and set up the JPanel. Those work fine. The problem is that for some reason, the X value of the 4 runners seems to be every single value at once.
public class Rivals extends JFrame{
Rivals(){
Make.frame(this,new RivalsPane(), 512,512,JFrame.EXIT_ON_CLOSE, false);
}
public static class RivalsPane extends JPanel implements ActionListener{
Timer t = new Timer(1,this);
static int x=70,x2=70,x3=70,x4=70,speed=5;
static boolean done=false;
static String win = " wins", winner;
RivalsPane(){
Make.panel(this,512,512,null);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Make.FootRaceTrack(g);
Run(g);
t.start();
}
public void Run(Graphics g) {
Paint.setPen(Color.blue);
Paint.shadeOval(g,x,90,30,30);
Paint.setPen(Color.pink);
Paint.shadeOval(g,x2,190,30,30);
Paint.setPen(Color.green);
Paint.shadeOval(g, x3, 290, 30, 30);
//This is the last one I set, and it always wins
Paint.setPen(Color.ORANGE);
Paint.shadeOval(g, x4, 390, 30, 30);
Rectangle r1 = new Rectangle(x-30,60, 60, 60);
Rectangle r2 = new Rectangle(x-30,160, 60, 60);
Rectangle r3 = new Rectangle(x-30,260, 60, 60);
Rectangle r4 = new Rectangle(x-30,360, 60, 60);
Rectangle r5 = new Rectangle(400,0,512,512);
if(r1.intersects(r5)) {
speed = 0;
winner ="Blue";
done = true;
} else if(r2.intersects(r5)) {
speed=0;
winner = "Pink";
done = true;
} else if(r3.intersects(r5)) {
speed=0;
winner = "Green";
done = true;
} else if(r4.intersects(r5)) {
speed=0;
winner = "Orange";
done = true;
}
if(done==true) System.out.println(winner + "wins");
}
public void actionPerformed(ActionEvent e) {
double rand1 = Math.random();
double rand2 = Math.random();
double rand3 = Math.random();
double rand4 = Math.random();
if(rand1<.75)x+=speed;
if(rand2<.75)x2+=speed;
if(rand3<.75)x3+=speed;
if(rand4<.75)x4+=speed;
repaint();
}
}
public static void main(String[] args) {
Do.showFrame(new Rivals());
}
}
Cause of your x position for all rectangles depends on x variable and not x2, x3, x4. From comment.
All my bounding rectangles were using x with applies to blue only. Change the x's to x2,x3, and x4 and it works. Credit to #Alex

Java: implementing if statement with switch cases, ArrayIndexOutOfBoundsException

Stack Trace Hi i'm working on a GUI for monopoly and i've reached a stage where i need to get user input that would ask for a specific number of players and would provide a certain number of tokens (monopoly pieces) based on the number of players specified. I've currently hit a problem i feel really shouldn't be as serious as it is where if i do try to specify the number of players for the game i'm hit with a an ArrayIndexOutOfBoundsException and i can't seem to identify where or what is wrong and how to fix it. Thanks for the help in advance and any edits or tips for my code to make it more efficient are also welcome. I will attach all necessary program files.
P.s i posted the full source code as i felt it was necessary as a shortened version wouldn't make things as clear. Thanks again. P.p.s the code does work when i specify the number of players in the source code without asking for user input but stops working when i do specify user input. Monopoly Board Image
package sprint_One;
/*
* Code written by: lagosBoys A layered pane was used to place all components on the frame at the
* desired locations
*/
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
public class UI_Monopoly_Board extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
// Array of coordinates for the position of each square on the board
Point[] locations = {new Point(630, 643), new Point(570, 643), new Point(510, 643),
new Point(450, 643), new Point(390, 643), new Point(330, 643), new Point(270, 643),
new Point(210, 643), new Point(150, 643), new Point(95, 643), new Point(60, 643),
new Point(60, 573), new Point(60, 503), new Point(60, 433), new Point(60, 383),
new Point(60, 323), new Point(60, 273), new Point(60, 213), new Point(60, 153),
new Point(60, 93), new Point(60, 33),
new Point(120, 13), new Point(180, 13), new Point(230, 13), new Point(280, 13),
new Point(340, 13), new Point(400, 13), new Point(460, 13), new Point(520, 13),
new Point(580, 13), new Point(660, 60), new Point(660, 120), new Point(660, 160),
new Point(660, 220), new Point(660, 280), new Point(660, 340), new Point(660, 400),
new Point(660, 460), new Point(660, 520), new Point(660, 580), new Point(660, 640)};
// The default position or starting point which is go
Point defaultPosition = new Point(600, 603);
private int players;
private Token[] token;
private static JPanel infoPanel;
private static JPanel commandPanel;
// creates a fixed length for the text field used by the command field
final static int field_Width = 20;
private static JTextField commandField = new JTextField(field_Width);
private static JLabel commandLabel = new JLabel("Enter Command: ");
private Border blackLineBorder;
private final int ROWS = 35;
private final int COLUMNS = 40;
private JTextArea textArea = new JTextArea(ROWS, COLUMNS);
private static JLabel echoed_Text_Label = new JLabel();
private JLayeredPane layeredPane = getLayeredPane(); // The use of a JLayeredPane allows easier
// and more flexible specification of
// component positions
private static JLabel monopolyImageLabel;
public UI_Monopoly_Board() {
String playerNumber = JOptionPane.showInputDialog("Please enter the number of players");
// int tokenNumber = Integer.parseInt(playerNumber);
// players = 6;
players = Integer.parseInt(playerNumber);
int offset = 10;
// Initialise tokens depending on number of players and spaces them out with offset
if(players >= 2 || players <= 6)
{
token = new Token[players];
switch (players) {
case 2:
token[0] = new Token();
token[0].setBounds(10, 10, 700, 700);
token[0].setPosition(600, 603);
token[1] = new Token(Color.red, null);
token[1].setBounds(10, 10, 700, 700);
token[1].setPosition(600 + offset, 603 + offset);
break;
case 3:
token[0] = new Token();
token[0].setBounds(10, 10, 700, 700);
token[0].setPosition(600, 603);
token[1] = new Token(Color.red, null);
token[1].setBounds(10, 10, 700, 700);
token[1].setPosition(600 + offset, 603 + offset);
offset = offset + 10;
token[2] = new Token(Color.blue, null);
token[2].setBounds(10, 10, 700, 700);
token[2].setPosition(600 + offset, 603 + offset);
break;
case 4:
token[0] = new Token();
token[0].setBounds(10, 10, 700, 700);
token[0].setPosition(600, 603);
token[1] = new Token(Color.red, null);
token[1].setBounds(10, 10, 700, 700);
token[1].setPosition(600 + offset, 603 + offset);
offset = offset + 10;
token[2] = new Token(Color.blue, null);
token[2].setBounds(10, 10, 700, 700);
token[2].setPosition(600 + offset, 603 + offset);
offset = offset + 10;
token[3] = new Token(Color.green, null);
token[3].setBounds(10, 10, 700, 700);
token[3].setPosition(600 + offset, 603 + offset);
break;
case 5:
token[0] = new Token();
token[0].setBounds(10, 10, 700, 700);
token[0].setPosition(600, 603);
token[1] = new Token(Color.red, null);
token[1].setBounds(10, 10, 700, 700);
token[1].setPosition(600 + offset, 603 + offset);
offset = offset + 10;
token[2] = new Token(Color.blue, null);
token[2].setBounds(10, 10, 700, 700);
token[2].setPosition(600 + offset, 603 + offset);
offset = offset + 10;
token[3] = new Token(Color.green, null);
token[3].setBounds(10, 10, 700, 700);
token[3].setPosition(600 + offset, 603 + offset);
offset = offset + 10;
token[4] = new Token(Color.yellow, null);
token[4].setBounds(10, 10, 700, 700);
token[4].setPosition(600 + offset, 603 + offset);
break;
case 6:
token[0] = new Token();
token[0].setBounds(10, 10, 700, 700);
token[0].setPosition(600, 603);
token[1] = new Token(Color.red, null);
token[1].setBounds(10, 10, 700, 700);
token[1].setPosition(600 + offset, 603 + offset);
offset = offset + 10;
token[2] = new Token(Color.blue, null);
token[2].setBounds(10, 10, 700, 700);
token[2].setPosition(600 + offset, 603 + offset);
offset = offset + 10;
token[3] = new Token(Color.green, null);
token[3].setBounds(10, 10, 700, 700);
token[3].setPosition(600 + offset, 603 + offset);
offset = offset + 10;
token[4] = new Token(Color.yellow, null);
token[4].setBounds(10, 10, 700, 700);
token[4].setPosition(600 + offset, 603 + offset);
offset = offset + 10;
token[5] = new Token(Color.cyan, null);
token[5].setBounds(10, 10, 700, 700);
token[5].setPosition(600 + offset, 603 + offset);
break;
default:
System.out.println("Invalid number of players");
}
}
// The location of the image should be specified here
monopolyImageLabel =
new JLabel(new ImageIcon(this.getClass().getResource("Monopoly_board.jpg")));
monopolyImageLabel.setBounds(-50, -30, 800, 750);
// The image and the tokens are added to the pane at different levels allowing them to overlap
layeredPane.add(monopolyImageLabel);
layeredPane.add(token[0], new Integer(1));
layeredPane.add(token[1], new Integer(2));
layeredPane.add(token[2], new Integer(3));
layeredPane.add(token[3], new Integer(4));
layeredPane.add(token[4], new Integer(5));
layeredPane.add(token[5], new Integer(6));
setSize(1500, 750);
setExtendedState(JFrame.MAXIMIZED_BOTH); // Sets the default window for the JFrame as a
// maximised
this.setResizable(false);
setTitle("Welcome to Monopoly");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Ensures the JFrame operation ends completely
// upon exiting the window
setVisible(true);
}
// This method displays the information panel and adds it to the pane
public void information_Panel() {
infoPanel = new JPanel();
JScrollPane scrollPane = new JScrollPane(textArea);
blackLineBorder = BorderFactory.createLineBorder(Color.BLACK);
TitledBorder title = BorderFactory.createTitledBorder(blackLineBorder, "Information Panel");
infoPanel.setBorder(title);
infoPanel.add(echoed_Text_Label, BorderLayout.NORTH);
// prevents any information from being added or deleted from the information panel.
textArea.setEditable(false);
infoPanel.add(scrollPane);
infoPanel.setBounds(750, 0, 600, 600); // specifies the desired coordinates of the panel being
// added to the layered pane
layeredPane.add(infoPanel);
}
// This method displays the command panel and adds it to the pane
public void command_Panel() {
commandPanel = new JPanel();
blackLineBorder = BorderFactory.createLineBorder(Color.BLACK);
JButton button = new JButton("Enter");
/*
* implements the actionlistener interface on the button to help execute a command when the
* button is clicked
*/
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (commandField.getText().isEmpty()) {
String command = null;
textArea.append(command);
}
else {
String command = commandField.getText();
textArea.append(command + "\n");
commandField.setText("");
}
}
});
// This invokes the actionListeners interface for actionPerformed (quick way to implement a key
// listener on the keyboards Enter button)
getRootPane().setDefaultButton(button);
commandPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
button.setPreferredSize(new Dimension(65, 20));
commandPanel.add(commandLabel);
commandPanel.add(commandField);
commandPanel.add(button);
commandPanel.setBounds(800, 630, 500, 50); // specifies the desired coordinates of the panel
// being added to the layered pane
layeredPane.add(commandPanel);
}
// Method which moves the tokens round the board one at a time
public void moveTokens() throws InterruptedException {
int i, j, offset;
offset = 0;
for (i = 0; i < token.length; i++) {
for (j = 0; j < locations.length; j++) {
token[i].setPosition(locations[j].x, locations[j].y);
repaint();
// controls the movement speed of the tokens across the board allowing for easy detection of
// their movement
Thread.sleep(300);
}
token[i].setPosition(defaultPosition.x + offset, defaultPosition.y + offset);
offset = offset + 15;
}
}
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
UI_Monopoly_Board obj = new UI_Monopoly_Board();
obj.information_Panel();
obj.command_Panel();
obj.moveTokens();
[enter image description here][1]
}
}
package sprint_One;
import java.awt.*;
import javax.swing.JComponent;
/*
* Each token has variables for location, dimension and shape, there's a constructor that allows the
* user to specify the colour of the shape the necessary accessor and mutator functions are provided
*/
public class Token extends JComponent {
/**
*
*/
private static final long serialVersionUID = 1L;
private int length;
private int breadth;
private int x;
private int y;
private Shape shape;
private Color color;
private String name;
private int balance;
public Token() {
super();
setVisible(true);
this.length = 15;
this.breadth = 15;
this.x = 5;
this.y = 5;
this.shape = new Rectangle(this.x, this.y, this.length, this.breadth);
this.color = Color.BLACK;
this.name = "";
this.balance = 20;
}
public Token(Color color, String name) {
this();
this.color = color;
this.name = name;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
// Method which specifies the x and y coordinates of the tokens
public void setPosition(int x, int y) {
this.x = x;
this.y = y;
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
super.paintComponent(g);
g2.setColor(color);
g2.fill(shape); // fills the shape with the colour specified
g2.draw(this.shape);
}
public Shape getShape() {
// TODO Auto-generated method stub
return this.shape;
}
}
Ok, you should learn how to use a debugger...
This is the line that causes your error:
layeredPane.add(token[2], new Integer(3));
And you initialise tokenlike this:
if(players >= 2 || players <= 6)
{
token = new Token[players];
So, what if players is 2? You will get an ArrayIndexOutOfBoundsException.
Another tip:
layeredPane.add(token[0], new Integer(1));
is not as readable as
layeredPane.add(token[0], 1);

How to get Specific Array List Item

I have a little issue with selecting from an array list. I am writing some code to enable me fix about 10 JButtons in a circle, I got that right, but then ..... I want to set an actionListener on each of the Buttons, but I don't get it, all the buttons inherit the actions required for one. How do I make it specific,... here's my code.... Thanks in advance!
private JButton quest;
public Beginner() {
int n = 10; // no of JButtons
int radius = 200;
Point center = new Point(250, 250);
double angle = Math.toRadians(360 / n);
List<Point> points = new ArrayList<Point>();
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();
// Layout used
int count = 1;
for (Point point : points) {
quest = new JButton("Question " + count);
quest.setForeground(Color.BLUE);
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(10, 10);
add(panels);
// action Listener to be set on individual buttons
quest.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent a) {
if (quest.equals(points.get(5)))
;
String c = "Hello!";
JOptionPane.showMessageDialog(null, c);
}
});
}
}
The problem is that expression
if (quest.equals(points.get(5)));
does nothing. I guess it should be rewritten like this
if (quest.equals(points.get(5))) {
String c = "Hello!";
JOptionPane.showMessageDialog(null, c);
}
The way I am understanding the question is that you have multiple buttons and you would like each button to have it's own action associated with it. There are a couple ways to go about doing this. Either you create a new ActionListener for each JButton depending which button you are creating.
You can also create a large case/switch or if/else within the ActionListener that gets determined by which button was selected. To do this you can call the getActionCommand() function for the ActionEvent object.
quest.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent a) {
if (a.getActionCommand().equals("Question 1"))
{
String c = "Hello!";
JOptionPane.showMessageDialog(null, c);
}
else if(a.getActionCommand().equals("Question 2"))
{
//have it do something else
}
//and so on so forth
}
});
You need to rethink the entire design. You have this line:
if (quest.equals(points.get(5))) {
But points is a list containing Point objects; points.get(5) returns a Point.
quest is a JButton. How can a JButton instance equal a Point instance?

Need assistance with frogger type game

I'm in the process of creating a frogger type game and have gotten pretty far in getting the program to do what I want it to do. However, I'm starting to think that to finish the game I will have to use way to much code and there must be a simpler way achieve the same results. I'm not looking for an answer, just need some more information.
Question 1: What can I use for the images that represent the moving Icons or cars? I'm currently using JButtons. The problem is that is difficult to get the buttons to move uniformly and I want to use 24 different moving Icons and from what I've learned so far I will have to add a new JButton for each icon.
Question 2: The way that I've gotten the Jbutton icons to move is to use a timer delay and then a counter to increment the x values. This works for the most part, but is there a better, perhaps simpler, way to move icons across the screen?
Any tips, tutorials etc are greatly appreciated.
Here is one of the classes that I've created to get movement of the icons:
public class EnemyJPanel extends JButton {
JButton enem = new JButton();
JButton enem12 = new JButton();
JButton enem13 = new JButton();
JButton enem1 = new JButton("1");
JButton enem2 = new JButton("2");
JButton enem3 = new JButton("3");
JButton enem4 = new JButton("4");
JButton score = new JButton("Score");
JButton enem5 = new JButton("5");
JButton enem6 = new JButton("6");
JButton enem7 = new JButton("7");
JButton enem8 = new JButton("8");
JButton yard = new JButton("50 Yard Line");
int i = 16;
int u = 576;
int d = 16;
int n = 576;
int k = 16;
int l = 16;
int dummyval = 16;
public EnemyJPanel(){
super();
setLayout(null);
enem1.setBounds(16,300,40,55);
enem2.setBounds(16,245,40,55);
enem3.setBounds(16,190,40,55);
enem4.setBounds(16,135,40,55);
score.setBounds(16,80,601,55);
yard.setBounds(16,355,601,55);
enem5.setBounds(16,410,40,55);
enem6.setBounds(16,465,40,55);
enem7.setBounds(16,520,40,55);
enem8.setBounds(16,575,40,55);
enem12.setBounds(16,300,40,55);
enem13.setBounds(16,300,40,55);
add(enem1);
add(enem2);
add(enem3);
add(enem4);
add(score);
}
public void addEnemy(){
enem1.setBounds(16,300,40,55);
enem2.setBounds(16,245,40,55);
enem3.setBounds(16,190,40,55);
enem4.setBounds(16,135,40,55);
score.setBounds(16,80,601,55);
add(enem1);
add(enem2);
add(enem3);
add(enem4);
add(score);
}
public void enemyMovement(){
i++;u--;d++;n--; // increments lateral movement from a timer in
dummyval++; // the dummy value is needed to keep the icons looping
dummyval = dummyval + 2;
enem1.setBounds(i,300,40,55);
i = i + 2;
if (dummyval > 176){
k++; k = k + 2;
enem12.setBounds(k,300,40,55);
}
if (k > 176){
l++;
l = l + 2;
enem13.setBounds(l,300,40,55);
}
enem2.setBounds(u,245,40,55);
enem3.setBounds(d,190,40,55);
enem4.setBounds(n,135,40,55);
enem5.setBounds(i,410,40,55);
enem6.setBounds(u,465,40,55);
enem7.setBounds(d,520,40,55);
enem8.setBounds(n,575,40,55);
if(i > 576){ // resets button
i = 16;
}
if(k > 576){
k = 16;
}
if(u < 16){
u = 576;
}
u = u - 2; // increase lateral speed
if(d == 576) {
d = 16;
}
if(n < 16){
n = 576;
}
n = n - 5; //increases lateral speed
}
}
The problem is created because you try to manage all the "stuff" separately. It looks like you may be missing some basic information on classes
First, I would create a custom class, something like
class ButtonObject extends JButton
{
public ButtonObject(String text, int x, int y, int width, int height)
{
super(text);
this.setBounds(x, y, width, height);
}
}
You also may want to take a look at arrays and create an array of your new ButtonObject.
The for loop will help you get through all the objects in your array.
ButtonObject[] enemies = new ButtonObject[10];
for (int i = 0; i < 10; i++)
{
String text = String.valueOf(i);
int y = 300 - (i * 55);
enemies[i] = new ButtonObject(text, 16, y, 40, 55);
}
There is probably a better way to do it than buttons but you may want to stick with them for now for simplicity.

Categories