### Basic DnD Setup Source: https://docs.oracle.com/javase/tutorial/uiswing/examples/dnd/BasicDnDProject/src/dnd/BasicDnD.java Initializes the main frame and panels for the drag and drop example. Sets up the layout for components. ```Java /* * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Oracle or the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package dnd; /* * BasicDnD.java requires no other files. */ import java.util.*; import java.awt.*; import java.awt.event.*; import java.text.*; import java.awt.datatransfer.*; import javax.swing.*; import javax.swing.text.*; import javax.swing.tree.*; import javax.swing.table.*; public class BasicDnD extends JPanel implements ActionListener { private static JFrame frame; private JTextArea textArea; private JTextField textField; private JList list; private JTable table; private JTree tree; private JColorChooser colorChooser; private JCheckBox toggleDnD; public BasicDnD() { super(new BorderLayout()); JPanel leftPanel = createVerticalBoxPanel(); JPanel rightPanel = createVerticalBoxPanel(); //Create a table model. DefaultTableModel tm = new DefaultTableModel(); tm.addColumn("Column 0"); tm.addColumn("Column 1"); tm.addColumn("Column 2"); tm.addColumn("Column 3"); tm.addRow(new String[]{"Table 00", "Table 01", "Table 02", "Table 03"}); tm.addRow(new String[]{"Table 10", "Table 11", "Table 12", "Table 13"}); tm.addRow(new String[]{"Table 20", "Table 21", "Table 22", "Table 23"}); tm.addRow(new String[]{"Table 30", "Table 31", "Table 32", "Table 33"}); //LEFT COLUMN //Use the table model to create a table. table = new JTable(tm); leftPanel.add(createPanelForComponent(table, "JTable")); //Create a color chooser. colorChooser = new JColorChooser(); leftPanel.add(createPanelForComponent(colorChooser, "JColorChooser")); //RIGHT COLUMN //Create a textfield. textField = new JTextField(30); textField.setText("Favorite foods:\nPizza, Moussaka, Pot roast"); rightPanel.add(createPanelForComponent(textField, "JTextField")); //Create a scrolled text area. textArea = new JTextArea(5, 30); textArea.setText("Favorite shows:\nBuffy, Alias, Angel"); JScrollPane scrollPane = new JScrollPane(textArea); rightPanel.add(createPanelForComponent(scrollPane, "JTextArea")); //Create a list model and a list. DefaultListModel listModel = new DefaultListModel(); listModel.addElement("Martha Washington"); listModel.addElement("Abigail Adams"); listModel.addElement("Martha Randolph"); listModel.addElement("Dolley Madison"); listModel.addElement("Elizabeth Monroe"); listModel.addElement("Louisa Adams"); listModel.addElement("Emily Donelson"); list = new JList(listModel); list.setVisibleRowCount(-1); list.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); list.setTransferHandler(new TransferHandler() { public boolean canImport(TransferHandler.TransferSupport info) { // we only import Strings if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) { return false; } JList.DropLocation dl = (JList.DropLocation)info.getDropLocation(); if (dl.getIndex() == -1) { return false; } return true; } ``` -------------------------------- ### Batch Update Example Setup (Java) Source: https://docs.oracle.com/javase/tutorial/jdbc/basics/sqlstructured.html Sets up the necessary components for a JDBC batch update, including connection and utility classes. ```java package com.oracle.tutorial.jdbc; import java.sql.*; public class InsertStores { public static void main(String args[]) { JDBCTutorialUtilities myJDBCTutorialUtilities; Connection myConnection = null; ``` -------------------------------- ### Start Main Application (JDK 6+) Source: https://docs.oracle.com/javase/tutorial/jmx/mbeans/standard.html Starts the Main application for JDK version 6 and later. ```bash java com.example.Main ``` -------------------------------- ### Create Java Example Directory Source: https://docs.oracle.com/javase/tutorial/getStarted/cupojava/unix.html Use mkdir to create a directory for your Java examples. Navigate into the newly created directory using cd. ```bash cd /tmp mkdir examples cd examples mkdir java ``` -------------------------------- ### Cursor-to-Event Example: Getting XMLEvent Objects Source: https://docs.oracle.com/javase/tutorial/jaxp/stax/example.html Demonstrates how an application can obtain information as an XMLEvent object when utilizing the cursor API. This example is located in the 'cursor2event' directory. ```Java CursorApproachEventObject.java ``` -------------------------------- ### Launch Java Web Start Application Link Source: https://docs.oracle.com/javase/tutorial/deployment/webstart/running.html Example of an HTML anchor tag linking to a JNLP file to launch a Java Web Start application from a browser. ```html Launch Notepad Application ``` -------------------------------- ### Producer-Consumer Example Main Class Source: https://docs.oracle.com/javase/tutorial/essential/concurrency/examples/ProducerConsumerExample.java The main class to start the producer and consumer threads. It initializes a shared 'Drop' object and creates separate threads for the producer and consumer, then starts them. ```java /* * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Oracle or the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ public class ProducerConsumerExample { public static void main(String[] args) { Drop drop = new Drop(); (new Thread(new Producer(drop))).start(); (new Thread(new Consumer(drop))).start(); } } ``` -------------------------------- ### Generate Keystore and Keys Source: https://docs.oracle.com/javase/tutorial/security/toolsign/step3.html Use this command to create a keystore named 'examplestore' and generate a new public/private key pair. You will be prompted for keystore and key passwords. ```bash keytool -genkey -alias signFiles -keystore examplestore ``` -------------------------------- ### Java SimpleThreads Example Source: https://docs.oracle.com/javase/tutorial/essential/concurrency/simple.html This is a comprehensive example demonstrating the creation and management of threads in Java. It includes a main thread that starts a worker thread, pauses its execution, and interrupts it if it takes too long. ```Java public class SimpleThreads { // Display a message, preceded by // the name of the current thread static void threadMessage(String message) { String threadName = Thread.currentThread().getName(); System.out.format("%s: %s%n", threadName, message); } private static class MessageLoop implements Runnable { public void run() { String importantInfo[] = { "Mares eat oats", "Does eat oats", "Little lambs eat oats", "A kid will eat ivy too" }; try { for (int i = 0; i < importantInfo.length; i++) { // Pause for 4 seconds Thread.sleep(4000); // Print a message threadMessage(importantInfo[i]); } } catch (InterruptedException e) { threadMessage("I wasn't done!"); } } } public static void main(String args[]) throws InterruptedException { // Delay, in milliseconds before // we interrupt MessageLoop // thread (default one hour). long patience = 1000 * 60 * 60; // If command line argument // present, gives patience // in seconds. if (args.length > 0) { try { patience = Long.parseLong(args[0]) * 1000; } catch (NumberFormatException e) { System.err.println("Argument must be an integer."); System.exit(1); } } threadMessage("Starting MessageLoop thread"); long startTime = System.currentTimeMillis(); Thread t = new Thread(new MessageLoop()); t.start(); threadMessage("Waiting for MessageLoop thread to finish"); // loop until MessageLoop // thread exits while (t.isAlive()) { threadMessage("Still waiting..."); // Wait maximum of 1 second // for MessageLoop thread // to finish. t.join(1000); if (((System.currentTimeMillis() - startTime) > patience) && t.isAlive()) { threadMessage("Tired of waiting!"); t.interrupt(); // Shouldn't be long now // -- wait indefinitely t.join(); } } threadMessage("Finally!"); } } ``` -------------------------------- ### RMI Client Output Example Source: https://docs.oracle.com/javase/tutorial/rmi/running.html This is the expected output displayed after successfully starting the RMI client. ```text 3.141592653589793238462643383279502884197169399 ``` -------------------------------- ### Basic GridBagLayout Setup Source: https://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html Demonstrates the typical setup for a container using GridBagLayout. It shows how to instantiate the layout manager, create GridBagConstraints, and add components to the panel. ```java JPanel pane = new JPanel(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); //For each component to be added to this container: //...Create the component... //...Set instance variables in the GridBagConstraints instance... pane.add(theComponent, c); ``` -------------------------------- ### Setup JDBC Sample Database Tables Source: https://docs.oracle.com/javase/tutorial/jdbc/basics/gettingstarted.html This command deletes existing tables, recreates them, and populates them with data. It also creates the database for Java DB if it doesn't exist. It's recommended to run this before executing most sample classes. Run from the root of the JDBC tutorial directory. ```bash ant setup ``` -------------------------------- ### Get ButtonGroup from ButtonModel Source: https://docs.oracle.com/javase/tutorial/uiswing/components/button.html Example of how to retrieve the ButtonGroup associated with a specific button's model. ```java ButtonGroup group = ((DefaultButtonModel)button.getModel()).getGroup(); ``` -------------------------------- ### Get Installed MIDI Device Information Source: https://docs.oracle.com/javase/tutorial/sound/accessing-MIDI.html Retrieves an array of MidiDevice.Info objects, each identifying an installed MIDI device such as a sequencer, synthesizer, or port. Use this to list available devices for user selection or programmatic identification. ```java static MidiDevice.Info[] getMidiDeviceInfo() ``` -------------------------------- ### Main Method for JDBCTutorialUtilities Source: https://docs.oracle.com/javase/tutorial/jdbc/basics/examples/JDBCTutorial/src/com/oracle/tutorial/jdbc/JDBCTutorialUtilities.java This is the main entry point for the JDBCTutorialUtilities example. It handles reading properties, establishing a database connection, creating the database if necessary, and performing various JDBC utility operations. Ensure a properties file is specified as a command-line argument. ```Java public static void main(String[] args) { JDBCTutorialUtilities myJDBCTutorialUtilities; Connection myConnection = null; if (args[0] == null) { System.err.println("Properties file not specified at command line"); return; } else { try { System.out.println("Reading properties file " + args[0]); myJDBCTutorialUtilities = new JDBCTutorialUtilities(args[0]); } catch (Exception e) { System.err.println("Problem reading properties file " + args[0]); e.printStackTrace(); return; } } try { myConnection = myJDBCTutorialUtilities.getConnection(); // JDBCTutorialUtilities.outputClientInfoProperties(myConnection); // myConnection = myJDBCTutorialUtilities.getConnection("root", "root", "jdbc:mysql://localhost:3306/"); // myConnection = myJDBCTutorialUtilities. // getConnectionWithDataSource(myJDBCTutorialUtilities.dbName,"derby","", "", "localhost", 3306); // Java DB does not have an SQL create database command; it does require createDatabase JDBCTutorialUtilities.createDatabase(myConnection, myJDBCTutorialUtilities.dbName, myJDBCTutorialUtilities.dbms); JDBCTutorialUtilities.cursorHoldabilitySupport(myConnection); JDBCTutorialUtilities.rowIdLifetime(myConnection); } catch (SQLException e) { JDBCTutorialUtilities.printSQLException(e); } catch (Exception e) { e.printStackTrace(System.err); } finally { JDBCTutorialUtilities.closeConnection(myConnection); } } } ``` -------------------------------- ### ClassSpy Example: Discovering All Public Class Members Source: https://docs.oracle.com/javase/tutorial/reflect/class/classMembers.html The `ClassSpy` example demonstrates how to use `get*s()` methods to list all public members of a class, including inherited ones. It requires the class name as a command-line argument. ```java import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Member; import static java.lang.System.out; enum ClassMember { CONSTRUCTOR, FIELD, METHOD, CLASS, ALL } public class ClassSpy { public static void main(String... args) { try { Class c = Class.forName(args[0]); out.format("Class:%n %s%n%n", c.getCanonicalName()); Package p = c.getPackage(); out.format("Package:%n %s%n%n", (p != null ? p.getName() : "-- No Package --")); for (int i = 1; i < args.length; i++) { switch (ClassMember.valueOf(args[i])) { case CONSTRUCTOR: printMembers(c.getConstructors(), "Constructor"); break; case FIELD: printMembers(c.getFields(), "Fields"); break; case METHOD: printMembers(c.getMethods(), "Methods"); break; case CLASS: printClasses(c); break; case ALL: printMembers(c.getConstructors(), "Constuctors"); printMembers(c.getFields(), "Fields"); printMembers(c.getMethods(), "Methods"); printClasses(c); break; default: assert false; } } // production code should handle these exceptions more gracefully } catch (ClassNotFoundException x) { x.printStackTrace(); } } private static void printMembers(Member[] mbrs, String s) { out.format("%s:%n", s); for (Member mbr : mbrs) { if (mbr instanceof Field) out.format(" %s%n", ((Field)mbr).toGenericString()); else if (mbr instanceof Constructor) out.format(" %s%n", ((Constructor)mbr).toGenericString()); else if (mbr instanceof Method) out.format(" %s%n", ((Method)mbr).toGenericString()); } if (mbrs.length == 0) out.format(" -- No %s --%n", s); out.format("%n"); } private static void printClasses(Class c) { out.format("Classes:%n"); Class[] clss = c.getClasses(); for (Class cls : clss) out.format(" %s%n", cls.getCanonicalName()); if (clss.length == 0) out.format(" -- No member interfaces, classes, or enums --%n"); out.format("%n"); } } ``` -------------------------------- ### GUI Creation and Setup Source: https://docs.oracle.com/javase/tutorial/uiswing/examples/events/FocusEventDemoProject/src/events/FocusEventDemo.java This method sets up the main window, adds components to its content pane, and makes the window visible. It should be invoked from the event dispatch thread for thread safety. ```Java private static void createAndShowGUI() { //Create and set up the window. FocusEventDemo frame = new FocusEventDemo("FocusEventDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Set up the content pane. frame.addComponentsToPane(frame.getContentPane()); //Display the window. frame.pack(); frame.setVisible(true); } ``` -------------------------------- ### Get Root Node Source: https://docs.oracle.com/javase/tutorial/uiswing/examples/components/GenealogyExampleProject/src/components/GenealogyModel.java Returns the root node of the genealogy tree. This is the starting point for traversing the tree structure. ```Java public Object getRoot() { return rootPerson; } ``` -------------------------------- ### Navigate to Java Example Directory Source: https://docs.oracle.com/javase/tutorial/getStarted/cupojava/unix.html Change your current directory to the location where your Java source files will be stored. ```bash cd /tmp/examples/java ``` -------------------------------- ### Main Application Setup Source: https://docs.oracle.com/javase/tutorial/uiswing/examples/dnd/TopLevelTransferHandlerDemoProject/src/dnd/TopLevelTransferHandlerDemo.java Initializes and displays the main application window, setting its size, position, and default close operation. It also requests focus for the list component. ```Java TopLevelTransferHandlerDemo test = new TopLevelTransferHandlerDemo(); test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); if (DEMO) { test.setSize(493, 307); } else { test.setSize(800, 600); } test.setLocationRelativeTo(null); test.setVisible(true); test.list.requestFocus(); ``` -------------------------------- ### Simple Applet Life Cycle Example Source: https://docs.oracle.com/javase/tutorial/deployment/applet/lifeCycle.html This applet displays a descriptive string when it encounters major milestones in its life cycle, such as initialization and starting. It extends the Applet class and overrides init(), start(), stop(), destroy(), and paint() methods. ```Java import java.applet.Applet; import java.awt.Graphics; //No need to extend JApplet, since we don't add any components; //we just paint. public class Simple extends Applet { StringBuffer buffer; public void init() { buffer = new StringBuffer(); addItem("initializing... "); } public void start() { addItem("starting... "); } public void stop() { addItem("stopping... "); } public void destroy() { addItem("preparing for unloading..."); } private void addItem(String newWord) { System.out.println(newWord); buffer.append(newWord); repaint(); } public void paint(Graphics g) { //Draw a Rectangle around the applet's display area. g.drawRect(0, 0, getWidth() - 1, getHeight() - 1); //Draw the current string inside the rectangle. g.drawString(buffer.toString(), 5, 15); } } ``` -------------------------------- ### Loading Startup File and Verifying PATH for Ksh, Bash, or Sh Source: https://docs.oracle.com/javase/tutorial/essential/environment/paths.html Source your profile file (e.g., ~/.profile) and then run 'java -version' to confirm the PATH has been updated for Ksh, Bash, or Sh. ```shell % . /.profile % java -version ``` -------------------------------- ### Create and Show GUI Source: https://docs.oracle.com/javase/tutorial/uiswing/examples/components/JWSFileChooserDemoProject/src/components/JWSFileChooserDemo.java Sets up and displays the main application window. This method should be called from the event dispatch thread for thread safety. ```Java private static void createAndShowGUI() { //Create and set up the window. JFrame frame = new JFrame("JWSFileChooserDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Add content to the window. frame.add(new JWSFileChooserDemo()); //Display the window. frame.pack(); frame.setVisible(true); } ``` -------------------------------- ### QuoteServer Sample Output Source: https://docs.oracle.com/javase/tutorial/deployment/applet/clientExample.html This is an example of the output you will see when the QuoteServer application starts. It indicates the port number on which the server is listening. ```text QuoteServer listening on port:3862 ``` -------------------------------- ### Main Method for JDBC Tutorial Utilities Source: https://docs.oracle.com/javase/tutorial/jdbc/basics/examples/JDBCTutorial/src/com/oracle/tutorial/jdbc/JdbcRowSetSample.java This is the main entry point for the application. It handles command-line arguments for a properties file, initializes JDBCTutorialUtilities, and establishes a database connection. ```Java public static void main(String[] args) { JDBCTutorialUtilities myJDBCTutorialUtilities; Connection myConnection = null; if (args[0] == null) { System.err.println("Properties file not specified at command line"); return; } else { try { myJDBCTutorialUtilities = new JDBCTutorialUtilities(args[0]); } catch (Exception e) { System.err.println("Problem reading properties file " + args[0]); e.printStackTrace(); return; } } try { myConnection = myJDBCTutorialUtilities.getConnection(); ``` -------------------------------- ### Create and Show GUI Method Source: https://docs.oracle.com/javase/tutorial/uiswing/dnd/toplevel.html Sets the system's look and feel and then creates and displays the main application window. It configures the frame's size, default close operation, and makes it visible. ```Java private static void createAndShowGUI(String[] args) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { } TopLevelTransferHandlerDemo test = new TopLevelTransferHandlerDemo(); test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); if (DEMO) { test.setSize(493, 307); } else { test.setSize(800, 600); } test.setLocationRelativeTo(null); test.setVisible(true); test.list.requestFocus(); } ``` -------------------------------- ### Get Mixer Information Source: https://docs.oracle.com/javase/tutorial/sound/accessing.html Retrieves an array of Mixer.Info objects, each describing an installed audio mixer. Iterate over this array to find a suitable mixer. ```java static Mixer.Info[] getMixerInfo() ``` -------------------------------- ### Running the TransformationApp03 Sample Source: https://docs.oracle.com/javase/tutorial/jaxp/xslt/generatingXML.html Execute the compiled TransformationApp03 application, providing a data file as a command-line argument. ```shell % java TransformationApp03 data/PersonalAddressBook.ldif ``` -------------------------------- ### Get Character Stream for Clob Object Source: https://docs.oracle.com/javase/tutorial/jdbc/basics/blob.html Retrieves a Writer object to write character streams to a Clob object, starting at the specified position. ```java Writer clobWriter = myClob.setCharacterStream(1); ``` -------------------------------- ### Get Available Font Family Names Source: https://docs.oracle.com/javase/tutorial/2d/text/fonts.html Retrieves the names of all font families installed on the system. This is useful for listing available fonts to a user. ```java GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); String []fontFamilies = ge.getAvailableFontFamilyNames(); ``` -------------------------------- ### Create JAR with Manifest and Run Application Source: https://docs.oracle.com/javase/tutorial/deployment/jar/appman.html Create a JAR file using the 'cfm' flags, specifying the manifest file and class files. Then, run the JAR file using the 'java -jar' command. ```bash jar cfm MyJar.jar Manifest.txt MyPackage/*.class ``` ```bash java -jar MyJar.jar ``` -------------------------------- ### Tabbed Pane Setup Source: https://docs.oracle.com/javase/tutorial/uiswing/examples/components/BorderDemoProject/src/components/BorderDemo.java Configures a JTabbedPane to display different border examples in separate tabs. Also sets a tooltip for one of the tabs. ```Java JTabbedPane tabbedPane = new JTabbedPane(); tabbedPane.addTab("Simple", null, simpleBorders, null); tabbedPane.addTab("Matte", null, matteBorders, null); tabbedPane.addTab("Titled", null, titledBorders, null); tabbedPane.addTab("Compound", null, compoundBorders, null); tabbedPane.setSelectedIndex(0); String toolTip = new String("Blue Wavy Line border art crew:
   Bill Pauley
   Cris St. Aubyn
   Ben Wronsky
   Nathan Walrath
   Tommy Adams, special consultant"); tabbedPane.setToolTipTextAt(1, toolTip); add(tabbedPane); ``` -------------------------------- ### Run CoffeesTable Sample Source: https://docs.oracle.com/javase/tutorial/jdbc/basics/gettingstarted.html Example command to execute a specific sample class, 'CoffeesTable'. Run from the root of the JDBC tutorial directory. ```bash ant runct ``` -------------------------------- ### GUI Creation and Setup Source: https://docs.oracle.com/javase/tutorial/uiswing/examples/components/SliderDemoProject/src/components/SliderDemo.java Creates and sets up the main JFrame, adding the SliderDemo animator component and making the window visible. ```Java /** * Create the GUI and show it. For thread safety, * this method should be invoked from the * event-dispatching thread. */ private static void createAndShowGUI() { //Create and set up the window. JFrame frame = new JFrame("SliderDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); SliderDemo animator = new SliderDemo(); //Add content to the window. frame.add(animator, BorderLayout.CENTER); //Display the window. frame.pack(); frame.setVisible(true); animator.startAnimation(); } ``` -------------------------------- ### Fully Qualified LDAP Names Source: https://docs.oracle.com/javase/tutorial/jndi/ldap/jndi.html Examples of fully qualified LDAP names as used in the protocol, identifying entries starting from the root of the LDAP namespace. ```text cn=Ted Geisel, ou=Marketing, o=Some Corporation, c=gb cn=Vinnie Ryan, ou=People, o=JNDITutorial ``` -------------------------------- ### Applet Initialization and Setup Source: https://docs.oracle.com/javase/tutorial/deployment/applet/examples/applet_StatusAndCallback/src/DrawingApplet.java Initializes the applet by creating an offscreen image, setting up the graphics context, enabling antialiasing, and simulating a delay. ```Java import java.applet.*; import java.awt.*; import java.awt.geom.*; import java.awt.image.*; /** * This applet exports an API for the use of client-side JavaScript code. */ public class DrawingApplet extends Applet { BufferedImage image; // We draw into this offscreen image Graphics2D g; // using this graphics context // The browser calls this method to initialize the applet public void init() { // Find out how big the applet is and create an offscreen image // that size. int w = getWidth(); int h = getHeight(); image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); // Get a graphics context for drawing into the image g = image.createGraphics(); // Start with a pure white background g.setPaint(Color.WHITE); g.fillRect(0, 0, w, h); // Turn on antialiasing g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); try { // sleep here to simulate a long init method Thread.sleep(4000); } catch (InterruptedException ie) { ie.printStackTrace(); } } // The browser automatically calls this method when the applet needs // to be redrawn. We copy the offscreen image onscreen. // JavaScript code drawing to this applet must call the inherited // repaint() method to request a redraw. public void paint(Graphics g) { g.drawImage(image, 0, 0, this); } // These methods set basic drawing parameters // This is just a subset: the Java2D API supports many others public void setLineWidth(float w) { g.setStroke(new BasicStroke(w)); } public void setColor(int color) { g.setPaint(new Color(color)); } public void setFont(String fontfamily, int pointsize) { g.setFont(new Font(fontfamily, Font.PLAIN, pointsize)); } // These are simple drawing primitives public void fillRect(int x, int y, int w, int h) { g.fillRect(x,y,w,h); } public void drawRect(int x, int y, int w, int h) { g.drawRect(x,y,w,h); } public void drawString(String s, int x, int y) { g.drawString(s, x, y); } // These methods fill and draw arbitrary shapes public void fill(Shape shape) { g.fill(shape); } public void draw(Shape shape) { g.draw(shape); } // These methods return simple Shape objects // This is just a sampler. The Java2D API supports many others public Shape createRectangle(double x, double y, double w, double h) { return new Rectangle2D.Double(x, y, w, h); } public Shape createEllipse(double x, double y, double w, double h) { return new Ellipse2D.Double(x, y, w, h); } public Shape createWedge(double x, double y, double w, double h, double start, double extent) { return new Arc2D.Double(x, y, w, h, start, extent, Arc2D.PIE); } } ``` -------------------------------- ### Method Naming Conventions Source: https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html Examples of common Java method naming conventions. Methods typically start with a lowercase verb, with subsequent words capitalized. ```java run runFast getBackground getFinalData compareTo setX isEmpty ``` -------------------------------- ### Basic SpringLayout Setup Source: https://docs.oracle.com/javase/tutorial/uiswing/layout/spring.html Initializes a JFrame and its content pane with a SpringLayout, adding a label and a text field. This is a starting point for defining component constraints. ```Java public class SpringDemo1 { public static void main(String[] args) { ... Container contentPane = frame.getContentPane(); SpringLayout layout = new SpringLayout(); contentPane.setLayout(layout); contentPane.add(new JLabel("Label: ")); contentPane.add(new JTextField("Text field", 15)); ... frame.pack(); frame.setVisible(true); } } ``` -------------------------------- ### GUI Setup and Menu Creation Source: https://docs.oracle.com/javase/tutorial/uiswing/examples/misc/TextBatchPrintingDemoProject/src/misc/TextBatchPrintingDemo.java Sets up the main application frame, including a JSplitPane for content display, a JList for selected pages, and a JMenuBar with a 'File' menu. The 'File' menu contains items for adding pages, printing, clearing selection, navigating home, and quitting. ```Java void createAndShowGUI() { messageArea = new JLabel(defaultMessage); selectedPages = new JList(new DefaultListModel()); selectedPages.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); selectedPages.addListSelectionListener(this); setPage(homePage); JSplitPane pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new JScrollPane(pageItem), new JScrollPane(selectedPages)); JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic(KeyEvent.VK_F); fileMenu.add(createMenuItem( new AbstractAction("Add Page") { public void actionPerformed(ActionEvent e) { DefaultListModel pages = (DefaultListModel) selectedPages.getModel(); pages.addElement(pageItem); selectedPages.setSelectedIndex(pages.getSize() - 1); } }, KeyEvent.VK_A, KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.ALT_MASK))); fileMenu.add(createMenuItem( new AbstractAction("Print Selected") { public void actionPerformed(ActionEvent e) { printSelectedPages(); } }, KeyEvent.VK_P, KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.ALT_MASK))); fileMenu.add(createMenuItem( new AbstractAction("Clear Selected") { public void actionPerformed(ActionEvent e) { DefaultListModel pages = (DefaultListModel) selectedPages.getModel(); pages.removeAllElements(); } }, KeyEvent.VK_C, KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.ALT_MASK))); fileMenu.addSeparator(); fileMenu.add(createMenuItem( new AbstractAction("Home Page") { public void actionPerformed(ActionEvent e) { setPage(homePage); } }, KeyEvent.VK_H, KeyStroke.getKeyStroke(KeyEvent.VK_H, ActionEvent.ALT_MASK))); fileMenu.add(createMenuItem( new AbstractAction("Quit") { public void actionPerformed(ActionEvent e) { for (Window w : Window.getWindows()) { w.dispose(); } } }, KeyEvent.VK_A, KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.ALT_MASK))); JMenuBar menuBar = new JMenuBar(); menuBar.add(fileMenu); JPanel contentPane = new JPanel(); contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS)); contentPane.add(pane); contentPane.add(messageArea); JFrame frame = new JFrame("Text Batch Printing Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setJMenuBar(menuBar); frame.setContentPane(contentPane); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); if (printService == null) { JOptionPane.showMessageDialog(frame, "No default print service", "Print Service Alert", JOptionPane.WARNING_MESSAGE); } } ``` -------------------------------- ### Comparing matches() and lookingAt() Source: https://docs.oracle.com/javase/tutorial/essential/regex/matcher.html This example shows the difference between `matches()`, which requires the entire input to match, and `lookingAt()`, which only requires a prefix match. Both start at the beginning of the input. ```Java import java.util.regex.Pattern; import java.util.regex.Matcher; public class MatchesLooking { private static final String REGEX = "foo"; private static final String INPUT = "fooooooooooooooooo"; private static Pattern pattern; private static Matcher matcher; public static void main(String[] args) { // Initialize pattern = Pattern.compile(REGEX); matcher = pattern.matcher(INPUT); System.out.println("Current REGEX is: " + REGEX); System.out.println("Current INPUT is: " + INPUT); System.out.println("lookingAt(): " + matcher.lookingAt()); System.out.println("matches(): " + matcher.matches()); } } ``` -------------------------------- ### Create and Show GUI Source: https://docs.oracle.com/javase/tutorial/uiswing/examples/components/MenuDemoProject/src/components/MenuDemo.java Sets up the main JFrame, including the menu bar and content pane, and makes the window visible. This method should be called on the event-dispatching thread. ```java /** * Create the GUI and show it. For thread safety, * this method should be invoked from the * event-dispatching thread. */ private static void createAndShowGUI() { //Create and set up the window. JFrame frame = new JFrame("MenuDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Create and set up the content pane. MenuDemo demo = new MenuDemo(); frame.setJMenuBar(demo.createMenuBar()); frame.setContentPane(demo.createContentPane()); //Display the window. frame.setSize(450, 260); frame.setVisible(true); } ``` -------------------------------- ### Java Regex Matching Example Source: https://docs.oracle.com/javase/tutorial/essential/regex/examples/MatcherDemo.java Finds all occurrences of a whole word 'dog' in a string and prints their start and end indices. Requires importing java.util.regex.Pattern and java.util.regex.Matcher. ```Java /* * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Oracle or the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import java.util.regex.Pattern; import java.util.regex.Matcher; public class MatcherDemo { private static final String REGEX = "\\bdog\\b"; private static final String INPUT = "dog dog dog doggie dogg"; public static void main(String[] args) { Pattern p = Pattern.compile(REGEX); // get a matcher object Matcher m = p.matcher(INPUT); int count = 0; while(m.find()) { count++; System.out.println("Match number " + count); System.out.println("start(): " + m.start()); System.out.println("end(): " + m.end()); } } } ``` -------------------------------- ### GUI Creation and Setup Source: https://docs.oracle.com/javase/tutorial/uiswing/examples/components/RootLayeredPaneDemoProject/src/components/RootLayeredPaneDemo.java Sets up the main JFrame and its content pane for the RootLayeredPaneDemo. Invokes the creation of the GUI on the event-dispatching thread for thread safety. ```java private static void createAndShowGUI() { //Create and set up the window. JFrame frame = new JFrame("RootLayeredPaneDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Create and set up the content pane. RootLayeredPaneDemo newContentPane = new RootLayeredPaneDemo( frame.getLayeredPane()); newContentPane.setOpaque(true); //content panes must be opaque frame.setContentPane(newContentPane); //Display the window. frame.setSize(new Dimension(300, 350)); frame.setVisible(true); } ``` -------------------------------- ### ProducerConsumerExample Main Method Source: https://docs.oracle.com/javase/tutorial/essential/concurrency/QandE/ProducerConsumerExample.java Sets up and starts producer and consumer threads using a SynchronousQueue. Ensure the Producer and Consumer classes are defined elsewhere. ```java /* * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of Oracle or the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import java.util.concurrent.BlockingQueue; import java.util.concurrent.SynchronousQueue; public class ProducerConsumerExample { public static void main(String[] args) { BlockingQueue drop = new SynchronousQueue (); (new Thread(new Producer(drop))).start(); (new Thread(new Consumer(drop))).start(); } } ``` -------------------------------- ### Main Thread for Producer-Consumer Example Source: https://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html This class initializes the shared Drop object and starts the Producer and Consumer threads, demonstrating the complete guarded blocks application. ```Java public class ProducerConsumerExample { public static void main(String[] args) { Drop drop = new Drop(); (new Thread(new Producer(drop))).start(); (new Thread(new Consumer(drop))).start(); } } ``` -------------------------------- ### Importing Tutorial LDIF File with ldapmodify Source: https://docs.oracle.com/javase/tutorial/jndi/software/content.html Use this command to load the tutorial's configuration file (tutorial.ldif) into the directory server. Ensure you replace placeholder values for hostname, administrator DN, and password with your server's specific details. ```bash ldapmodify -a -c -v -h hostname -p 389\ -D "cn=Administrator, cn=users, dc=xxx, dc=xxx"\ -w passwd -f tutorial.ldif ``` -------------------------------- ### Self-Contained Bundles Directory Structure (Windows Example) Source: https://docs.oracle.com/javase/tutorial/deployment/selfContainedApps/converting.html Illustrates the typical directory structure after generating self-contained bundles for Windows, including native binaries and installers. ```text /packager_DynamicTreeDemo <--- application project /build /packager /bundles Dynamic Tree Demo <---folder image Dynamic Tree Demo-1.0.exe <---EXE installer Dynamic Tree Demo-1.0.msi <---MSI installer ... /dist DynamicTreeDemo.jar ... /src /package <--- custom resources /linux /macosx /windows /webstartComponentArch <--- application source files ... ``` -------------------------------- ### Compile Read-and-Write Example Source: https://docs.oracle.com/javase/tutorial/jaxp/stax/example.html Compiles the Java source files for the Read-and-Write example using the provided JAXP library. ```Shell javac -classpath ../lib/jaxp-ri.jar stax/readnwrite/*.java ``` -------------------------------- ### Get Sentence BreakIterator Instance Source: https://docs.oracle.com/javase/tutorial/i18n/text/sentence.html Creates a BreakIterator instance configured to detect sentence boundaries for a given locale. This is the starting point for sentence boundary detection. ```java BreakIterator sentenceIterator = BreakIterator.getSentenceInstance(currentLocale); ``` -------------------------------- ### Main Method for JDBC Stored Procedure Tutorial Source: https://docs.oracle.com/javase/tutorial/jdbc/basics/examples/JDBCTutorial/src/com/oracle/tutorial/jdbc/StoredProcedureJavaDBSample.java This is the main entry point for the JDBC stored procedure tutorial. It handles command-line arguments for properties files, establishes a database connection, initializes tables, and runs stored procedure examples. ```Java public static void main(String[] args) { JDBCTutorialUtilities myJDBCTutorialUtilities; Connection myConnection = null; if (args[0] == null) { System.err.println("Properties file not specified at command line"); return; } else { try { myJDBCTutorialUtilities = new JDBCTutorialUtilities(args[0]); } catch (Exception e) { System.err.println("Problem reading properties file " + args[0]); e.printStackTrace(); return; } } try { myConnection = myJDBCTutorialUtilities.getConnection(); StoredProcedureJavaDBSample mySP = new StoredProcedureJavaDBSample(myConnection, myJDBCTutorialUtilities.dbName, myJDBCTutorialUtilities.dbms); // JDBCTutorialUtilities.initializeTables(myConnection, // myJDBCTutorialUtilities.dbName, // myJDBCTutorialUtilities.dbms); System.out.println("\nCreating stored procedure:"); mySP.createProcedures(myConnection); // System.out.println("\nAdding jar file to Java DB class path:"); // mySP.registerJarFile(myJDBCTutorialUtilities.jarFile); System.out.println("\nRunning all stored procedures:"); mySP.runStoredProcedures("Colombian", 0.10f, 19.99f); } catch (SQLException e) { JDBCTutorialUtilities.printSQLException(e); } finally { JDBCTutorialUtilities.closeConnection(myConnection); } } ``` -------------------------------- ### Subclassing Thread to Start a Thread Source: https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html This example shows how to create a thread by subclassing the Thread class and overriding its run method. This approach is simpler for basic applications but is limited by class inheritance. ```java public class HelloThread extends Thread { public void run() { System.out.println("Hello from a thread!"); } public static void main(String args[]) { (new HelloThread()).start(); } } ``` -------------------------------- ### HelloWorldApp.java - Initial Version Source: https://docs.oracle.com/javase/tutorial/getStarted/QandE/questions.html The basic 'Hello World' program in Java. This is the starting point for Exercise 1. ```java public class HelloWorldApp { public static void main(String[] args) { // schedule a job for the event list System.out.println("Hello World!"); // Display the string into a console } } ``` -------------------------------- ### Get NumberFormat Instance for a Locale Source: https://docs.oracle.com/javase/tutorial/i18n/locale/services.html This snippet demonstrates how to obtain a NumberFormat instance for a specific locale using a NumberFormatProvider. It first checks for runtime support and then queries installed providers if necessary. ```java Locale loc = new Locale("da", "DK"); NumberFormat nf = NumberFormatProvider.getNumberInstance(loc); ``` -------------------------------- ### Get Resource Bundle with Custom Control Source: https://docs.oracle.com/javase/tutorial/i18n/resbundle/control.html This method signature shows how to obtain a ResourceBundle using a specified base name, locale, and a custom Control object to guide the loading process. ```java public static final ResourceBundle getBundle( String baseName, ResourceBundle.Control cont // ... ) ```