Sunday, September 28, 2014

How to Involve API With Android

Instructions

    1

    Open the Java Eclipse programming software and open your Android app project. Double-click the "main.xml" file in the "resource" directory for the app.

    2

    Locate the "manifest" tag in the XML file. Within this tag, add the following value:

    In this example, the API version used in the Android app is version 5.

    3

    Save the file and click "Run" to execute the code in the Android emulator. The emulator opens and displays your app in the designated version.



How to Set an SVN in Eclipse

Instructions

    1

    Open the Eclipse software and open the project with which you want to use SVN. Click the Software Updates menu item and select Find and Install.

    2

    Click Search for New Features to Install in the list of options and click "Next." Click New Update Site in the right panel. In the opened window, copy and paste "http://subclipse.tigris.org/update_1.0.x" into the URL text box and click "OK."

    3

    Click "Subclipse" in the details window. Click "Finish" to install and set up the system. This process takes several minutes to complete.



How to Pass the Checkbox Value Into Database Using JSP Servlet

Instructions

    1

    Open your JSP editor and the Web project. Open the page that you want to use to retrieve the checkbox value and insert the value into the database.

    2

    Create a variable and use the "getParameter" function to retrieve the checkbox value. The following code retrieves the value:

    string cbValue = req.getParameter("name");

    Replace "name" with the name of your checkbox on the JSP form.

    3

    Connect to the database server. The following code uses a MySQL database example to connect to a database server:

    Class.forName("org.gjt.mm.mysql.Driver");
    connection = DriverManager.getConnection (serverURL, "dbuser", "password");

    Replace the "serverURL," username and password with your database server information.

    4

    Insert the checkbox value into a database table. The following code inserts the checkbox value into the "subscription" database:

    String query = "insert into subscript values (?)";
    PreparedStatement ps = connection.prepareStatement(query);
    int rows = ps.executeUpdate();



How to Open Java Images in Android

Instructions

    1

    Open the Eclipse software on your desktop and open the Android app project to open all of the files in the editor.

    2

    Double-click the "main.xml" file in the "resource" directory. This file is where you place your XML images and layout. Add the following code to add an image to the app:

      android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1">

      android:background="@null"
    android:id="@+id/myimage"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/myimage" />

    The "myimage" ID is the image you want to use from the list of Java project images.

    3

    Open the view and display the image in your app. The following code opens the "main.xml" file and displays the image:

    setContentView(R.layout.main);



How to Use Xerces in Eclipse

Instructions

    1

    Open the Eclipse software and open the Java project you want to use to parse the XML file. Double-click the .java source code file in the left panel to open the code in the editor.

    2

    Instantiate the class and open the XML file. The class loads the XML into a handler so you can edit or display the information. The following code loads the file customer.xml into the parser, but replace this file with your own:

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    xml= db.parse("customer.xml");

    3

    Display the node list. For instance, the following code displays the employee's first and last name to the user:

    Element elements = xml.getDocumentElement();
    NodeList nodes = elements.getElementsByTagName("customer");
    System.out.println((Element)nodes.item('FirstName') + " " + (Element)nodes.item('LastName') );



How to Turn Off JSP Validation in Eclipse

Instructions

    1

    Open the Eclipse software and open your JSP project to open all of the programming files.

    2

    Click the Eclipse "Window" menu item. Click "Preferences." Click the "Web and XML" tab to view a list of options.

    3

    Remove the check mark next to the "Validate JSP Fragments" in the "JSP Files" section. Click "OK" to save the preferences.



How to Fix Lava on 317 Client

How to Fix Lava on 317 Client

Instructions

    1

    Check your code for simple errors. Make sure all of your lines of code begin with "" when necessary. Leaving out a bracket is one of the biggest causes of buggy server behavior.

    2

    Download a new 317 client. If you don't have much invested in the client you're running, it may be easier to start over with an unmodified bug-free 317 client than to try to fix the bugs in your current client.

    3

    Download a patch for your current client. There are patches available that fix the bugs commonly encountered in RuneScape clients, such as scenery not appearing where it should and lava not flowing correctly.

    4

    Install the patch according to the instructions, and re-start your server. The bugs should be fixed and the lava should work correctly.

    5

    Join a RuneScape Private Server forum. There are several available, and when new bugs come up, this is the best place to find fixes and workarounds because other people will have encountered a similar problem already.



How to Create Enum Hierarchies With Java

