Unreachable Statement with a JFrame - jframe

I have created a program to display red and black boxes. When I compile it there is an error saying that the variable I used to declare for my JFrame to set visible is an unreachable statement. I don't know what I am doing wrong.
import javax.swing.*;
import java.awt.*;
public class test {
public static void main(String[] args) {
JFrame theGUI = new JFrame();
theGUI.setTitle("Colour");
theGUI.setSize(300, 300);
theGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container pane = theGUI.getContentPane();
pane.setLayout(new GridLayout(8, 8));
Color color1 = Color.black;
Color color2 = Color.red;
for (int i = 1; 1 <= 64; i++){
JPanel panel = new JPanel();
//Alternate colors on a row
if (i % 2 == 0)
panel.setBackground(color1);
else
panel.setBackground(color2);
pane.add(panel);
// at the end of a row start next row on the other color1
if ( i % 8 == 0){
Color temp = color1;
color1 = color2;
color2 = temp;
}
}
theGUI.setVisible(true);
}
}

I am sure you have figured it out by now. The loop condition is wrong...says 1 <= 64, should be i <= 64...
/Mattias

Related

Add percent to boxes of image after prediction?

I'm working with darknet and want to add the prediction in percent next to the label with darknet like this:
rather than the default like this:
Is there a way to do this? after you've run darknet it displays the probability that the label surrounding the object is the actual label. This is what i want to add to the image itself.
I figured out how to add it. I've added the code for anyone with the same question in the future so it's copy and paste. remember to re-make darknet afterwards.
We need to replace draw_directions function in darknet/src/image.c with the following:
void draw_detections(image im, detection *dets, int num, float thresh, char **names, image **alphabet, int classes)
{
int i,j;
for(i = 0; i < num; ++i){
char labelstr[4096] = {0};
int class = -1;
for(j = 0; j < classes; ++j){
if (dets[i].prob[j] > thresh){
if (class < 0) {
/* this line adds the percent to the image*/
sprintf(labelstr,"%s %f%%",names[j], (dets[i].prob[j]*100) );
class = j;
} else {
strcat(labelstr, ", ");
strcat(labelstr, names[j]);
}
printf("%s: %.0f%%\n", names[j], dets[i].prob[j]*100);
}
}
if(class >= 0){
int width = im.h * .006;
/*
if(0){
width = pow(prob, 1./2.)*10+1;
alphabet = 0;
}
*/
//printf("%d %s: %.0f%%\n", i, names[class], prob*100);
int offset = class*123457 % classes;
float red = get_color(2,offset,classes);
float green = get_color(1,offset,classes);
float blue = get_color(0,offset,classes);
float rgb[3];
//width = prob*20+2;
rgb[0] = red;
rgb[1] = green;
rgb[2] = blue;
box b = dets[i].bbox;
//printf("%f %f %f %f\n", b.x, b.y, b.w, b.h);
int left = (b.x-b.w/2.)*im.w;
int right = (b.x+b.w/2.)*im.w;
int top = (b.y-b.h/2.)*im.h;
int bot = (b.y+b.h/2.)*im.h;
if(left < 0) left = 0;
if(right > im.w-1) right = im.w-1;
if(top < 0) top = 0;
if(bot > im.h-1) bot = im.h-1;
draw_box_width(im, left, top, right, bot, width, red, green, blue);
if (alphabet) {
image label = get_label(alphabet, labelstr, (im.h*.03));
draw_label(im, top + width, left, label, rgb);
free_image(label);
}
if (dets[i].mask){
image mask = float_to_image(14, 14, 1, dets[i].mask);
image resized_mask = resize_image(mask, b.w*im.w, b.h*im.h);
image tmask = threshold_image(resized_mask, .5);
embed_image(tmask, im, left, top);
free_image(mask);
free_image(resized_mask);
free_image(tmask);
}
}
}
}

Confused About Passing Color to Class (Java)

