Jump to content
xisto Community

beeseven

Members
  • Content Count

    628
  • Joined

  • Last visited

Posts posted by beeseven


  1. Table of Contents

    I. Introduction

    II. Before You Begin

    III. Necessities in a Java Program

    IV. Creating a Canvas

    V. Shapes

    ????[/TAB]A. Line

    ????B. Rectangle

    ????C. Oval

    ????D. Polygon

    VI. Other Things

    ????A. Changing the Color

    ????B. Strings

    ????????1. Changing the Font

    ????????2. Drawing a String

    [TAB]C. Images

    VII. Conclusion

     

    I. Introduction

    Welcome to my second tutorial here at Xisto. I'm going on vacation for a week so I thought I'd leave you all with some of the things that I picked up in the class I took ealier this summer. If anyone wants to see some things that I've done, too bad. If you want to see one thing that I've done, that's okay, because only one thing I've done is anywhere near showable. My final project was Mario, and you can download it at tjhsst.edu/~tsmilack/java/mario. The filenames work like dates (MMDDYY), so 080505 is newer than 080405. I also plan on working on this more, so watch for updates. Anyway, on to the tutorial.

     

    II. Before You Begin

    Before you start, you'll need the Java Software Developer's Kit and a compiler. The SDK you can get from the Java website (java.sun.com). They also have an installation guide located at java.sun.com/developer/onlineTraining/new2java/programming/learn/. As for a compiler, it depends on your computer. If your computer is just okay, or it doesn't really like Java, use pcGRASP (http://www.eng.auburn.edu/grasp/archive.html). If your computer is pretty good jGRASP (spider.eng.auburn.edu/user-cgi/grasp/grasp.pl?;dl=download_jgrasp.html) might be better, but it all comes down to preference.

     

    III. Necessities in a Java Program

    Okay, now that you've installed the SDK and your compiler, it's time to learn the basic things that you must have in a Java program. In this tutorial I'll be working with JFrames as opposed to applets, so if you're familiar with Java and JFrames you might be able to skip this part (and maybe the next). Anyway, on to the code.

     

    First of all, you'll need to have a .java file. In this file you will put all your code. The thing that you put your code in inside the .java file is called a class. The class should have the same name as the .java file (eg Hello.java's class would be Hello). To define a class, generally you say "public class ClassName". You don't always say public, but for now we will. By convention the first letter of the class name is capitalized and the first letters of any subsequent words in the name are also capital. Everything in a class is enclosed in curly braces ( { and } ). We'll call our file "Grapics1.java," so right now we have:

     

    Graphics1.java:

    public class Graphics1{}

    Since we're going to be putting this in a JFrame it has to be a subclass of a JPanel, so we then change it to this:

     

    Graphics1.java:

    public class Graphics1 extends JPanel{}

    However, the compiler won't know what a JPanel is, so we have to "import" some things. This just makes them available to use (it is the same as "include" in other languages). One of the best things about Java is that there are so many things to use that people have already made.

     

    Graphics1.java:

    import javax.swing.*; //JFrame, JPanelimport java.awt.*; //Graphicspublic class Graphics1 extends JPanel{}

    Since this isn't going to be an applet (we would have said "extends JApplet" in that case), we need to have a method called main (methods are called functions in some other languages). Main always must have the same header, and method bodies must also be inside curly braces.

     

    Graphics1.java:

    import javax.swing.*; //JFrame, JPanelimport java.awt.*; //Graphicspublic class Graphics1 extends JPanel{     public static void main(String[] args)     {          }}

    IV. Creating a Canvas

    To create a JFrame, you must create a new JFrame object. This will automatically make a window pop up and be all windowy. There are several things to do to create this, and most of them shouldn't be changed. Here is the code to create a new JFrame and add our Graphics1 panel to it:

     

    Graphics1.java:

    import javax.swing.*; //JFrame, JPanelimport java.awt.*; //Graphicspublic class Graphics1 extends JPanel{     public static void main(String[] args)     {          JFrame f = new JFrame("This is the title that appears in the upper left");  //Single line comments are made with two slashes          f.setSize(500,500); //Width in pixels, height in pixels          f.setLocation(100,100); //x, y from 0,0 (0,0 is top left corner of screen)          f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //This should not be changed or your program will not terminate properly. JFrame.EXIT_ON_CLOSE is an integer variable, so if you want to type less, it's actually 3          f.setContentPane(new Graphics1()); //adds our panel          f.setVisible(true); //makes the window visible     }}

    Now this won't really do anything because all we've done is created a panel. Therefore, we have to define the method paintComponent in order to make out picture pretty. Now Graphics1 will look like this:

     

    Graphics1.java:

    import javax.swing.*; //JFrame, JPanelimport java.awt.*; //Graphicspublic class Graphics1 extends JPanel{     public static void main(String[] args)     {          JFrame f = new JFrame("This is the title that appears in the upper left");  //Single line comments are made with two slashes          f.setSize(500,500); //Width in pixels, height in pixels          f.setLocation(100,100); //x, y from 0,0 (0,0 is top left corner of screen)          f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //This should not be changed or your program will not terminate properly. JFrame.EXIT_ON_CLOSE is an integer variable, so if you want to type less, it's actually 3          f.setContentPane(new Graphics1()); //adds our panel          f.setVisible(true); //makes the window visible     }     public void paintComponent(Graphics g)     {          super.paintComponent(g); //This pretty much just makes the background grey     }}

    Now we have our canvas. All the painting will go inside the method paintComponent.

     

    V. Shapes

    Shapes need to have a pair of coordinates specified. The coordinate system is a little weird, in that (0,0) is at the top left of the window. X increases to the right (as usual), but Y increases as you go down. The reason for this is that most people resize things from the bottom right corner, so it makes sense to have the origin at a fixed point. On to the shapes.

     

    A. Line

    Lines are very simple. They take four arguments, and they are x1, y1, x2, and y2. You call the method by saying (graphics object).drawLine(...). In this case our graphics object is called g, so we add this to paintComponent:

    public void paintComponent(Graphics g){     super.paintComponent(g);     g.drawLine(0,0,100,100);}

    This draws a line from (0,0) to (100,100).

     

    B. Rectangle

    Rectangles are similar to lines, but instead of x2 and y2, the third and fourth arguments and width and height:

    public void paintComponent(Graphics g){     super.paintComponent(g);     g.drawLine(0,0,100,100);     g.drawRect(0,0,100,100);}

    Now we have our original line, plus a square that encompasses the line. With rectangles and other shapes besides lines, you can also do a fill. You just change "draw" to "fill":
    public void paintComponent(Graphics g){     super.paintComponent(g);     g.drawLine(0,0,100,100);     g.fillRect(0,0,100,100);}

    This makes a filled square. I won't mention fills again because it's all the same. The default color for all lines and shapes and things is black, but I'll say how to change it later.

     

    C. Oval

    Ovals are very much like rectangles, but, well, ovals. The arguments are the same: x, y, w, h. The top left corner of the oval is the same as the top left corner of the rectangle that it is circumscribed in:

    public void paintComponent(Graphics g){     super.paintComponent(g);     g.drawLine(0,0,100,100);     g.drawRect(0,0,100,100);     g.drawOval(0,0,100,100);}

    This makes a circle inside the rectangle we drew previously. There is no specific "drawCircle" method, but you can just make the width and height the same. To make a circle centered at x,y with radius r, say this:
    g.drawOval(x + r, y + r, 2 * r, 2 * r);

    D. Polygon

    Polygons are a bit harder. They require arrays of points but can make pretty much any shape. The arguments are defined as "int[] xPoints, int[] yPoints, int nPoints." That means "an array of integers xPoints, an array of integers yPoints, and the number of points nPoints." Here's how it works:

    public void paintComponent(Graphics g){     super.paintComponent(g);     g.drawLine(0,0,100,100);     g.drawRect(0,0,100,100);     g.drawOval(0,0,100,100);     int[] xPoints = { 0, 100, 0 };     int[] yPoints = { 0, 0, 100 };     int nPoints = xPoints.length; //returns the number of items in the array     g.drawPolygon(xPoints, yPoints, nPoints);}

    This new piece of code draws a triangle with points at (0,0), (100,0), and (0,100).

     

    VI. Other Things

    You can do more than just black shapes. Here I'll show you a few other things.

     

    A. Changing the Color

    Changing the color is relatively simple. The method takes one argument, but you must pass it a color object:

    g.setColor(new Color(255,0,0));g.setColor(Color.red);

    Both of these will set the color to red, but a Color.(color) doesn't exist for every color, so knowledge of the RGB system is helpful (if you don't know it there's probably something on Google, just search "color chooser"). Now we'll set the draw color to blue before our next section:
    public void paintComponent(Graphics g){     super.paintComponent(g);     g.drawLine(0,0,100,100);     g.drawRect(0,0,100,100);     g.drawOval(0,0,100,100);     int[] xPoints = { 0, 100, 0 };     int[] yPoints = { 0, 0, 100 };     int nPoints = xPoints.length; //returns the number of items in the array     g.drawPolygon(xPoints, yPoints, nPoints);     g.setColor(new Color(0,0,255));}
    B. Strings

    You should all know what strings are. They're just strings of characters, like "hello" or "kjekt43543 34hkdsg-43 gdf4(*%#." Sometimes it's useful to put a string on a image, and that's what this section's about.

     

    1. Changing the Font

    Like a color, setFont requires one variable but you must have a new object for it. To make a font object, you must give the name, style, and size. Universally supported names are "Serif," "SansSerif," and "Monospaced," but you can also use names like "Arial" and "Tahoma." Style is bold (Font.BOLD), italic (Font.ITALIC), or bold italic (Font.BOLD | Font.ITALIC). Size is a numeric representation of the size. Here is an example:

    public void paintComponent(Graphics g){     super.paintComponent(g);     g.drawLine(0,0,100,100);     g.drawRect(0,0,100,100);     g.drawOval(0,0,100,100);     int[] xPoints = { 0, 100, 0 };     int[] yPoints = { 0, 0, 100 };     int nPoints = xPoints.length; //returns the number of items in the array     g.drawPolygon(xPoints, yPoints, nPoints);     g.setColor(new Color(0,0,255));     g.setFont(new Font("Serif", Font.BOLD, 14));}

    This makes a 14pt bold serif font.

     

    2. Drawing a String

    The method drawString takes three arguments: the string to be drawn, the x coordinate and the y coordinate. For strings, the x and y values are at the bottom left of the string as opposed to top left. Here is how to use drawString:

    public void paintComponent(Graphics g){     super.paintComponent(g);     g.drawLine(0,0,100,100);     g.drawRect(0,0,100,100);     g.drawOval(0,0,100,100);     int[] xPoints = { 0, 100, 0 };     int[] yPoints = { 0, 0, 100 };     int nPoints = xPoints.length; //returns the number of items in the array     g.drawPolygon(xPoints, yPoints, nPoints);     g.setColor(new Color(0,0,255));     g.setFont(new Font("Serif", Font.BOLD, 14));     g.drawString("Hello World!",100,100);}

    This draws the string "Hello World!" just to the right of our square.

     

    C. Images

    Images are a bit complicated. You have to import the ImageIcon class (which is in javax.swing.* so we're okay here). You create an image by making a new ImageIcon and giving it a string for the location:

    ImageIcon hi = new ImageIcon("hi.gif");

    Then you draw the image with the method drawImage (you also need to use getImage on the icon). Here it is in paintComponent:
    public void paintComponent(Graphics g){     super.paintComponent(g);     g.drawLine(0,0,100,100);     g.drawRect(0,0,100,100);     g.drawOval(0,0,100,100);     int[] xPoints = { 0, 100, 0 };     int[] yPoints = { 0, 0, 100 };     int nPoints = xPoints.length; //returns the number of items in the array     g.drawPolygon(xPoints, yPoints, nPoints);     g.setColor(new Color(0,0,255));     g.setFont(new Font("Serif", Font.BOLD, 14));     g.drawString("Hello World!",100,100);     ImageIcon hi = new ImageIcon("hi.gif");     g.drawImage(hi.getImage(),0,100,null); //image, x, y, ImageObserver (ignore that, just put a 'null' there)}

    This draws hi.gif just below our square.

     

    VII. Conclusion

    Se here's our finished program (comments removed):

    import javax.swing.*;import java.awt.*;public class Graphics1 extends JPanel{     public static void main(String[] args)     {          JFrame f = new JFrame("This is the title that appears in the upper left");            f.setSize(500,500);          f.setLocation(100,100);          f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);          f.setContentPane(new Graphics1());          f.setVisible(true);     }     public void paintComponent(Graphics g)     {          super.paintComponent(g);          g.drawLine(0,0,100,100);          g.drawRect(0,0,100,100);          g.drawOval(0,0,100,100);          int[] xPoints = { 0, 100, 0 };          int[] yPoints = { 0, 0, 100 };          int nPoints = xPoints.length;          g.drawPolygon(xPoints, yPoints, nPoints);          g.setColor(new Color(0,0,255));          g.setFont(new Font("Serif", Font.BOLD, 14));          g.drawString("Hello World!",100,100);          ImageIcon hi = new ImageIcon("hi.gif");          g.drawImage(hi.getImage(),0,100,null);     }}
    Now that you're done just hit the compile button and wait for it to finish, then run it (I have compiled this code and it runs as expected).

     

    Well, I guess this tutorial is over now. I hope you enjoyed it. Perhaps I'll do another one later on double buffering and animation, but that is for another day.

     

    See you when I get back from my vacation, Xisto! (or maybe earlier if this doesn't give me enough credits to last >_>)


  2. I'll agree that Aqua Teen Hunger Force is a really funny show, but I'd have to say that Family Guy is more consistently funny. ATHF has its moments, but most episodes of FG have me laughing all the way through. Futurama is usually really good, too, but didn't they stop making new ones a long time ago? Anyway, as for my favorite episode, I'd have to say the first one where they encounter the Plutonians (the tall, green and fat, orange aliens).


  3. This topic reminded me of Google's April Fools Day joke. It was a really obvious poke as GMail. One of the things in the FAQ was this:

    7. How can I get my hands on a Google Gulp?
    This "limited release" beta product is available to anyone who turns in a used Google Gulp bottle cap at any local retailer. If you don't have any Gulp caps, ask a friend to give you one.

    8. What if none of my friends have a Gulp cap to give me? Can't you just give Google Gulp to anyone who wants it?

    Well, we're thinking about it, but, um, you have to understand that there are many considerations which go into deciding how to distribute --

    9. I mean, isn't this whole invite-only thing kind of bogus?

    Dude, it's like you've never even heard of viral marketing.

    ...

    11. When will you take Google Gulp out of beta?

    Man, if you pressure us, you just drive us away. We'll commit when we're ready, okay? Besides, what's so great about taking things out of beta? It ruins all the romance, the challenge, the possibilities, the right to explore. Carpe diem, ya know? Maybe we're jaded, but we've seen all these other companies leap headlong into 1.0, thinking their product is exactly what they've been dreaming of all their lives, that everything is perfect and hunky-dory and the next thing you know some vanilla copycat release from Redmond is kicking their butt, the Board is holding emergency meetings and the CEO is on CNBC blathering sweatily about "a new direction" and "getting back to basics." No thanks, man. We like our freedom.



  4. I was going to try to put these in some order, but I can't. So here's just a big jumble of artists I really like:The Beatles, Queen, Led Zeppelin, Pink Floyd, The Doors, The Who, The Greatful Dead, The Rolling Stones, Fleetwood Mac, The Moody Blues, Iron Butterfly, Train, The Presidents of the United States of America, Eric Hutchinson (he might be local), and probably a lot more I'm forgetting.


  5. Here's a PHP version of the above script:

    $spam = false;spamArray = array("poker", "viagra", "texas", "xanax", "holdem");for($x = 0; $x < count($spamArray); $x++){     if (substr_count($_POST['message'],spamArray[$x]) > 0 )     {          $spam = true;     }}if(!$spam)     mail(...


  6. HTML isn't a programming language, and JavaScript barely is. I wouldn't go for HTML/JS/PHP/ASP unless you're interested in web design, and few companies use that much Java. C++ is the most widely used I think, but it depends on what field you're in.Some things about each:JS/PHP/ASP are very linear languages. Like, they go from the top of the code to the bottom and that's pretty much it. However, if you're into webdesign, these are pretty importantLanguages like Java, C, and C++ have more possibilities because you can have things like keylisteners and timers.Java isn't used much because it's generally pretty slow, but it can be good for games. I think I also remember reading that Google was interested in hiring people who were really experienced with Java.C and C++ are probably used most. They're relatively fast and can do a lot of things. Probably most of the programs on your computer are in one of the two.In the end, it just depends what you want to do.


  7. I don't think it would be possible. You'd have to figure out the path to the desktop. On Windows this is C:\Documents and Settings\%USERNAME%\Desktop, I don't remember Linux's, and something else on Mac. You can get the OS with PHP's $_SERVER['HTTP_USER_AGENT'], but I don't think it's possible to write a file to the desktop.You could always just tell people to drag their link to the desktop.

    Notice from KuBi:
    Edit as per requested.

  8. This will write to a text file, but you probably need to change permissions to do it:

    System.setOut(new PrintStream(new FileOutputStream("signs.txt"))); //sets output destinationSystem.out.println(signature); //writes to file
    You'll also have to import java.io.*.

    As for the permissions, you could just create the file beforehand and set it to 0766 (0777? Anybody know if it matters for this?), or do something needlessly complicated that I'm not sure would work anyway.

  9. You're being kind of vague, so I'm not exactly sure what you mean, but here are some neat things you can do with a JButton:

    Let's assume we have a JButton called myButton.

    This changes the font:

    String name = "Serif"; //"Serif", "SansSerif", "Monospaced", or a font nameint style = Font.ITALIC //Font.ITALIC, Font.BOLD, or Font.BOLD | Font.ITALICint size = 14 //any number sizemyButton.setFont(new Font(name, style, size));
    Change colors:
    myButton.setForeground(new Color(255,0,0)); //changes font color (in this case makes it red)myButton.setBackground(new Color(0,0,255)); //changes background color (in this case blue)
    Disable, reenable:
    myButton.setEnabled(false);myButton.setEnabled(true);
    Add an image to display if it's enabled, or disabled:
    ImageIcon ico = new ImageIcon("picture.gif"); //any imagemyButton.setIcon(ico);ImageIcon ico2 = new ImageIcon("otherpicture.gif");myButton.setDisabledIcon(ico2);
    Make the button plain text (but still a button):
    button.setBorderPainted(false);DDT TJ 08: button.setFocusPainted(false);


  10. I think it's similar in most of America, at least I have it like this:Grades:A = Exceptional (highest)B+ = Really goodB = Above averageC+ = A little above averageC = AverageD+ = Below averageD = Not goodF = Fail (lowest actual grade)Other:I - Incomplete (no grade, but doesn't count against you)0 (zero) - No grade (factored in instead of a score -usually if you've cheated)Some places include A+, some don't have +'s, and some include -'s which are like the +'s but a little lower than the letter. Most places also map the letters to a 0-100% scale. Mine is 94-100 = A90-93 = B+84-89 = B80-83 = C+74-79 = C70-73 = D+64-69 = D<64 = Fbut I hear most places are by 10's (90-100 = A, 80-89 = B, 70-79 = C, etc).


  11. Anyone ever played this game? It's one of the most original ideas I've ever seen, and it was implemented beautifully.Katamari Damacy is a PS2 game in which you control the Prince of All Cosmos. The story is basically that your dad, the King of All Cosmos, got high and accidentally broke every star in the sky. Since your parents aren't all that great, they blame you and make you rebuild all the stars. To do this, you get a katamari (basically a little sticky ball) and you roll around various areas picking up literally anything that's smaller than you until the time runs out. As the game progresses, your goals sizes get bigger and the time to reach them gets shorter.Now when I say you can pick up anything, that's pretty much anything. You start really small and can only pick up things like thumbtacks or pieces of candy, but as you get bigger you can pick up many more things, such as people, trees, buildings, giant mock superheroes, clouds, islands, tornadoes and even rainbows!If you do well enough in certain levels, you unlock an eternal mode which lets you roll around and pick up things until you run out of things to pick up (and I have run out).I guess it might not seem like the greatest idea written down, but the enormous number of things that you can pick up and the depth that was put into the levels truly makes this game a masterpiece.I recommend that everyone play this game at least once. If you don't happen to have a PS2, they are also porting this game to the Nintendo DS, and if Nintendo's getting it, other consoles probably will aswell.Overall, Katamari Damacy is simply magnificent, so if you have a PS2 you should definitely pick it up (especially because it's dirt cheap! Most stores sell it for around $20 US).


  12. Most of the posts on the Java board seem to be about JavaScript or JSP. This was kind of surprising to me, since Java is usually hailed as the fastest growing programming language. Not to mention the fact that lots of people now turn off JS and few know about JSP.Do you think Java newest and best thing in programming? Maybe C++ since it's a bit faster and used more, but I think Java probably has the fastest growing support.


  13. I'm making minesweeper so I have this big matrix of JButtons. I want to have it so that when you click the button is disabled and the ImageIcon is changed to whatever it should be, but when you disable a button it becomes grayscale so the pictures are hard to see/don't look like what they're supposed to.Is there a way to disable the button and keep the images colorful, or does anyone have any other ideas?(I've thought about just removing the ActionListener but that might get confusing to have blank buttons that do nothing. Maybe only disabling it if there's not a number or mine, but that might require a lot more code)


  14. I've been doing a lot of java stuff recently and some is pretty neat, so I'd like to put it on the internet. I'm using XHTML 1.1 for all my pages, though, and according to W3Schools <applet> doesn't exist anymore and to use object.

     

    It's not working, though. There are a bunch of attributes (http://www.w3schools.com/tags/tag_object.asp) and I have no idea which things I need to use. Which do I put for an applet?


  15. Right now I have this:

    DecimalFormat form = new DecimalFormat("0.00");form.toPattern();form.format(tot);
    The Java API said that 0 would be a digit that you didn't want ignored (ie an extra zero), but it's only showing the first 0 after the decimal. This is a monetary value so I have to have exactly 2. Also sometimes it weirds out and goes from 0.05 to 0.0600...002 or from 0.09 to 0.0999..., so I need it to round to those 2 decimals, too.

    As for the DecimalFormat I've tried "#.##", "0.#0", "#.#0", and "0.##" but those didn't work, either.
×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.