Instructions

    1

    Declare an enumerated type:

    public enum DaysAndMonths

    2

    Add some basic categories to the enum type. In this example, you add a "day" type and a "month" type:

    public enum DaysAndMonths
    day(null),
    month(null),

    3

    Create sub categories under the basic categories:

    public enum DaysAndMonths
    day(null),
    Monday(day), Tuesday(day), Wednesday(day), Thursday(day), Friday(day),
    month(null),
    January(month), February(month), March(month), April(month), May(month), June(month), July(month), August(month), September(month),
    October(month), November(month), December(month)



How to Draw a Circle in NetBeans

Instructions

    1

    Create a new project. Select "Java," then"Java Application." Create a main class named "DrawCircle." Click "Finish."

    2

    Enter the following code into the new "DrawCircle" class. This code represents a function that will draw a circle in a system window:

    import java.awt.;
    import java.awt.event.
    ;
    import java.awt.geom.*;

    public class CircleDraw extends Frame
    Shape circle = new Ellipse2D.Float(100.0f, 100.0f, 100.0f, 100.0f);
    Shape square = new Rectangle2D.Double(100, 100,100, 100);
    public void paint(Graphics g)
    Graphics2D ga = (Graphics2D)g;
    ga.draw(circle);
    ga.fill(circle);
    ga.setPaint(Color.red);
    ga.draw(square);

    3

    Create the main function after the "CircleDraw" function:

    public static void main(String args[])
    Frame frame = new CircleDraw();
    frame.addWindowListener(new WindowAdapter()
    public void windowClosing(WindowEvent we)
    System.exit(0);

    );
    frame.setSize(300, 250);
    frame.setVisible(true);

    This code will create a new system window, call the CircleDraw function, and draw the circle in the new window.

    4

    Press the green arrow in the top menu bar to run the program. A window containing a circle will appear.



How to Link to the GUI Interface in Java with a Code

Instructions

    1

    Open your Java editor on your desktop, and open your Java project. Open the source code file you want to use to create a GUI.

    2

    Copy and paste the following code to the top of your file:

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

    These commands import the necessary libraries to create a GUI in Java.

    3

    Test the new libraries using the "JFrame" class. The JFrame class creates a form on the user's desktop. Add the following code to your source code file:

    JPanel pane = new JPanel();
    setVisible(true);

    4

    Save the changes, and click the "Run" button to run the new code in the Java debugger.



How to Convert JSP to Java

Instructions

    1

    Write a JSP page. The JSP page can contain HTML as well as Java code. The file can be a simple HTML document saved with a ".jsp" extension. Name the file "test.jsp".

    2

    Start the Tomcat server or confirm that it is installed and activated. Apache Tomcat runs Java Server Pages and compiles them into Java. Tomcat can be downloaded from Tomcat.apache.org.

    3

    Execute the Web page through the browser. If Tomcat is running, simply point your browser to "http://localhost:8080/examples/jsp/test.jsp".

    4

    Get the file from the temp directory. Once it has run through the server, the JSP file becomes a Java file and it is stored in the work directory of the app. This directory differs, depending on the operating system. You can get the .java file from that directory.



How to Make an Address Book in NetBeans

Instructions

    1

    Open the Netbeans software on your desktop. Click "File" and select "New." Click "Project." Type "AddressBook" for the app name and click "OK." A blank project is created on your desktop.

    2

    Drag and drop a "JForm" from the Netbeans toolbox to the center panel. The JForm is the object that contains your text boxes and buttons for the address book app. After you drag and drop the JForm to the center pane, you can create the address book text boxes your users use to fill out the data.

    3

    Drag and drop a text box control to the form. For instance, you need a first and last name text box. Drag and drop two text boxes to the JForm. Netbeans automatically draws the text boxes for you, so you just need to label them with "First Name" and "Last Name," so users know where to place the data.

    4

    Add a button to submit and store the new entry. Double-click the button to open the code panel where you add the code that saves the data to the database.

    5

    Add the code that stores the contact to the database. The following code is an example of storing the first and last name in a "contacts" database table:

    insert = query.executeQuery("insert into contacts (fname, lname) values ('" + fname + ";, '" + lname + "')");

    6

    Click the "Run" button to run the Netbeans app in the Java debugger.



How to Make a Chat Without Needing Java