Trying to write a program in which if a user enters in a name that is "Randy" than Java would generate a random number between 0 to 255 (RGB). If the name is "Prius" than the color would be green only. From there I would pass that random number or the green color into my tank class.
import java.awt.*;
import java.util.*;
public class Program4
{
public static void main(String[ ] args)
{
Scanner kb = new Scanner(System.in);
Random rand = new Random();
System.out.print("Please enter in your name: ");
String name = kb.nextLine();
if(name.equalsIgnoreCase ("Randy"))
{
for (int i=1 ; i<= 3; i++)
{
int color2 = rand.nextInt(255);
Color myColor = new Color (color2);
Tank myTank = new Tank(myColor, 25);
}
}
else if (name.equalsIgnoreCase ("Prius"))
{
Color myColor = new Color (0,255,0);
Tank myTank = new Tank(myColor,25);
}
//create a new instance of a Tank, get its dimension
Color myColor = new Color(255, 0, 255);
Tank myTank = new Tank(myColor, 25);
int dimension = myTank.getDimension();
//create a new instance of a Landscape
Landscape myLS = new Landscape();
//tell the landscape to add the tank to itself
myLS.addTank(myTank);
//tell the tank to turn around
myTank.turn("left");
myTank.turn("left");
//ask the landscape where is its green opening (as an int)
Point greenPoint = myLS.getGreenOpening();
int greenY = (int)greenPoint.getY();
//tell the tank to keep moving as long as it is above the green opening
while(myTank.getPositionY() + dimension < greenY)
myTank.move();
//turn left
myTank.turn("left");
//hopefully, move through the green wall
for (int i=0; i<200; i++)
myTank.move();
Point orangePoint = myLS.getOrangeOpening();
int orangeY = (int)orangePoint.getY();
if (myTank.getPositionY() + dimension < orangeY)
{
myTank.turn("right");
while (myTank.getPositionY() + dimension < orangeY)
{
myTank.move();
}
myTank.turn("left");
}
else
{
myTank.turn("left");
while (myTank.getPositionY() + dimension > orangeY)
{
myTank.move();
}
myTank.turn("right");
}
for (int i=0 ; i<200 ; i++)
myTank.move();
Point targetLocation = myLS.getTargetLocation();
int targetY = (int)targetLocation.getY();
if (myTank.getPositionY() + dimension <targetY)
{
myTank.turn("right");
while (myTank.getPositionY() + dimension < targetY + 30)
{
myTank.move();
}
myTank.turn("left");
}
else
{
myTank.turn("left");
while (myTank.getPositionY() + dimension > targetY + 30)
{
myTank.move();
}
myTank.turn("right");
}
for (int i=0 ; i<500 ; i++)
myTank.move();
}
}
There is more to the program however, I just need help with the colors. The program compiles and works. The only problem is the random color and green is not being passed onto my tank class. The default tank color is purple.
Thank you for the help.
Have you tried this?
Color myColor;
Tank myTank;
if(name.equalsIgnoreCase ("Randy"))
{
for (int i=1 ; i<= 3; i++)
{
int color2 = rand.nextInt(255);
myColor = new Color (color2);
myTank = new Tank(myColor, 25);
}
}
else if (name.equalsIgnoreCase ("Prius"))
{
myColor = new Color (0,255,0);
myTank = new Tank(myColor,25);
}
else
{
myColor = new Color(255, 0, 255);
myTank = new Tank(myColor, 25);
}
int dimension = myTank.getDimension();

How does 3D picking work in JavaFX 8

