sirlink99 56 Practically a Master Poster

Hello,

I am working on a simple timer toolbar app in swift for macOS and I am experiencing a visual bug.

Basically, I should be able to add any number of timers to the main screen and they should stack on top of each other. Once the space is filled up in the window, a scroll bar appears allowing you to scroll through all the timers. My issue is that when I add the timers, they do not show all the time. I have a hunch it is either some refresh issue or some spacing issue.

The blank screen looks like this:
Screen_Shot_2017-07-18_at_10_45_21.png

The bug is visible here. Out of the 3 timers added only 2 show up with the empty space between the 2 timers being the location where the third timer should be: Screen_Shot_2017-07-18_at_10_49_06.png

The main scene is arranged like this: Screen_Shot_2017-07-18_at_10_52_12.png

Where the mainScreenView and the dynamicScrollView and the View are all set to 250px wide. The timer view itself is a separate view, but that is also 250 px wide.

The code that adds the timers to the window is as follows:

func updateList(){
        let documentView = NSView(frame: CGRect(x:0,y:0,width:250,height:max(360, AppDelegate.timekeeperArray.count*60)))
        documentView.autoresizesSubviews = true
        documentView.canDrawConcurrently = true

        var counter = 0
        for var i in AppDelegate.timekeeperArray{
            //let offset = CGFloat(counter * 50)
            //let button = NSButton(frame: CGRect(x:0, y:offset, width:150, height:50 ))
            dsvScrollView.contentView.addSubview(i.getPreview(index: counter))
            counter += 1;
        }
        dsvScrollView.documentView = documentView
        for var i in (dsvScrollView.documentView?.subviews)!{
            i.needsDisplay = true
            i.superview?.needsDisplay = true
            for var j ...
rproffitt commented: Interesting issue but I have no way to duplicate. +12

sirlink99 56

ok. First there are several thing I would like to point out. When you are summing you set the number at I equal to the sum at I. What you want to do is create another variable outside of the loop, and add the number at the I value to the sum variable. Second you will want to take a look at 2D arrays also to traverse the 2D array you will need a nested for loop (a for loop inside of the for loop) and make sure you don't use the same counter. You will also want to print out the sum after your outer for loop has completed.

I hope this helps

sirlink99 56

You will want to take a look at JDBC. As for the updating the database you could update it in intervals, or whenever the user types, moves the mouse, etc.as for the extending the solution I can think of is to have a panel, and then have an arrayList/Vector containing components, and then when you press a button you add the components to a corresponding arraylist/vector, and then add it to the panel.

sirlink99 56

If you want to use graphics, then just use a Rectangle over the area that you want to be clickable. Then when you press the mouse button check the coordinates of the Mouse and it the Rectangle contains them. If they do then run the action. If the Image is in a JScrollPane this becomes more difficult.

sirlink99 56

Mine is working correctly. I wrote this sample code to demonstrate.

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class Main {

    public Main(){
        System.out.println("Test Korean: 안녕하세요\n");

        try {
            BufferedWriter out = new BufferedWriter(new FileWriter(new File ("test.txt")));

            System.out.println("Writing: English");
            out.write("English\n");
            System.out.println("Writing: 한국어");
            out.write("한국어\n");
            System.out.println("Writing: I wonder if it worked");
            out.write("I wonder if it worked");

            out.close();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        try {
            Scanner in = new Scanner (new File ("test.txt"));
            while (in.hasNext()){
                System.out.println("Read: " + in.nextLine());
            }
            in.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        new Main();

    }

}

Just make sure you have your IDE's console set to display UTF-8

somjit{} commented: this is going to help a lot of people. +3

sirlink99 56

Hello and welcome to Daniweb.

I would like to refer you to the rules and the TOS. Here we are glad to help anyone stuggling with some code, or a concept. In order to effectively help, we need to know as much information as possible. Please provide code examples, error messages and descriptions of what you have attempted. If you are strugling with a concept, then tell us what concept you are stuggling with and how you currently understand it. This will allow us to help you understand the concept. We will gladly help, but we will not give you code for homework assignments.

iamthwee commented: nods +14

sirlink99 56

Welcome to Daniweb!

I would like to refer you to the TOS which you agreed to when you signed up. Please provide more information, examples of what you have done, error messages and any other relevant information. We are a community of programmers looking to help other programmers when they are having trouble. We will not do your homework for you!

sirlink99 56

Glad I could help. Just remember that in order for a method to execute you need to call it first.

sirlink99 56

Here is the general order of how you want to create a frame containing a panel containing a button

first you want to create a JFrame, JPanel and a JButton

Then you want to make sure you set the action command of the button (if you have multiple buttons this will allow you to distinguish between them).

Then you want to add the button to the JPanel and then the Panel to the JFrame. You want to set the frame visible and the other important thing is to set the frame's setDefaultCloseOperation() to JFrame.EXIT_ON_CLOSE

If you would like a more detailed guide then take a look at this it should have all the information you need

sirlink99 56

You could do it in java, however php would probably be easier.

Here is how you can send an email using php: http://php.net/manual/en/function.mail.php

with java you would have to use the JavaMail API: http://www.oracle.com/technetwork/java/javamail/index.html

In both cases what you want to do is run through your database using the primary key as your indexing and then checing if the stock is 0 or at a low number depending on your wishes. Then probably the best way to do it is to add the low items to a string and then send the whole string in an email.

PHP has the built in ways of traversing a database, bowever with java you will want to take a look at JDBC: http://docs.oracle.com/javase/tutorial/jdbc/basics/connecting.html

Hope this helps you achieve your goal.

sirlink99 56

Correct me if I am wrong, but you are using the 2D array as your map. For example if you have a 10 by 10 2D array and your frame is 100 by 100, then each element in the array represents 10px by 10px. These pixels can either be a 1 (snake) or a 0 (background) (and possibly a 2 for the collect ball). Then what you want to do is if you have the right arrow pressed down, then you want to move the head of the snake (1) to array[x+1][y] like you showed. But you also want to keep in mind that you need to work from the back of the snake otherwise you lose reference to the rest of the body (because if you turn and the snake just moves right you get a diagonal snake). This method should work fine, although your paintComponent method will have a nested for loop which will slow your game down slightly. Then depending on the value in the array you either draw nothing, or a circle/rectangle for your snake.

As for your other question. No you don't need to change the position each time, although if you want to you can make it generate in a random location with 2 lines of code.

sirlink99 56

what you could do is restructure your player constructor to take in a Main.java reference

new Player (this, x tileWidth, y tileHeight, tileWidth, tileHeight)

and then store the reference to the Main class in the player class, however ideally you want your pprogram to have the layout of a tree

         Main class
   /                  \
High Score           Draw 
                  /        \  
                Player    Level

With level I am referring to my game with obstacles as well.
Structuring your program this way will allow for minimal extra storage( by storing references back to the parent class), and will make your code less complicated to read and debug. Structuring this way also allows for easier feature implementation in the future.

sirlink99 56

As James Cherrill said. you are making the player, but you are not painting it. Also is your map01 a grid for your snake to go on, or are you going to make levels like in my snake game?

This is the snake game I made a year or so ago, and I have recently started to remake it.

My new version has these classes
Main.java - creates the frame, and runs the game loop which repaints the Disp.java and moves the snake (calls a meethod)
Disp.java - the JPanel which holds the graphics that is added to the frame. Gets repainted from Main.java and repaints the snake
Listeners.java - Holds the key listener which has been added to the frame(Main.java). Changes variables to moves the snake
Snake.java - holds the snake (a Vector or points) which then moves according to boolean variables changed by the Listeners
Instances.java - holds variables that need to be accessed from many different classes.
HighScore.java - a system of adding high scores to a database (for future use).

I technically also use a 2d array to do my movement, but I do not have it defined in an array. Instead I just set the content pane of the frame to be 500 by 500, and then I move the snake 10 at a time (so it works out to a 50 by 50 grid) which controls the snake. Then I use rectangles to check if the snake is out of the screen (in which ...

sirlink99 56

You may want to take a look at the java.net package. If you don't know how to write a standalone program you will allso want to take a look at the javax.swing package. Search up some tutorials to help you. The oracle website has many tutorials that will help you get started.

sirlink99 56

hsa.Console? From the context I assume that this class is used for outputting things. I'm just wondering... What is the great benefit of using this class as opposed to using something that comes with the Java libraries? I suggest you to take a look here. You can access an instance of PrintStream using the static out reference variable of the System class. E.g. System.out.println("You win!!!").

I recongize the hsa console. It is a built in console in the Ready to Program IDE. It is essentially a TextArea that works like the command prompt and "simplifies" reading user input that is entered into the console.

mvmalderen commented: Oh, okay, I didn't know that. +13

sirlink99 56

I have in a couple of comments in some areas, but they are generic. you can delete them if you wish. I have already released my code on thetechgame.com. Anyways here is the main part of the code the frame portion is separate.

[CODE]
package snakeColored;

import javax.swing.;
import java.awt.event.
;
import java.awt.;
import java.util.
;

public class SnakeG extends JPanel implements KeyListener, Runnable{

private Vector<Point> snake = new Vector<Point> (5,10);
private Point target;
private Rectangle targetRect;
private Rectangle frameRect = new Rectangle (0,0,490,470);
private Vector<Color> snakeColor = new Vector<Color> (5,10);
private Color targetColor;
private Vector<Rectangle> snakeRectangle = new Vector<Rectangle> (5,10);

public void startGraphics (){

    this.addKeyListener(this);
    Thread thread = new Thread (this);

    repaint();
    grabFocus();
    snake.add (new Point (250,250));
    genTarget();
    snakeRectangle.add(new Rectangle (250,250,10,10));
    snakeColor.add(Color.black);
    runThread = true;
    thread.start();
}

private void addBall() {
    // TODO Auto-generated method stub
    if (previous.equals("right")){
    snake.add (new Point (snake.lastElement().x - 10, snake.lastElement().y));
    }
    if (previous.equals("left")){
        snake.add (new Point (snake.lastElement().x + 10, snake.lastElement().y));
    }
    if (previous.equals("up")){
        snake.add (new Point (snake.lastElement().x, snake.lastElement().y + 10));
    }
    if (previous.equals("down")){
        snake.add (new Point (snake.lastElement().x, snake.lastElement().y - 10));
    }
    snakeRectangle.add(new Rectangle ((int)snake.lastElement().x, (int) snake.lastElement().y, 10,10));
    snakeColor.add(targetColor);

}

public void paintComponent (Graphics g){
    //TODO GRAPHICS AREA
    super.paintComponent (g);

    for (Point x : snake){
        g.setColor(snakeColor.elementAt(snake.indexOf(x)));
        g.fillOval((int)x.getX(),(int)x.getY(),10, 10);

    }
    g.setColor (Color.black);
    if (runThread == false){
        System.out.println ("Lost message entered");
        g.setFont (new Font ("Arail", 30,30));
        g.drawString("You Lose!", 200, 220);
        g.setFont (new Font ("Arial", 10,10));
        g.drawString("Press N for a new Game", 210,230);
        g.setFont(new Font ("Arial", 17,17));
        g.drawString("Your Final Snake Size Was: " + snake.size(), 160, 250);
    }
    else { ...

sirlink99 56

you want to use graphics. You also want to implement MouseMotionListener, and KeyListener, which are both located in java.awt.event. I suggest you look through the API docs to find out how to make a JFrame, and how to set the layout. But the combo box and JFrame are located in javax.swing.

I cannot help you more, unless you have a specific issue. We do not do your homework/assignments here. We just help.

sirlink99 56

You can just use the code I posted. All you would need to do is change the package and the name of the class and it should work.

My jar file works. it takes me a little while to load though.

sirlink99 56

no I suggest you try to create another project, or package and try again. if that doesn't work then just use your original, or paste my current code into your original and then change the class name. You can change the name of the JAR file if you single click 2 times on the icon, or right click it and rename, or right click > properties and then change the name from there. the only way you can see the class files in the project are if you extract the jar file using winzip, or win rar or another archiver program.

sirlink99 56

did you change the Class name from the file to the new class name?

where it says

[CODE]public class Try1 {[/CODE]

replace it with

[CODE]public class NewClassNameHere {[/CODE]

you wrote in the class name when you made the class (if you are using netbeans or eclipse) or it is the name of the file (if you are using notepad, or another text editor)

if that doesn't fix it send me the code. maybe you have a small error that is correct, except misused.

sirlink99 56

All of this code will be written inside the main method before the OptionPane

sirlink99 56

you want to keep the print statement inside of the method, just move it above the return. I have modified your code a bit. I have also added in comments to help you.

[CODE]package try1;

import javax.swing.JOptionPane;

public class Try1 {

public static void main(String[] args){
    String[] messages = {"message1","message2","message3","message4", "message5"}; // stores messages
    JOptionPane.showMessageDialog(null,messages[getRandomIndex(messages.length)]); // prints out one of the messages
    System.exit(0);        
}

public static int getRandomIndex(int max){  // gets which message to print out
    int messagePrintNumber = (int)(max*Math.random()); // generates a random number in the array

    System.out.println("Message " + (messagePrintNumber + 1)); // tells you which message it is printing. the +1 is to account for the array beginning at 0

    return messagePrintNumber; // returns which message it should print out
}

}[/CODE]

I have made it so that it uses the max value of the array in the random calculation.

Note that the random message generation is separate from the print statement. This way you can return the generated number.

sirlink99 56

The messages.length returns an int. It tells you how many messages you have. If you replace the 5 here
[CODE]System.out.println("Message " + (int)(5*Math.random()));[/CODE]

with your max value passed into the method you will not have to constantly update that number, as it will always be passed in with the new number of messages.

You would need to replace 5 with 100 if you had 100 messages, or you could pass in the value like I suggested, and then you could write more or less messages.

@stultuske doesn't casting as an int round the value?

sirlink99 56 Practically a Master Poster

I am making a game where random obstacles appear. The obstacles will move towards you. I currently have this code to animate the obstacles.

[CODE]
for (int i = 0; i < obstacle.size(); i++){ // animate walls
obstacle.elementAt(i).x -= 1;
}
[/CODE]

My vector multiple instances of the Walls class

[CODE]
Walls w = new Walls ();
Vector obstacle = new Vector (5,5);
[/CODE]

and this is what the Walls class looks like

[CODE]
import java.awt.Rectangle;

class Walls {
Walls (){
randomLocation ();

}
public void randomLocation() {
    // TODO Auto-generated method stub
    x = 510;
    y = (int)Math.round (Math.random ()*300);
    makeRect ();
}
private void makeRect() {
    // TODO Auto-generated method stub
    rect = new Rectangle (x,y,10,30);
}
public int x = 510;
public int y;
public Rectangle rect;

}
[/CODE]

Eclipse gave me an error if my class that draws the objects didn't look like this

[CODE]
public class CopterG extends JPanel implements KeyListener, ActionListener{
...
...
}
[/CODE]

I am not sure what the does in the drawing class.

I am trying to communicate from the class that draws the images (also animates them) with the Walls class which stores the positions of the walls. I don't know how I could fix the issue with the animation. It underlines the .x in the first code. I have made a snake game that works kind of like this, but that didn't give me any errors. I tried comparing the two and they are extremely similar.

If you ...

sirlink99 56

you could put a boolean variable in for the condition and then set it to false when you want the delay, then start a timer that generates every 2 seconds, then you want to stop the timer set the variable to true and then call your loop again. You would probably do this by creating a method called something like getStudentInfo();

you could either pass the boolean, or make it a private variable all in the same class.

it would look like this

getStudentInfo (){
// do the stuff you want

bool = false;
timer.start;
}

and the timer would look like so

public void actionPerformed (ActionEvent e){
timer.stop;
bool = true;
getStudentInfo();
}

sirlink99 56

[CODE]JTextField disp = new JTextField (19);disp.setText ("0"); disp.setEditable (false);
disp.setFont (new Font ("Arial", 10,10));[/CODE]

[URL="http://www.javaprogrammingforums.com/java-swing-tutorials/39-how-change-jtextarea-font-font-size-color.html"]Here[/URL] is a website as well
.

sirlink99 56

make a graph calculator. use graphics and then get the user to type in a valid expression. then calculate the y points for the x values and graph it. This will let yo use graphics and arrays. You will also use Math class. It will be interesting especially if you make a vector of arrays that hold the y vales for the x and then you color code them and print them all out. Then you could compare graphs. You would also have too clear the screen once in a while. This would be a great teaching tool. You know what ... Thanks for the idea (lol (JK :P))

sirlink99 56

True. you can leave out the break; in the while loop.

mKorbel commented: starting to post answers +1 +8

sirlink99 56

It is because you set check to true.

[CODE]
boolean check = false;
for (int i = 1; i<=numplayer;i++){
while (check == false){
System.out.print(playerarray[i-1] + ", what number do you think it would be :");
Scanner num = new Scanner(System.in);
String checkifint = num.next();
try {
int guess = Integer.parseInt(checkifint);
scorearray[i-1][1]= guess;
check = true; //
}
catch(NumberFormatException nFE) {
System.out.println("Please enter a correct value!");
}
continue;
}
}
[/CODE]

you are checking if you can convert it and then you go back to the while loop and then the condition is false, so the loop only executes once.

you want to break out of the while loop and then set check to flase and then it will ask for all the player.

[CODE]
boolean check = false;
for (int i = 1; i<=numplayer;i++){
while (check == false){
System.out.print(playerarray[i-1] + ", what number do you think it would be :");
Scanner num = new Scanner(System.in);
String checkifint = num.next();
try {
int guess = Integer.parseInt(checkifint);
scorearray[i-1][1]= guess;
check = true;
}
catch(NumberFormatException nFE) {
System.out.println("Please enter a correct value!");
}
break; // break out of while
}
check = false; // set condition to false so it executes for the next players
}
[/CODE]

sirlink99 56

[QUOTE=AhmedGhazey;1598100]i tried it before it works fine , try it and tell me .

SHUTDOWN -S
TO RESTART SHUTDOWN -R
TO ABORT SHUTDOWN -A

I hope this help. :)[/QUOTE]

He is trying to [B]turn on[/B] a computer not turn off. An idea, but it is not with programming.

Just make a 555 timer circuit and cat the timing correct (by placing multiple capacitors in series or increasing the resistance) and then make it run off of a battery so that every 24 hours it sends a current. Then hook it up so that it sends the current though the power button. Then the computer will turn on every 24 hours since the time you set it up (Assuming your battery never runs out. Then again you could just make an adapter). Anyways, this circuit is not that hard to make and it would accomplish the job assuming you know how much of a current you need to send through the power switch.

A quick circuit analysis

power button cables disconnected from button, connected to 2 sides of 555 (-,+)
555 running off of battery/ outlet
every 24 hours the capacitors fill up and release a charge though the wire (that were connected to the button) and then turn on the computer. After the charge is released the capacitors begin to fill up again and the cycle continues.

If you decide to go with this idea and need help I suggest you go to the PC hardware section under Hardware & ...

jingda commented: Like your last senetence. Maybe the poster will see me at the hardware forum there. Lol +9