Instructions

    1

    Create a socket object and bind it to a port so that it may listen for incoming messages:

    soc = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    soc.bind(('127.0.0.1',5432))
    soc.listen(5)

    2

    Define the class to receive messages. This relies on the "threading" library so that it can run in the background of other applications:

    class ChatThread(threading.Thread):

    def __init__(self,c):
    threading.Thread.__init__(self)
    self.conn = c
    self.stopIt=False
    3

    Define the "run" method, which executes when a thread of type "ChatThread" executes:

    def run(self):

        while not self.stopIt:
    msg = self.message_recv()
    print 'recieved-> ',msg
    4

    Define a message receiving class, which runs as part of the "run" method. This waits for messages and returns the message once received:

    def message_recv(self):

        data = self.conn.recv(SIZE)
    self.conn.send('OK')
    msg = self.conn.recv(int(data))
    return msg
    5

    Get a socket connection and create a ChatThread thread:

    c1,a1 = soc.accept()

    thr = ChatThread(c1)
    thr.start()
    sender = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    soc.bind(('127.0.0.1',5433))
    sender.send('Message')



How to Find a Triangle Within a Triangle Using Java Code

Instructions

    1

    Create a class that represents a triangle, storing three points representing x and y coordinates. These points will represent the basic triangle (Source 1):

    class T

    public static void main(String[] args)

    int[] s1 = 10, 6;
    int[] s2 = 16, 16;
    int[] s3 = 4, 0;


    2

    Determine the midpoint of two different sides (Source 1):

    int diff_side1x = s2[0] - s1[0];
    int diff_side1y = s2[1] - s1[1];
    int[] mid_side1 = diff_side1x + s1[0], diff_side1y + s1[1];

    int diff_side2x = s2[0] - s3[0];
    int diff_side2y = s2[1] - s3[1];
    int[] mid_side2 = diff_side2x + s3[0], diff_side2y + s3[1];

    3

    Connect the two midpoints to one of the already existing points. These three points will form a triangle inscribed in the original (Source 1):

    //original triangle
    s1;
    s2;
    s3;

    //internal triangle
    s3;
    mid_side1;
    mid_side2;

    //internal triangle
    s2;
    mid_side1;
    mid_side2;



How to Build JBoss With Java 6

Instructions

    1

    Open a Web browser and download the ZIP file that contains the JBoss source code files.

    2

    Unzip the file contents to a directory on your computer. Click the Windows "Start" button and type "cmd" in the search text box. Press "Enter" to open the command prompt.

    3

    Type the following command into the command prompt:

    java -classpath newfile.jar sourcecode.java

    Replace the JAR file name with the executable you want to build. Replace "sourcecode.java" with the source code file in the downloaded directory.



How to Make Certificates for Unsigned Android Apps

Instructions

    1

    Click the Windows "Start" button and type "cmd" in the search text box. Press "Enter" to open the command prompt on the desktop.

    2

    Type "c:project" where "project" is the folder in which your Android app is stored. This command moves the prompt to your Android project location.

    3

    Type "ant debug" and press "Enter." The project compiles with the unsigned certificate.



How to Calculate the Checks of a String Using Adler32 in Java

Instructions

    1

    Import the "Adler32" and "CheckedInputStream" modules, which calculate and store the checksum of a file or string. Use the following code:

    import java.util.zip.CheckedInputStream;
    import java.util.zip.Adler32;

    2

    Define a string value and convert it into a byte stream. Adler32 will only calculate checksums on incoming data streams:

    String s = "This is the String";
    byte buff[] = s.getBytes()'
    ByteArrayInputStream ba = new ByteArrayInputStream(buff);

    3

    Calculate the checksum using an Adler32 object:

    CheckedInputStream checked = new CheckedInputStream(ba, new Adler32());



How to Create UML From Java Source

Instructions

    1

    Open the Eclipse software and the project you want to map in the UML modeler. Click the "File" menu and select "New Project." Choose "UML Project" to start the modeler.

    2

    Drag and drop the ".java" source code files in the left navigation panel to the center UML designer panel. The modeler automatically draws a class map for you, and it displays in the designer.

    3

    Click the "Drawing Tools" menu item and select the "Line" object. Use your mouse to draw lines between the different classes. For instance, connect the "User" class with the "Orders" class to indicate that users have a relationship with orders.

    4

    Click the "Save" button to save the changes. If you want to test the new UML, you can generate Java code from the UML design, which is called "forward engineering." Right-click one of the classes and select "Generate Java" to create the code from the UML.



How to Build a Jar File With Build.xml