Unfortunately I could not find any good tutorial for picking api.
Can anyone give me a brief tutorial about it or some useful links?
Update
world.setOnMouseClicked((event)->{
PickResult res = event.getPickResult();
System.out.println("res "+res);
//you can get a reference to the clicked node like this
if (res.getIntersectedNode() instanceof Node){
((Node)res.getIntersectedNode()).setTranslateZ(-50);
}
});
The code above only work on the first node that I click.
Does anyone know what is the problem?
It seems to work just fine without much understanding. My guess is it takes the element closest to the camera (ie. in front) in the 2D representation of where you clicked. It doesn't matter which face you click, it always gets the right node.
The code is very simple. I've made a scene with a Parent called world that has 3D elements.
package simple3dboxapp;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Parent;
import javafx.scene.PerspectiveCamera;
import javafx.scene.Scene;
import javafx.scene.SubScene;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.PickResult;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.paint.Material;
import javafx.scene.paint.PhongMaterial;
import javafx.scene.shape.Box;
import javafx.scene.text.Text;
import javafx.scene.transform.Rotate;
import javafx.scene.transform.Translate;
import javafx.stage.Stage;
public class Simple3dBoxApp extends Application {
public Rotate rx = new Rotate();
{ rx.setAxis(Rotate.X_AXIS); }
public Rotate ry = new Rotate();
{ ry.setAxis(Rotate.Y_AXIS); }
public Rotate rz = new Rotate();
{ rz.setAxis(Rotate.Z_AXIS); }
Translate t = new Translate();
private final PerspectiveCamera camera = new PerspectiveCamera(true);
{camera.getTransforms().addAll(t, rz, ry, rx);}
Label data = new Label();{data.setWrapText(true);data.setPrefHeight(200);}
public Parent createContent() {
Group root = new Group();
for(int i = 0; i<10; i++){
Box box = new Box(50, 50, 50);
Text text = new Text("Hi "+i);
ImageView iv = new ImageView("file:apple-touch-icon.png");
Image im = iv.getImage();
Material m = new PhongMaterial(Color.CYAN, im, null, null, null);
box.setMaterial(m);
box.getTransforms().add(new Translate(-250 + i * 50 , -100, -100 + i * 50));
text.getTransforms().add(new Translate(-250 + i * 50 , 0, -100 + i * 50));
iv.getTransforms().add(new Translate(-250 + i * 50 , +100, -100 + i * 50));
root.getChildren().addAll(box,text,iv);
}
camera.setNearClip(1);
camera.setFarClip(2000);
camera.setFieldOfView(100);
// Use a SubScene
SubScene subScene = new SubScene(root, 500,500);
subScene.setFill(Color.ALICEBLUE);
subScene.setCamera(camera);
Group group = new Group();
group.getChildren().add(subScene);
return group;
}
#Override
public void start(Stage stage) {
VBox vbox = new VBox();
Parent world = createContent();
world.setFocusTraversable(true);
vbox.getChildren().addAll(world,data);
Scene scene = new Scene(vbox);
stage.setScene(scene);
stage.show();
world.setOnKeyPressed((evt)->{
switch (evt.getCode()){
case UP:
rx.setAngle(rx.getAngle()+5);
break;
case DOWN:
rx.setAngle(rx.getAngle()-5);
break;
case RIGHT:
t.setX(t.getX()+10);
//camera.setTranslateX(camera.getTranslateX()+10);
break;
case LEFT:
t.setX(t.getX()-10);
//camera.setTranslateX(camera.getTranslateX()-10);
break;
case Z:
double zoom = evt.isShortcutDown()?-10:+10;
t.setZ(t.getZ()+zoom);
//camera.setTranslateZ(camera.getTranslateZ()+zoom);
break;
}
});
world.setOnMouseClicked((event)->{
PickResult res = event.getPickResult();
data.setText("res "+res);
if (res.getIntersectedNode() instanceof Box){
((Box)res.getIntersectedNode()).setMaterial(
new PhongMaterial(event.isShiftDown() ? Color.BLACK : Color.RED));
}
});
}
public static void main(String[] args) {launch(args);}
}
And this is the result from clicking a Box
res PickResult [node = Box#1dc02a4, point = Point3D [x = 12.361420184603276, y = 15.984395060669844, z = -5.0], distance = 1866.0254037844388, texCoord = Point2D [x = 0.6236142018460328, y = 0.8196879012133969]
PickResult javadoc

Processing.js: Won't track mouseMoved()?

I'm having an issue with tracking the movement of a mouse in a Processing sketch when its ported to Javascript. As far as I can tell, the program runs fine except that it wont activate mouseMoved, either as an event or as a logical operation. I also tried pMousex != mouseX and that also didn't work. Any help?
color[] palette = new color[5];
color c1;
color c2;
color c3;
color c4;
color c5;
color bgColor;
int swarmSize;
int xVariance;
int yVariance;
int maxSize;
int maxOpacity;
int maxStroke;
//Non-definables for swarm gen
int sideMod;
int sSize;
int opacity;
int stroke;
void setup() {
size(600, 400);
c1= #BF2633;
c2= #A6242F;
c3= #D9CEAD;
c4= #C0B18F;
c5= #011C26;
bgColor = color(23, 76, 79);
palette[0] = c1;
palette[1] = c2;
palette[2] = c3;
palette[3] = c4;
palette[4] = c5;
swarmSize = 1;
xVariance = 60;
yVariance = 60;
maxSize = 30;
maxOpacity = 255;
maxStroke = 4;
}
void draw() { //tried tracking pMouse != mouse here, no dice
}
void drawSwarm() {
for (int i = 0; i < swarmSize; i++)
{
if (random(1, 10) < 5) {
sideMod = -1;
}
else {
sideMod = 1;
}
stroke = int(random(1, maxStroke));
sSize = int(random(1, maxSize));
opacity = int(random(0, maxOpacity));
strokeWeight(stroke);
stroke(palette[int(random(1, 5))], opacity);
fill(palette[int(random(1, 5))], opacity);
// strokeWeight(int(random(1, 7)));
ellipse(mouseX + int(random(1, xVariance)) * sideMod, mouseY+ int(random(1, yVariance)), sSize, sSize);
}
}
void mouseMoved() { //Doesn't work in processing.js
drawSwarm();
}
void keyPressed() {
background(bgColor);
}
The following code works just fine (see http://jsfiddle.net/qPpRQ/)
int x,y;
void draw() {
point(x,y);
}
void mouseMoved() {
x = mouseX;
y = mouseY;
redraw();
}
usually, draw instructions in a mouse handler don't work all that well, you generally want to set up your state based on the mouse position, and then call redraw(), with the code that actually draws things to the screen being called from draw, not from your event handler.

Java - I think my boolean is defaulting to true for some reason

I'm having an issue with my hangman program. When I run it, the label holding the int variable "lives" is supposed to update when you guess a wrong letter. But for some reason it isn't. I've placed this in my code as a test mechanism, and it isn't appearing even here.
if (used[letter] = false) {
System.out.println("test");
However, when I place it here.. It DOES work..
if (finished == false) {
boolean found = false;
boolean www = false;
System.out.println("test");
if (used[letter] = false) {
It almost leads me to believe that used[letter] is true by default, when it really shouldn't be. The variable is declared at the very top. Any thoughts?
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.util.ArrayList;
public class Hangman implements ActionListener {
JFrame frame;
JPanel stats = new JPanel();
JLabel currentWordLA = new JLabel("Current word:");
JLabel triedLettersLA = new JLabel("Tried letters:");
JLabel triesLeftLA = new JLabel("Tries remaining:");
private String[] wordList = {"computer","java","activity","alaska","appearance","article",
"automobile","basket","birthday","canada","central","character","chicken","chosen",
"cutting","daily","darkness","diagram","disappear","driving","effort","establish","exact",
"establishment","fifteen","football","foreign","frequently","frighten","function","gradually",
"hurried","identity","importance","impossible","invented","italian","journey","lincoln",
"london","massage","minerals","outer","paint","particles","personal","physical","progress",
"quarter","recognise","replace","rhythm","situation","slightly","steady","stepped",
"strike","successful","sudden","terrible","traffic","unusual","volume","yesterday" };
public String mysteryWord;
public int lives;
private boolean finished = false;
private boolean won = false;
private Button a[];
public boolean used[] = new boolean[26];
public static void main (String[] args) {
Hangman gui = new Hangman();
gui.go();
}
class myDrawPanel extends JPanel {
public void paintComponent(Graphics g) {
setBackground(Color.white);
g.setColor(Color.gray);
g.fillRect(50, 200, 150, 20);
g.fillRect(90,20,10,200);
g.fillRect(90,20,60,10);
g.setColor(Color.black);
g.fillRect(145,20,5,25);
g.setColor(Color.green);
if (lives < 6 )
g.drawOval(132,45,30,30);
if (lives < 5 )
g.drawLine(147,75,147,100);
if (lives < 4 )
g.drawLine(147,100,167,133);
if (lives < 3 )
g.drawLine(147,100,127,133);
if (lives < 2 )
g.drawLine(147,75,167,85);
if (lives < 1 )
g.drawLine(147,75,127,85);
StringBuffer guessed = new StringBuffer();
for (int cl = 0; cl < mysteryWord.length(); cl++) {
if (used[(int)mysteryWord.charAt(cl)-'a'])
guessed.append(mysteryWord.charAt(cl));
else
guessed.append("*");
}
currentWordLA.setText("Current word: " + guessed.toString());
if (lives < 1) {
g.setColor(Color.white);
g.fillRect(70, 200, 200, 30);
g.setColor(Color.black);
g.drawString(mysteryWord.toString(),75,230);
Font fff = new Font("Helvetica",Font.BOLD,36);
g.setFont(fff);
g.setColor(Color.red);
g.drawString("You lose!",200,100);
//finished = true;
}
if (won) {
Font fff = new Font("Helvetica",Font.BOLD,36);
g.setFont(fff);
// Color red=new Color.red
g.setColor(Color.red);
g.drawString("You Win!",200,100);
//finished = true;
}
}
}
public void go() {
///////////////////////DESIGN BEGIN//////////////////////////////////////////////
frame = new JFrame("Hangman");
JPanel topPanel = new JPanel();
myDrawPanel noosePanel = new myDrawPanel();
JPanel bottomPanel = new JPanel();
JPanel scorePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout( new GridLayout( 2, 0) );
bottomPanel.setLayout( new GridLayout( 0, 2) );
scorePanel.setSize(20,100);
noosePanel.setBorder(BorderFactory.createTitledBorder("Your progress."));
topPanel.setBorder(BorderFactory.createTitledBorder("Your arsenal."));
scorePanel.setBorder(BorderFactory.createTitledBorder("Your score."));
frame.add(topPanel);
frame.add(bottomPanel);
bottomPanel.add(scorePanel);
bottomPanel.add(noosePanel);
//Just the stats panel.
JButton restart = new JButton("Reset");
currentWordLA.setFont(new Font("Verdana", Font.PLAIN, 10));
currentWordLA.setForeground(Color.black);
triedLettersLA.setFont(new Font("Verdana", Font.PLAIN, 10));
triedLettersLA.setForeground(Color.black);
triesLeftLA.setFont(new Font("Verdana", Font.PLAIN, 10));
triesLeftLA.setForeground(Color.black);
restart.setFont(new Font("Verdana", Font.PLAIN, 16));
restart.setForeground(Color.red);
stats.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(20,0,0,0);
c.anchor = GridBagConstraints.LINE_START;
stats.add(currentWordLA, c);
c.gridx = 0;
c.gridy = 1;
c.anchor = GridBagConstraints.LINE_START;
stats.add(triedLettersLA, c);
c.gridx = 0;
c.gridy = 2;
c.anchor = GridBagConstraints.LINE_START;
stats.add(triesLeftLA, c);
c.gridx = 0;
c.gridy = 3;
c.anchor = GridBagConstraints.LINE_START;
stats.add(restart, c);
scorePanel.add(stats);
///////////////////////DESIGN END//////////////////////////////////////////////
///////////////////////ALPHABET BEGIN//////////////////////////////////////////
int i;
StringBuffer buffer;
a = new Button[26];
topPanel.setLayout( new GridLayout( 4,0, 10, 10) );
for (i = 0; i <26; i++) {
buffer = new StringBuffer();
buffer.append((char)(i+'a'));
a[i] = new Button(buffer.toString());
a[i].setSize(100,100);
a[i].addActionListener( this );
topPanel.add(a[i]);
}
///////////////////////ALPHABET END//////////////////////////////////////////
//Just shows the entire window.
frame.setSize(500, 500);
frame.setResizable(false);
frame.setVisible(true);
//////////////////////GAMEPLAY BEGIN////////////////////////////////////////
lives = 6;
triesLeftLA.setText("Tries remaining: " + lives);
mysteryWord = wordGen();
}
//Returns a random word from the wordList bank.
private String wordGen() {
return wordList[0 + (int)(Math.random() * ((63 - 0) + 1)) ]; //Make sure to set these to nonprinted chars eventually
}
public void consultWord(int letter) {
if (finished == false) {
boolean found = false;
boolean www = false;
if (used[letter] = false) {
System.out.println("test");
for (int cl = 0 ; cl < mysteryWord.length(); cl++) {
if (mysteryWord.charAt(cl)==((char)(letter + 'a'))) {
found = true;
}
}
if (found == false) {
lives = lives - 1;
triesLeftLA.setText ("Tries remaining: " + lives);
}
}
used[letter] = true;
for (int cl = 0; cl < mysteryWord.length(); cl++) {
if (!used[(int)(mysteryWord.charAt(cl)) - 'a']){
www = true;
}
}
if (www == false) {
won = true;
}
frame.repaint();
}
}
public void actionPerformed( ActionEvent e) {
int i;
for (i = 0; i < 26; i++) {
if (e.getSource() == a[i]) {
consultWord(i); }
}
}
}
Make that:
if (used[letter] == false) {
System.out.println("test");
if (used[letter] = false) {
You just set used[letter] to false. Try ==
Of course, to avoid this typo you shouldn't be using == but rather ...
if (!used[letter]) {