Instructions

    1

    Create a source directory for your project, containing subfolders named "src," "lib," and "build."

    2

    Write a simple "Hello World" program, and save the file in the "src" folder under the name "test.java":

    class HW

    public static void main(String[] args)

    System.out.println("Hello World");

    3

    Create a file called "build.xml" in the main project directory, and include the following line of code:

    4

    Write the project root tags in the build.xml file:


    5

    Add the following code into the "project" section of the build.xml file. This code defines the dependencies for the build file and compiles the test.java file:



    6

    Save the build file, then execute it by navigating a command terminal to the main project directory and entering the command "ant."



I Can't Find .APK for an Android Project

Can't Find APK in Eclipse

    Since Google recommends that Android developers use Eclipse to build Android projects, issues with Eclipse are common. If you built your project in Eclipse and now Eclipse can't find it, you need to change Eclipse's properties. Click the Project menu and select "Properties." Click "Android." Uncheck "ls Library." If that does not solve the problem, try copying your source code to a new project and rebuilding the APK.

Windows Explorer

    To find your APK on your Windows hard drive, use Windows Explorer. Check in your "My Documents" folder and in the folder for the program you used to write your project, which is usually located in the Program Files directory. If you still can't find your project, type ".apk" in the Search field. Windows Explorer will list all of the files on your computer with ".apk" in the file name.

Linux

    Since Android runs on a Linux kernel, many people choose to use Linux to develop their Android projects. If you can't find your APK file on your Linux hard drive, open your Home folder. Press "Ctrl" plus "h" to reveal any hidden files and folders. Type ".apk" in the Search field and press "Enter." If you would rather use the command line, open a terminal session. Type "find / -name "*.apk" and press "Enter."

Other Considerations

    Try rebuilding your project again. If you walked away from your computer while your project was compiling, it is possible that you missed an error message and that your APK was never built. If you are having problems with an SDK other than Eclipse, ask the software manufacturer for support. It's possible that you do not have everything configured correctly.



How to Clear a Screen and Put a New One in Java

Instructions

    1

    Enter the following code at the beginning of your Java program to import the required components:

    import java.lang.*;

    2

    Enter the following code into the Main method of your Java application:

    public void ClearConsole()

    3

    Enter the following code between the ClearConsole brackets to create a loop:

    for (int i = 0; i < 50; i++)
    System.out.println("n");

    4

    Enter the following code within your program whenever you want to clear the console and start with a blank screen:

    new Main().ClearConsole();



How to Make a Proxy in Java

Instructions

    1

    Create a generic interface that contains an abstract method. For example:

    interface ProxyInterface
    public void method();

    2

    Create two classes that implement the ProxyInterface:

    class P1 implements ProxyInterface

    class P2 implements ProxyInterface

    3

    Create an implementation of "method()" in class "P2." Then, call the P2 version of "method()" from "P1." P1 now represents the proxy class:

    class P1 implements ProxyInterface

    P2 p = new P2();

    public void method()
    p.method();

    class P2 implements ProxyInterface

    public void method()
    System.out.println("Hi");



How to Build a Simple Clock for an Android in Eclipse

Instructions

    1

    Open the Android Eclipse programming software and open the Android project you want to edit. Double-click the XML file for your app.

    2

    Add the "LinearLayout" tag container. This container holds the objects such as buttons, text and the clock, so you can display the objects in one screen. Add the following code:
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    3

    Add the clock tag to display the object in the layout container. Place the following code in the LinearLayout tag container:
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

    4

    Click the "Save" button and click "Run" to execute the code in the Android emulator.



How to Create Interactive Widgets for the Android

Instructions

    1

    Open the Java Eclipse editor and the project in which you want to display the widget. Double-click the XML file in the "resource" directory and the Java source code file in the left navigation panel.

    2

    Create the button for the interactive widget. The button displays results after the user taps it on an Android device. Add the following XML code to the XML file:

     android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:text="@string/sayhello"
    android:onClick="helloFunction" />

    The button's name is set as "sayhello." When the user taps the button, the "helloFunction" function triggers. After you create the interactive button, you must create the Java function that runs the code to display feedback to the user.

    3

    Switch to the Java source code file you opened previously. In this file, you create the widget's function. For instance, in this example, the text "Hello, World" displays on the screen:

    public void helloFunction(View view)

    TextView tv = new TextView(this);
    tv.setText("Hello, World");
    setContentView(tv);

    4

    Save the changes and click the Eclipse "Run" button in the main menu to review your button functionality.



How to Change Text Color in Java Chat

Instructions

    1

    Open your website files using an FTP client.

    2

    Open the file containing your embedded Java Chat code using Notepad.

    3

    Locate the following parameter:

    4

    Enter the hexadecimal value of the desired color in the Value field.

    5

    Save the website file and upload to your Web server.



How to Get Button Backgrounds in Android

Instructions

    1

    Open the Eclipse software and your Android project to load the code files in the editor and emulator. Double-click the XML file for the layout.

    2

    Create the basic button XML. The following code creates a button with the standard button background:



How to Disable Random Numbers in Java

Instructions

    1

    Open your Java programming editor and open the Java app project you want to edit. Open the source code file you want to use to create the random number.

    2

    Initialize the random generator class. Initialization lets you set up the generator to return a number. Add the following code to the file:

    Random random = new Random();

    3

    Generate a number. You specify the range in which you want to generate a number. The range is from zero to a positive integer number. For instance, the following code generates a number between zero and five:

    int number = random.nextInt(5);

    4

    Pass the integer to the function that disables the control. For instance, the following code passes the random number to the "DisableControl" function:

    DisableControl(5);



How to Connect to ODB Java

Instructions

    1

    Open your Java programming software and the desktop project you want to edit. Double-click the data connections source code file to load it in the Java editor.

    2

    Add the connection drivers for the SQL language. You need these drivers to query the server. Add the following code to the top of your file:

    import java.sql.Connection;

    3

    Create the connection string variables. The following code sets up the strings you use with the connection libraries:

    String driver = "sun.jdbc.odbc.JdbcOdbcDriver";

    String url = "jdbc:odbc:northwind";

    String username = user"";

    String password = "pass";

    Replace the "user" and "pass" values with your username and password.

    4

    Create the connection object:

    Connection connect = new Connection(url, username, password);



How to Change the JDK in BEA WebLogic 8.1

Instructions

    1

    Launch the Notepad text editor and open the setDomainEnv.cmd file for the domain you want to edit. You can find that file in the bin directory that is inside your domain folder.

    2

    Type the following code in the file, followed by the name of the JDK you wish to use:

    set JAVA_VENDOR=

    For example, to use the Sun JDK, type "set JAVA_VENDOR=SUN"

    3

    Save the file and restart your Oracle WebLogic server.



How to Embed Java in Flash

Instructions

    1

    Download and install the Java Flash Player API from jpackages.com. You can get the trial version for free or purchase the API.

    2

    Add the downloaded JAR file to your classpath. In the Eclipse project window, click Java Build Path, and then the Add External Jars tab in the right panel. Navigate to the Java Flash Player JAR and click "OK."

    3

    Use the Java Flash Player API to import a Flash file into your project:

    import java.awt.;
    import java.awt.event.
    ;
    import javax.swing.;
    import javax.swing.filechooser.FileFilter;
    import java.io.
    ;
    import com.jpackages.jflashplayer.*;

    class FlashTest

    public static void main(String[] args)

    FlashPanel.setRequiredFlashVersion("9");
    FlashPanel flashPanel = new FlashPanel(new File("Movie.swf")); // loaded movie



Java UDP: How to Send a File

Instructions

    1

    Create the base class to send the UDP datagram, with a main function. The class will use the "DatagramPacket," "DatagramSocket," and "InetAddress" libraries:

    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.net.InetAddress;

    class SendUDP

    public static void main(String[] args)


    2

    Create a new DatagramSocket and DatagramPacket in the main method. The datagram socket object will send the datagram packet object, which will get its information from the byte array "buffer":

    DatagramSocket s = new DatagramSocket();

    byte[] buf = new byte[1000];
    DatagramPacket out;
    3

    Create a sample message to send over UDP, and encode it into the byte array "buf:"

    String outString = "This is the message";
    buf = outString.getBytes();

    4

    Instantiate the "out" datagram packet with the buffer byte array containing the message, and point it towards the IP adress of the receiver, received through the "getByName" method. The number "9999" represents a port number open to UDP connections on the receiver's end: this could be any port number, depending on the receiving server's configuration.

    InetAddress reciever = InetAddress.getByName("http://www.sun.java.com");

    DatagramPacket out = new DatagramPacket(buf, buf.length, receiver, 9999);

    5

    Send the packet. Now that the datagram packet contains information required to send, transmit it through the Datagram socket:

    s.send(out);



How to Write Your Own Simple Java Message Queue

Instructions

    1

    Open your Java programming software and the project for the queue code. Double-click the code file to open it in the editor.

    2

    Create the URL or file location for the queue. In this example, the queue is set up in the C:queue folder:

    String queue = "c:queue";
    ConnectionFactory connect = new ActiveMQConnectionFactory(queue);

        Connection msg = connect.createConnection();
    msg.start();
    3

    Start the destination session. After you create the folder location, you must start the destination session to listen for new messages. The following code sets up the session listener:

    Destination dest = session.createQueue();

    4

    Send a message to the queue to test the new session and messaging service. In this example, a text message is sent to the queue:

    MessageProducer pro = session.createProducer(destination);

        TextMessage text = session.createTextMessage("my message");
    pro.send(text);


How to Randomly Cycle Images With Java

Instructions

    1

    Open the Java editor you want to use to create the random image function. Open the Java source code file you want to edit.

    2

    Create an array of images, if you do not already have an image array set up. For instance, the following code creates an array of two images:

    string[] images;
    images[0] = "image1.jpg";
    images[1] = "image2.jpg";

    3

    Create a random number you use to plug in to your array. The following code randomly generates a number between zero and one, because the array index starts with zero and not one:

    Random gen = new Random();
    int number = randomGenerator.nextInt(1);

    4

    Display the randomly generated image from the array. The following code shows the image to the user:

    System.out.println(images[number]);



How to Use CutePDF From Java

Instructions

    1

    Set up your class:

    class ExampleClass

    public static void main(String[] args)


    2

    Create a "Process" object:

    public static void main(String[] args)
    Process p;

    3

    Use the Process object to call CuteFtp from the command line. This opens a separate process running CuteFTP that the user can interact with. The command for opening the file depends on the host operating system:

    public static void main(String[] args)

    Process p;
    p = Runtime.getRuntime().exec("open CuteFTP.app"); //MacOS



How to Write a Blurb With a Java Program

Instructions

    1

    Set up a Blurb class. This class will contain a String array, which will contain the blurbs, as well as a counter to count the number of blurbs:

    import java.io.*;
    import java.util.Random;

    class Blurb

    String[] blurbs = new String[20];

    int count = 0;

    public static void main(String args[])


    2

    Create a list of blurbs in an array:

    public static void main(String args[])

    blurbs[0] = "blurb 1";
    blurbs[1] = "blurb 2";
    blurbs[2] = "blurb 3";
    blurbs[3] = "blurb 4";

    count = 4; //four blurbs

    3

    Generate a random number in the main program:

    Random r = new Random(); //random number up to

    4

    Cycle through the blurbs at short intervals, using a random number each time:

    for (int i = count; i < count; i++)
    int current = r.nextInt(count); //random number between 0 and 3
    System.out.println(blurbs[current]);

    Thread.sleep(10000); //pause for ten seconds



How to Build an App Around a Java Applet

How to Build an App Around a Java Applet

Instructions

    1

    Locate the Java source code file containing the applet's main method. If the applet consists of more than one file, then this is usually the one whose name is the same as the Applet itself. It will contain a "public void init()" method.

    2

    Change the part of the class declaration that reads "extends JApplet" to "extends JFrame" for the program to run as an app instead of an application.

    3

    Change the method declaration "public void init()" to "static public void main (String [] args)" to change the program's function from that of an applet to a regular app.

    4

    Add the lines "import javax.swing.;" and "import java.awt.;" to the very top of the source code file.



Resize Method for Java Applets

Instructions

    1

    Open the Java applet's source code file in your favored development program.

    2

    Go to the top of the file, after any "include" references.

    3

    Type "scrollbarResizer=True;" on a new line.

    4

    Type "clientResizer=True;" on another new line.

    5

    Save the applet to complete the process.



How to Know if Your Server Has JavaMail

Instructions

    1

    Open the JSP editor from your Windows program menu. Open your current project and create a new file. Name the file "test.jsp" so you can quickly find it and delete it from the project after you finish testing for JavaMail.

    2

    Add the JavaMail library to the top of your file. The following shows you how to add an include file with the JavaMail server library:

    <%@ page import="sun.net.smtp.SmtpClient" %>

    3

    Save the file and click "Run" in the JSP editor to run the file on the server and in your default browser. If the page returns "Error on Line 1," you know that the server doesn't contain the JavaMail server files. If no error is presented, you know your server contains JavaMail.



How to Convert From RGB to YCrCb in Java

How to Convert From RGB to YCrCb in Java

Instructions

    1

    Define a new function named "RGB_to_YCrCB()" in your Java file.

    void RGB_to_YCrCB (int[] RGB, int[] YCrCB)
    ...

    2

    Calculate the Y value from RGB using the following conversion.

    YCrCb[0] = (int) ( 0.299 RGB[0] + 0.587 RGB[1] + 0.114 * RGB[2]);

    3

    Calculate the Cr value from RGB using the following conversion.

    YCrCb[1] = (int) ( -0.16874 RGB[0] - 0.33126 RGB[1] + 0.50000 * RGB[2]);

    4

    Calculate the Cb value from RGB using the following conversion.

    YCrCb[2] = (int) ( 0.50000 RGB[0] - 0.41869 RGB[1] - 0.08131 * RGB[2]);



How to Connect Frames Using NetBeans

Instructions

    1

    Open NetBeans and the Java project you want to edit, then double-click the file for the first frame you want to use to link to another frame.

    2

    Create the second frame by adding the following code:

    JFrame frame2 = new JFrame("My Frame");

    Change the "My Frame" text to your own title for the frame.

    3

    Open the frame and set its visibility status so it displays on the user's desktop. The following code links and opens the second frame:

    frame2.setVisible(true);

    4

    Save the frame code changes and click NetBeans' "Run" button to execute the code in the debugger.



How to Use Tesseract OCR in Java

Instructions

    1

    Right-click the Java file you want to use to create the OCR document. Click "Open With" and select your preferred Java editor.

    2

    Add the OCR library namespace at the top of the file. Copy and paste the following code to your source code file:

    com.tplan.robot.imagecomparison.tesseractocr

    3

    Create the code that scans characters to the file. For instance, the following code loops through each character in a file and writes it to an image file:

    Var lines=0
    Compareto method="tocr" cmparea="x:33,y:2,w:200,h:22"
    for (i=1; i Typeline "_TOCR_LINEi"

    4

    Click the Java editor's "Save" button and click "Run" to execute the code in a Java debugger.



How to Remove Default Attribute Values From the Output Java XML Transformer

Instructions

    1

    Open the Java editor you use to create your applications. Open the project, and then double-click the Java source code file you want to use with the Transformer class.

    2

    Add the libraries to the top of the source code file. You must add the "includes" to use the libraries. The following code adds the includes to the source code:

    include javax.xml.transform;

    3

    Initialize the Java Transformer class. The following code code initializes the class:

    TransformerFactory trans = TransformerFactory.newInstance( );

    4

    Load the XLST file you want to use to transform the XML data. The following code loads a file named "styles.xlst":

    Transformer file = transFact.newTransformer("stles.xlst");

    5

    Remove the default attribute. You remove the default attribute by setting it to a blank string. The following code removes the attribute:

    file.setParameter("default", "");

    6

    Save the changes and click the "Run" button in the editor's toolbar to view the code changes in the debugger.



How to Find Foreign Keys Using Inner Joins in Java

Instructions

    1

    Open the Java editor you use to create your project. Open the project and source code file in which you want to link and use the inner join statements.

    2

    Add the JDBC libraries. Copy and paste the following code to the top of the Java source code file:

    import java.sql.*;

    3

    Replace the "root" and "password" values with your own username and password in the following code to connect to the server and a database named "mydata":

    Class.forName("com.mysql.jdbc.Driver");
    con = DriverManager.getConnection
    ("jdbc:mysql://localhost:3306/mydata","root","password");

    4

    Set up the inner join statement. The following code connects a customer table to an orders table to find the foreign key called "customerid":

    Statement query = con.createStatement();
    ResultSet dataset = query.executeQuery
    ("select * from customers c join orders o on o.customerid=c.customerid");

    5

    Display the results. The following code displays the first customer name in the joined statement to verify that the query worked successfully:

    string name = dataset.getInt("name");
    System.out.println("Customer name: " + name);



How to Grab Key Events Outside Java

Instructions

    1

    Open the Java editor that you use to write your code and load up the project you want to edit. Double-click on your Java source code file.

    2

    Add the event handler that detects when a user presses a key. The following Java code detects each key press:

    public boolean mouseDown( Event evt, int x, int y)

    The Java code that you want to execute when the key is pressed is placed within the brackets.

    3

    Add code to the event handler. The following example echoes the keystroke back to the user:

    System.out.println("You pressed the " + evt.key + " key.");



How to Append a String to Another String in Struts 2 in JSP

Instructions

    1

    Right-click the JSP file you want to edit and select "Open With." Select your preferred JSP editor.

    2

    Create the two strings you want to use. The following code creates two strings you can concatenate:

    String str1 = "First String";
    String str2 = "Second String";

    3

    Append the second string to the first string using the "+" character. The following code appends "str2" to "str1":

    String appended = str1+str2;

    4

    Print the results to the user's screen. The following code displays the new string to the user:

    System.out.println(appended);



How to Insert Java Faces as a JSP Fragment

How to Insert Java Faces as a JSP Fragment

Instructions

    1

    Create a file with a ".JSPF" extension.

    2

    Type all the necessary taglib directives at the top of the file and then put all your JSF code within your "" and "" tags.

    3

    Save the file and upload it to the same server directory as the JSP file into which you will import it.

    4

    Import the JSP Fragment into your JSP file by including the directive "<%@ include file="file.jspf" %>" at the top of your file.



How to Hibernate Using Scroll in Java

How to Hibernate Using Scroll in Java

Instructions

    1

    Determine the parameters of your search so that you know exactly what you're looking for in your search query. The reason for this is simple. If you try to use the "ScrollableResults" command to try to find your data, the end result will be that your query will lead to your program trying to read each row of data. This could literally result in the computer trying to load millions of rows of data, which takes significant RAM or Random Access Memory, thereby slowing your entire system down until the search has finished.

    2

    Begin your query by entering the proper Java command: "Session.createQuery()." This command will indicate you're beginning your search for the data you want to scroll for. The "setMaxResults()" and "setFirstResult()" commands allow you to determine the page of your query. Other types of commands can also be used to limit your search results and speed up the process.

    3

    Complete your query by entering the "scroll()" command into the query instructions. The "scroll()" command will begin the search according to whatever specifications you entered as you began the query. You can execute the query again with different parameters, but you'll have to wait until the first query has completed.

    4

    Remove objects from your session, especially when working on multiple queries. This can be done by adding the "evict()" command string. This command is designed to keep you from running out of memory, which you can do by using the scroll function when you conduct multiple search queries back to back.



How to Convert P12 with Keytool

Instructions

    1

    Click "Start." Type "cmd" into the search box and then press "Enter" to open Command Prompt.

    2

    Type "cd/" without quotes into the command-line application and then press "Enter" to go to the root folder.

    3

    Enter "cd" followed by the full file path linking to the directory where the keystore is saved.

    4

    Type the following into Command Prompt to convert P12 to JKS:

    keytool -importkeystore -srckeystore keystore.p12 -srcstoretype PKCS12 -deststoretype JKS -destkeystore keystore.jks

    Press "Enter" after each command to convert P12 to JKS in Keytool. You may be prompted to create a new password for the JKS keystore; it's recommended that you use the same password as the original keystore.



How to Use Weblogic.ejbc Instead of Weblogic.appc

Instructions

    1

    Open your Windows Start menu, type "cmd" in the search box and press "Enter" to open the command-line prompt utility.

    2

    Enter the following command in the command-line prompt window:

    cd C:BEAinstfolderejb

    Replace "BEAinstfolder" with the path of your BEA WebLogic Server installation directory.

    3

    Type the following command in the command-line prompt utility:

    java weblogic.ejbc options originalfiles outputfiles

    Replace "options" with any option you would like to use, "originalfiles" with the name of the original JAR file or the name of the directory containing the source files and "outputfiles" with the name of the JAR file or directory into which WebLogic.ejbc should place the compiled files.

    4

    Press the "Enter" key to start the compiling process.



How to Format a Parser in a Java String

Instructions

    1

    Type the following code:

    String myString = "This is the string I want to parse";

    This code creates a string variable named "myString" that you want to divide using your parser.

    2

    Type the following code:

    String delimiter = "[i]";

    This creates a string that you will use as your delimiter, which indicates the characters you want to use as tokens to break up the parsed string. In this example, you use only a lowercase "i." Uppercase "I" will not be included in the parsing process.

    3

    Type the following code:

    String[] myParsedString = myString.split(delimiter);

    This line parses the string, using the delimiter to break it up. The square brackets after "String" indicates you want to create an array to save the results. The value of "myParsedString" after execution is ("Th", "s ", "s the str", "ng I want to parse").

    4

    Type the following code:

    String[] myParsedString = myString.split(delimiter, 3);

    This line parses the string similarly to the previews example, except it limits the array result to three values, ignoring any occurrences of the delimiter after the third. The value of "myParsedString" after execution is ("Th", "s ", "s the string I want to parse").