JTable Examples #Programming Code Examples #Java/J2EE/J2ME #Advanced Swing

# JTableSimpleExample.java Simple table that takes column names and data from arrays of Strings.

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

/** Simple JTable example that uses a String array for the
 *  table header and table data.
 *
 */

public class JTableSimpleExample extends JFrame {
  public static void main(String[] args) {
    new JTableSimpleExample();
  }

  private final int COLUMNS = 4;
  private final int ROWS = 15;
  private JTable sampleJTable;

  public JTableSimpleExample() {
    super("Creating a Simple JTable");
    WindowUtilities.setNativeLookAndFeel();
    addWindowListener(new ExitListener());
    Container content = getContentPane();

    String[]   columnNames = buildColumnNames(COLUMNS);
    String[][] tableCells = buildTableCells(ROWS, COLUMNS);

    sampleJTable = new JTable(tableCells, columnNames);
    JScrollPane tablePane = new JScrollPane(sampleJTable);
    content.add(tablePane, BorderLayout.CENTER);
    setSize(450,150);
    setVisible(true);
  }

  private String[] buildColumnNames(int columns) {
    String[] header = new String[columns];
    for(int i=0; i<columns ; i++) {
      header[i] = "Column " + i;
    }
    return(header);
  }

  private String[][] buildTableCells(int rows, int columns) {
    String[][] cells = new String[rows][columns];
    for(int i=0; i<rows ; i++) {
      for(int j=0; j<columns; j++ ) {
        cells[i][j] = "Row " + i + ", Col " + j;
      }
    }
    return(cells);
  }
}
*/

# DefaultTableExample.java A dynamic table (rows can be added or deleted) using a DefaultTableModel.

import java.util.Vector;
import javax.swing.*;
import javax.swing.table.*;

/** JTable that uses the DefaultTableModel, which permits
 *  adding rows and columns programmatically.
 *
  */

public class DefaultTableExample extends JTable {
  
  private String[] columnNames = 
    { "Flag", "City", "Country", "Comment", "Visited" };

  public DefaultTableExample() {
    this(new DefaultTableModel());
  }
    
  public DefaultTableExample(DefaultTableModel model) {
    super(model);
    
    JavaLocationCollection collection =
      new JavaLocationCollection();
    JavaLocation[] locations = collection.getLocations();

    // Set up the column labels and data for the table model.
    int i;
    for(i=0; i<columnNames.length; i++ ) {
      model.addColumn(columnNames[i]); 
    }
    for(i=0; i<locations.length; i++) {
      model.addRow(getRowData(locations[i]));
    }
  }

  private Vector getRowData(JavaLocation location) {
    Vector vector = new Vector();
    vector.add(new ImageIcon(location.getFlagFile()));
    vector.add("Java");
    vector.add(location.getCountry());
    vector.add(location.getComment());
    vector.add(new Boolean(false));
    return(vector);
  }
  
  public static void main(String[] args) {
    WindowUtilities.setNativeLookAndFeel();    
    WindowUtilities.openInJFrame(
       new JScrollPane(new DefaultTableExample()), 600, 150, 
                       "Using a DefaultTableModel");
  }
}

# CustomTableExample.java An improved table that uses a CustomTableModel to correctly display cells containing images and boolean values. 
import javax.swing.*;
import javax.swing.table.*;

/** JTable that uses a CustomTableModel to correctly render
 *  the table cells that contain images and boolean values.
 *
*/

public class CustomTableExample extends DefaultTableExample {
  
  public CustomTableExample() {
    super(new CustomTableModel());
    setCellSizes();
  }
    
  private void setCellSizes() {
    setRowHeight(50);
    getColumn("Flag").setMaxWidth(55);
    getColumn("City").setPreferredWidth(60);
    getColumn("Country").setMinWidth(80);
    getColumn("Comment").setMinWidth(150);
    // Call to resize columns in viewport (bug).
    sizeColumnsToFit(JTable.AUTO_RESIZE_OFF);
  }
  
  public static void main(String[] args) {
    WindowUtilities.setNativeLookAndFeel();
    WindowUtilities.openInJFrame(
       new JScrollPane(new CustomTableExample()), 525, 255, 
                       "Using a CustomTableModel");
  }
}

    * CustomTableModel.java Returns the class type of a column (for use by the default cell renderers).

import javax.swing.table.*;

/** A custom DefaultTableModel that returns the class
 *  type for the default cell renderers to use. The user is 
 *  restricted to editing only the Comment and Visited columns.
 *
 */

public class CustomTableModel extends DefaultTableModel {
  
  public Class getColumnClass(int column) {
    return(getValueAt(0, column).getClass());
  }

  // Only permit edit of "Comment" and "Visited" columns.
  public boolean isCellEditable(int row, int column) {
    return(column==3 || column==4);
  }
}
**//
    * JavaLocationCollection.java A simple collection of JavaLocation (below) objects.
    * JavaLocation.java An object representing a city named Java. Defines the country where the Java city is located, along with a comment and country flag 
JTableEvents.java A table that reacts to the user entering data into a cell.
import java.awt.*;
import java.text.DecimalFormat;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;

/** A JTable that responds to TableModelEvents and
 *  updates other cells in the table, based on user input.
 *
  */

public class JTableEvents extends JFrame {
  private final int COL_COST     = 1;
  private final int COL_QTY      = 2;
  private final int COL_TOTAL    = 3;
  private final int ROW_LAST     = 5;
  private DecimalFormat df = new DecimalFormat("$####.##");
  private JTable sampleJTable;
  private DefaultTableModel tableModel;

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

  public JTableEvents() {
    super("Using TableEvents");
    WindowUtilities.setNativeLookAndFeel();
    addWindowListener(new ExitListener());
    Container content = getContentPane();

    String[] columnNames = { "Book", "Cost", "Qty", "Total" };

    final Object[][] data = {
      {"Core Web Programming", "$ 0.99", "0", "$0.00"},
      {"Core Servlets and JavaServer Pages",
                               "$34.39", "0", "$0.00"},
      {"Core Swing",           "$39.99", "0", "$0.00"},
      {"Core Java, Volume I",  "$31.49", "0", "$0.00"},
      {"Core Java, Volume II", "$34.39", "0", "$0.00"},
      {null, null,                  "Grand:", "$0.00"} };

    tableModel = new DefaultTableModel(data, columnNames);
    tableModel.addTableModelListener(
      new TableModelListener() {
        int row, col;
        int quantity;
        float cost, subTotal, grandTotal;
        public void tableChanged(TableModelEvent event) {
          row = event.getFirstRow();
          col = event.getColumn();
          // Only update table if a new book quantity entered.
          if (col == COL_QTY) {
            try {
              cost = getFormattedCellValue(row, COL_COST);
              quantity = (int)getFormattedCellValue(row, COL_QTY);
              subTotal = quantity * cost;

              // Update row total.
              tableModel.setValueAt(df.format(subTotal),
                                    row, COL_TOTAL);
              // Update grand total.
              grandTotal =0;
              for(int row=0; row<data.length-1; row++) {
                grandTotal += getFormattedCellValue(row, COL_TOTAL);
              }
              tableModel.setValueAt(df.format(grandTotal),
                                    ROW_LAST,COL_TOTAL);
              tableModel.fireTableDataChanged();
            } catch (NumberFormatException nfe) {
                // Send error message to user.
                JOptionPane.showMessageDialog(
                             JTableEvents.this,
                             "Illegal value entered!");
            }
          }
        }

        private float getFormattedCellValue(int row, int col) {
          String value = (String)tableModel.getValueAt(row, col);
          return(Float.parseFloat(value.replace('$',' ')));
        }
      });

    sampleJTable = new JTable(tableModel);
    setColumnAlignment(sampleJTable.getColumnModel());
    JScrollPane tablePane = new JScrollPane(sampleJTable);

    content.add(tablePane, BorderLayout.CENTER);
    setSize(460,150);
    setVisible(true);
  }

  // Right-align all but the first column.
  private void setColumnAlignment(TableColumnModel tcm) {
    TableColumn column;
    DefaultTableCellRenderer renderer =
      new DefaultTableCellRenderer();
    for(int i=1; i<tcm.getColumnCount(); i++) {
      column = tcm.getColumn(i);
      renderer.setHorizontalAlignment(SwingConstants.RIGHT);
      column.setCellRenderer(renderer);
    }
  }
}
**//

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10301
Categories:Programming Code Examples, Java/J2EE/J2ME, Advanced Swing
Tags:Java/J2EE/J2MEAdvanced Swing
Post Data:2017-01-02 16:04:31

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

JTree Examples #Programming Code Examples #Java/J2EE/J2ME #Advanced Swing

SimpleTree.java Basic tree built out of DefaultMutableTreeNodes. A DefualtMutableTreeNode is a starting point for a root node, in which children nodes can be added. 
import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;

/** Example tree built out of DefaultMutableTreeNodes. 
 *
 */

public class SimpleTree extends JFrame {
  public static void main(String[] args) {
    new SimpleTree();
  }
 
  public SimpleTree() {
    super("Creating a Simple JTree");
    WindowUtilities.setNativeLookAndFeel();
    addWindowListener(new ExitListener());
    Container content = getContentPane();
    Object[] hierarchy =
      { "javax.swing",
        "javax.swing.border",
        "javax.swing.colorchooser",
        "javax.swing.event",
        "javax.swing.filechooser",
        new Object[] { "javax.swing.plaf",
                       "javax.swing.plaf.basic",
                       "javax.swing.plaf.metal",
                       "javax.swing.plaf.multi" },
        "javax.swing.table",
        new Object[] { "javax.swing.text",
                       new Object[] { "javax.swing.text.html",
                                     "javax.swing.text.html.parser" },
                       "javax.swing.text.rtf" },
        "javax.swing.tree",
        "javax.swing.undo" };
    DefaultMutableTreeNode root = processHierarchy(hierarchy);
    JTree tree = new JTree(root);
    content.add(new JScrollPane(tree), BorderLayout.CENTER);
    setSize(275, 300);
    setVisible(true);
  }

  /** Small routine that will make a node out of the first entry
   *  in the array, then make nodes out of subsequent entries
   *  and make them child nodes of the first one. The process 
   *  is repeated recursively for entries that are arrays.
   */

  private DefaultMutableTreeNode processHierarchy(
                                           Object[] hierarchy) {
    DefaultMutableTreeNode node =
      new DefaultMutableTreeNode(hierarchy[0]);
    DefaultMutableTreeNode child;
    for(int i=1; i 0) {
      try {
        n = Integer.parseInt(args[0]);
      } catch(NumberFormatException nfe) {
        System.out.println(
          "Can't parse number; using default of " + n);
      }
   }
    new DynamicTree(n);
  }
 
  public DynamicTree(int n) {
    super("Creating a Dynamic JTree");
    WindowUtilities.setNativeLookAndFeel();
    addWindowListener(new ExitListener());
    Container content = getContentPane();
    JTree tree = new JTree(new OutlineNode(1, n));
    content.add(new JScrollPane(tree), BorderLayout.CENTER);
    setSize(300, 475);
    setVisible(true);
  }
}


    * OutlineNode.java A simple tree node that builds its children.
import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;

/** Simple TreeNode that builds children on the fly.
 *  The key idea is that getChildCount is always called before
 *  any actual children are requested. That way, getChildCount 
 *  builds the children if they don't already exist.
 *  

* In this case, it just builds an "outline" tree. I.e., * if the root is current node is "x", the children are * "x.0", "x.1", "x.2", and "x.3". *

* */ public class OutlineNode extends DefaultMutableTreeNode { private boolean areChildrenDefined = false; private int outlineNum; private int numChildren; public OutlineNode(int outlineNum, int numChildren) { this.outlineNum = outlineNum; this.numChildren = numChildren; } public boolean isLeaf() { return(false); } public int getChildCount() { if (!areChildrenDefined) { defineChildNodes(); } return(super.getChildCount()); } private void defineChildNodes() { // You must set the flag before defining children if you // use "add" for the new children. Otherwise, you get an // infinite recursive loop since add results in a call // to getChildCount. However, you could use "insert" in such // a case. areChildrenDefined = true; for(int i=0; i<numchildren ; i++) { add(new OutlineNode(i+1, numChildren)); } } public String toString() { TreeNode parent = getParent(); if (parent == null) { return(String.valueOf(outlineNum)); } else { return(parent.toString() + "." + outlineNum); } } } **// CustomIcons.java Demonstrates displaying custom icons for the nodes of a tree. import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.tree.*; /** JTree with missing or custom icons at the tree nodes. * */ public class CustomIcons extends JFrame { public static void main(String[] args) { new CustomIcons(); } private Icon customOpenIcon = new ImageIcon("images/Circle_1.gif"); private Icon customClosedIcon = new ImageIcon("images/Circle_2.gif"); private Icon customLeafIcon = new ImageIcon("images/Circle_3.gif"); public CustomIcons() { super("JTree Selections"); WindowUtilities.setNativeLookAndFeel(); addWindowListener(new ExitListener()); Container content = getContentPane(); content.setLayout(new FlowLayout()); DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root"); DefaultMutableTreeNode child; DefaultMutableTreeNode grandChild; for(int childIndex=1; childIndex<4; childIndex++) { child = new DefaultMutableTreeNode("Child " + childIndex); root.add(child); for(int grandChildIndex=1; grandChildIndex<4; grandChildIndex++) { grandChild = new DefaultMutableTreeNode("Grandchild " + childIndex + "." + grandChildIndex); child.add(grandChild); } } JTree tree1 = new JTree(root); tree1.expandRow(1); // Expand children to illustrate leaf icons. JScrollPane pane1 = new JScrollPane(tree1); pane1.setBorder( BorderFactory.createTitledBorder("Standard Icons")); content.add(pane1); JTree tree2 = new JTree(root); // Expand children to illustrate leaf icons. tree2.expandRow(2); DefaultTreeCellRenderer renderer2 = new DefaultTreeCellRenderer(); renderer2.setOpenIcon(null); renderer2.setClosedIcon(null); renderer2.setLeafIcon(null); tree2.setCellRenderer(renderer2); JScrollPane pane2 = new JScrollPane(tree2); pane2.setBorder( BorderFactory.createTitledBorder("No Icons")); content.add(pane2); JTree tree3 = new JTree(root); // Expand children to illustrate leaf icons. tree3.expandRow(3); DefaultTreeCellRenderer renderer3 = new DefaultTreeCellRenderer(); renderer3.setOpenIcon(customOpenIcon); renderer3.setClosedIcon(customClosedIcon); renderer3.setLeafIcon(customLeafIcon); tree3.setCellRenderer(renderer3); JScrollPane pane3 = new JScrollPane(tree3); pane3.setBorder( BorderFactory.createTitledBorder("Custom Icons")); content.add(pane3); pack(); setVisible(true); } } **//

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10300
Categories:Programming Code Examples, Java/J2EE/J2ME, Advanced Swing
Tags:Java/J2EE/J2MEAdvanced Swing
Post Data:2017-01-02 16:04:31

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

JList Examples #Programming Code Examples #Java/J2EE/J2ME #Advanced Swing

All examples, except for FileTransfer use WindowUtilities.java and ExitListener.java.
WindowUtilities.java: 
import javax.swing.*;
import java.awt.*;   // For Color and Container classes.

/** A few utilities that simplify using windows in Swing. 
 *
  */

public class WindowUtilities {

  /** Tell system to use native look and feel, as in previous
   *  releases. Metal (Java) LAF is the default otherwise.
   */

  public static void setNativeLookAndFeel() {
    try {
     UIManager.setLookAndFeel(
       UIManager.getSystemLookAndFeelClassName());
    } catch(Exception e) {
      System.out.println("Error setting native LAF: " + e);
    }
  }

  public static void setJavaLookAndFeel() {
    try {
     UIManager.setLookAndFeel(
       UIManager.getCrossPlatformLookAndFeelClassName());
    } catch(Exception e) {
      System.out.println("Error setting Java LAF: " + e);
    }
  }

   public static void setMotifLookAndFeel() {
    try {
      UIManager.setLookAndFeel(
        "com.sun.java.swing.plaf.motif.MotifLookAndFeel");
    } catch(Exception e) {
      System.out.println("Error setting Motif LAF: " + e);
    }
  }

  /** A simplified way to see a JPanel or other Container. Pops
   *  up a JFrame with specified Container as the content pane.
   */

  public static JFrame openInJFrame(Container content,
                                    int width,
                                    int height,
                                    String title,
                                    Color bgColor) {
    JFrame frame = new JFrame(title);
    frame.setBackground(bgColor);
    content.setBackground(bgColor);
    frame.setSize(width, height);
    frame.setContentPane(content);
    frame.addWindowListener(new ExitListener());
    frame.setVisible(true);
    return(frame);
  }

  /** Uses Color.white as the background color. */

  public static JFrame openInJFrame(Container content,
                                    int width,
                                    int height,
                                    String title) {
    return(openInJFrame(content, width, height,
                        title, Color.white));
  }

  /** Uses Color.white as the background color, and the
   *  name of the Container's class as the JFrame title.
   */

  public static JFrame openInJFrame(Container content,
                                    int width,
                                    int height) {
    return(openInJFrame(content, width, height,
                        content.getClass().getName(),
                        Color.white));
  }
}
**//
ExitListener.java.:
import java.awt.*;
import java.awt.event.*;

/** A listener that you attach to the top-level JFrame of
 *  your application, so that quitting the frame exits the 
 *  application.
 *
  */
public class ExitListener extends WindowAdapter {
  public void windowClosing(WindowEvent event) {
    System.exit(0);
  }
}
**//
JList Examples

    * JListSimpleExample.java Illustrates creating a simple list. In this example, all the entries for the list are stored in a String array and later supplied in the JList constructor. In addition, a private class, ValueReporter, implements a ListSelectionListener to display the last entry in the list selected by the user. 
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;

/** Simple JList example illustrating
 *  
    *
  • Creating a JList, which we do by passing values * directly to the JList constructor, rather than * using a ListModel, and *
  • Attaching a listener to determine when values change. *
*/ public class JListSimpleExample extends JFrame { public static void main(String[] args) { new JListSimpleExample(); } private JList sampleJList; private JTextField valueField; public JListSimpleExample() { super("Creating a Simple JList"); WindowUtilities.setNativeLookAndFeel(); addWindowListener(new ExitListener()); Container content = getContentPane(); // Create the JList, set the number of visible rows, add a // listener, and put it in a JScrollPane. String[] entries = { "Entry 1", "Entry 2", "Entry 3", "Entry 4", "Entry 5", "Entry 6" }; sampleJList = new JList(entries); sampleJList.setVisibleRowCount(4); sampleJList.addListSelectionListener(new ValueReporter()); JScrollPane listPane = new JScrollPane(sampleJList); Font displayFont = new Font("Serif", Font.BOLD, 18); sampleJList.setFont(displayFont); JPanel listPanel = new JPanel(); listPanel.setBackground(Color.white); Border listPanelBorder = BorderFactory.createTitledBorder("Sample JList"); listPanel.setBorder(listPanelBorder); listPanel.add(listPane); content.add(listPanel, BorderLayout.CENTER); JLabel valueLabel = new JLabel("Last Selection:"); valueLabel.setFont(displayFont); valueField = new JTextField("None", 7); valueField.setFont(displayFont); valueField.setEditable(false); JPanel valuePanel = new JPanel(); valuePanel.setBackground(Color.white); Border valuePanelBorder = BorderFactory.createTitledBorder("JList Selection"); valuePanel.setBorder(valuePanelBorder); valuePanel.add(valueLabel); valuePanel.add(valueField); content.add(valuePanel, BorderLayout.SOUTH); pack(); setVisible(true); } private class ValueReporter implements ListSelectionListener { /** You get three events in many cases -- one for the * deselection of the originally selected entry, one * indicating the selection is moving, and one for the * selection of the new entry. In the first two cases, * getValueIsAdjusting returns true; thus, the test below * when only the third case is of interest. */ public void valueChanged(ListSelectionEvent event) { if (!event.getValueIsAdjusting()) { Object value = sampleJList.getSelectedValue(); if (value != null) { valueField.setText(value.toString()); } } } } } **// DefaultListModelExample.java Creates a list using a DefaultListModel. By default, a JList doesn't permit you to directly add new entries; however, with the DefaultListModel you can add or delete entries to the model (which are reflected in the list). import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; /** JList example illustrating *
    *
  • The creation of a JList by creating a DefaultListModel, * adding the values there, then passing that to the * JList constructor. *
  • Adding new values at runtime, the key thing that * DefaultListModel lets you do that you can't do with * a JList where you supply values directly. *
* */ public class DefaultListModelExample extends JFrame { public static void main(String[] args) { new DefaultListModelExample(); } JList sampleJList; private DefaultListModel sampleModel; public DefaultListModelExample() { super("Creating a Simple JList"); WindowUtilities.setNativeLookAndFeel(); addWindowListener(new ExitListener()); Container content = getContentPane(); String[] entries = { "Entry 1", "Entry 2", "Entry 3", "Entry 4", "Entry 5", "Entry 6" }; sampleModel = new DefaultListModel(); for(int i=0; i<entries .length; i++) { sampleModel.addElement(entries[i]); } sampleJList = new JList(sampleModel); sampleJList.setVisibleRowCount(4); Font displayFont = new Font("Serif", Font.BOLD, 18); sampleJList.setFont(displayFont); JScrollPane listPane = new JScrollPane(sampleJList); JPanel listPanel = new JPanel(); listPanel.setBackground(Color.white); Border listPanelBorder = BorderFactory.createTitledBorder("Sample JList"); listPanel.setBorder(listPanelBorder); listPanel.add(listPane); content.add(listPanel, BorderLayout.CENTER); JButton addButton = new JButton("Add Entry to Bottom of JList"); addButton.setFont(displayFont); addButton.addActionListener(new ItemAdder()); JPanel buttonPanel = new JPanel(); buttonPanel.setBackground(Color.white); Border buttonPanelBorder = BorderFactory.createTitledBorder("Adding Entries"); buttonPanel.setBorder(buttonPanelBorder); buttonPanel.add(addButton); content.add(buttonPanel, BorderLayout.SOUTH); pack(); setVisible(true); } private class ItemAdder implements ActionListener { /** Add an entry to the ListModel whenever the user * presses the button. Note that since the new entries * may be wider than the old ones (e.g., "Entry 10" vs. * "Entry 9"), you need to rerun the layout manager. * You need to do this before trying to scroll * to make the index visible. */ public void actionPerformed(ActionEvent event) { int index = sampleModel.getSize(); sampleModel.addElement("Entry " + (index+1)); ((JComponent)getContentPane()).revalidate(); sampleJList.setSelectedIndex(index); sampleJList.ensureIndexIsVisible(index); } } } **// # JListCustomModel.java Example illustrating that you can use your own custom data model (data structure) to hold the entries in a list. Uses the following classes: * JavaLocationListModel.java A custom list model (implements ListModel interface which provides support for custom data structures) to store data for the list. * JavaLocationCollection.java A simple collection of JavaLocation (below) objects. * JavaLocation.java An object representing a city named Java. Defines the country where the Java city is located, along with a comment and country flag (gif image). JListCustomModel.java: import java.awt.*; import javax.swing.*; /** Simple JList example illustrating the use of a custom * ListModel (JavaLocationListModel). * */ public class JListCustomModel extends JFrame { public static void main(String[] args) { new JListCustomModel(); } public JListCustomModel() { super("JList with a Custom Data Model"); WindowUtilities.setNativeLookAndFeel(); addWindowListener(new ExitListener()); Container content = getContentPane(); JavaLocationCollection collection = new JavaLocationCollection(); JavaLocationListModel listModel = new JavaLocationListModel(collection); JList sampleJList = new JList(listModel); Font displayFont = new Font("Serif", Font.BOLD, 18); sampleJList.setFont(displayFont); content.add(sampleJList); pack(); setVisible(true); } } **// # JavaLocationListModel.java: import javax.swing.*; import javax.swing.event.*; /** A simple illustration of writing your own ListModel. * Note that if you wanted the user to be able to add and * remove data elements at runtime, you should start with * AbstractListModel and handle the event reporting part. * */ public class JavaLocationListModel implements ListModel { private JavaLocationCollection collection; public JavaLocationListModel(JavaLocationCollection collection) { this.collection = collection; } public Object getElementAt(int index) { return(collection.getLocations()[index]); } public int getSize() { return(collection.getLocations().length); } public void addListDataListener(ListDataListener l) {} public void removeListDataListener(ListDataListener l) {} } **// JavaLocationCollection.java: /** A simple collection that stores multiple JavaLocation * objects in an array and determines the number of * unique countries represented in the data. * */ public class JavaLocationCollection { private static JavaLocation[] defaultLocations = { new JavaLocation("Belgium", "near Liege", "flags/belgium.gif"), new JavaLocation("Brazil", "near Salvador", "flags/brazil.gif"), new JavaLocation("Colombia", "near Bogota", "flags/colombia.gif"), new JavaLocation("Indonesia", "main island", "flags/indonesia.gif"), new JavaLocation("Jamaica", "near Spanish Town", "flags/jamaica.gif"), new JavaLocation("Mozambique", "near Sofala", "flags/mozambique.gif"), new JavaLocation("Philippines", "near Quezon City", "flags/philippines.gif"), new JavaLocation("Sao Tome", "near Santa Cruz", "flags/saotome.gif"), new JavaLocation("Spain", "near Viana de Bolo", "flags/spain.gif"), new JavaLocation("Suriname", "near Paramibo", "flags/suriname.gif"), new JavaLocation("United States", "near Montgomery, Alabama", "flags/usa.gif"), new JavaLocation("United States", "near Needles, California", "flags/usa.gif"), new JavaLocation("United States", "near Dallas, Texas", "flags/usa.gif") }; private JavaLocation[] locations; private int numCountries; public JavaLocationCollection(JavaLocation[] locations) { this.locations = locations; this.numCountries = countCountries(locations); } public JavaLocationCollection() { this(defaultLocations); } public JavaLocation[] getLocations() { return(locations); } public int getNumCountries() { return(numCountries); } // Count the number of unique countries in the data. // Assumes the list is sorted by country name private int countCountries(JavaLocation[] locations) { int n = 0; String currentCountry, previousCountry = "None"; for(int i=0;i<locations .length;i++) { currentCountry = locations[i].getCountry(); if (!previousCountry.equals(currentCountry)) { n++; } currentCountry = previousCountry; } return(n); } } **// JavaLocation.java : /** Simple data structure with three properties: country, * comment, and flagFile. All are strings, and they are * intended to represent a country that has a city or * province named "Java," a comment about a more * specific location within the country, and a path * specifying an image file containing the country's flag. * Used in examples illustrating custom models and cell * renderers for JLists. * */ public class JavaLocation { private String country, comment, flagFile; public JavaLocation(String country, String comment, String flagFile) { setCountry(country); setComment(comment); setFlagFile(flagFile); } /** String representation used in printouts and in JLists */ public String toString() { return("Java, " + getCountry() + " (" + getComment() + ")."); } /** Return country containing city or province named "Java." */ public String getCountry() { return(country); } /** Specify country containing city or province named "Java." */ public void setCountry(String country) { this.country = country; } /** Return comment about city or province named "Java." * Usually of the form "near such and such a city." */ public String getComment() { return(comment); } /** Specify comment about city or province named "Java". */ public void setComment(String comment) { this.comment = comment; } /** Return path to image file of country flag. */ public String getFlagFile() { return(flagFile); } /** Specify path to image file of country flag. */ public void setFlagFile(String flagFile) { this.flagFile = flagFile; } } **// JListCustomRenderer.java A list can contain items other than Strings; however, the list needs to know how to render (display) the different items. In this example, a custom cell renderer is used to display each JavaLocation as a JLabel containing an Icon (for the flag) and text (country and description). Uses the following classes and images: import java.awt.*; import javax.swing.*; /** Simple JList example illustrating the use of a custom * cell renderer (JavaLocationRenderer). * */ public class JListCustomRenderer extends JFrame { public static void main(String[] args) { new JListCustomRenderer(); } public JListCustomRenderer() { super("JList with a Custom Cell Renderer"); WindowUtilities.setNativeLookAndFeel(); addWindowListener(new ExitListener()); Container content = getContentPane(); JavaLocationCollection collection = new JavaLocationCollection(); JavaLocationListModel listModel = new JavaLocationListModel(collection); JList sampleJList = new JList(listModel); sampleJList.setCellRenderer(new JavaLocationRenderer()); Font displayFont = new Font("Serif", Font.BOLD, 18); sampleJList.setFont(displayFont); content.add(sampleJList); pack(); setVisible(true); } } **// # JavaLocationRenderer.java Simple custom renderer that builds the JLabel for each item to display in the list. import javax.swing.*; import java.awt.*; import java.util.*; /** Simple custom cell renderer. The idea here is to augment * the default renderer instead of building one from scratch. * The advantage of this approach is that you don't have to * handle the highlighting of the selected entries yourself, * plus values that aren't of the new type you want to draw can * be handled automatically. The disadvantage is that you are * limited to a variation of a JLabel, which is what the default * renderer returns. *

* Note that this method can get called lots and lots of times * as you click on entries. We don't want to keep generating * new ImageIcon objects, so we make a Hashtable that associates * previously displayed values with icons, reusing icons for * entries that have been displayed already. *

* Note that in the first release of JDK 1.2, the default * renderer has a bug: the renderer doesn't clear out icons for * later entries. So if you mix plain strings and ImageIcons in * your JList, the plain strings still get an icon. The * call below clears the old icon when the value is not a * JavaLocation. * */ public class JavaLocationRenderer extends DefaultListCellRenderer { private Hashtable iconTable = new Hashtable(); public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean hasFocus) { // First build the label containing the text, then // later add the image. JLabel label = (JLabel)super.getListCellRendererComponent(list, value, index, isSelected, hasFocus); if (value instanceof JavaLocation) { JavaLocation location = (JavaLocation)value; ImageIcon icon = (ImageIcon)iconTable.get(value); if (icon == null) { icon = new ImageIcon(location.getFlagFile()); iconTable.put(value, icon); } label.setIcon(icon); } else { // Clear old icon; needed in 1st release of JDK 1.2. label.setIcon(null); } return(label); } } **// # JavaLocationListModel.java A custom list model (implements ListModel interface) to store data for a list. # JavaLocationCollection.java A simple collection of JavaLocation (below) objects. # JavaLocation.java An object representing a city named Java. Defines the country where the Java city is located, along with a comment and country flag

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10299
Categories:Programming Code Examples, Java/J2EE/J2ME, Advanced Swing
Tags:Java/J2EE/J2MEAdvanced Swing
Post Data:2017-01-02 16:04:31

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

ThreadedRSAKey.java Illustrates converting a method in an existing class from a single-threaded method to a multi-threaded method. #Programming Code Examples #Java/J2EE/J2ME #Advanced Swing

ThreadedRSAKey.java  Illustrates converting a method in an existing class from a single-threaded method to a multi-threaded method. In this example, RSAKey  computes an RSA public-private key pair, where the key size has a specified number of digits. As large prime numbers require considerable CPU time, ThreadedRSAKey converts the original computeKey method in RSAKey  to a multi-threaded method, thus allowing simultaneous (multithreaded) computation of multiple key pairs. Uses the following classes:
import java.io.*;   

 * RSAKey.java Computes RSA public-private key pairs of arbitrary length.


 * Primes.java Generates large prime numbers.


/** An example of creating a background process for an
 *  originally nonthreaded, class method. Normally,
 *  the program flow will wait until computeKey is finished.
 
public class ThreadedRSAKey extends RSAKey implements Runnable {

  // Store strNumDigits into the thread to prevent race
  // conditions.
  public void computeKey(String strNumDigits) {
    RSAThread t = new RSAThread(this, strNumDigits);
    t.start();
  }

  // Retrieve the stored strNumDigits and call the original
  // method.  Processing is now done in the background.
  public void run() {
    RSAThread t = (RSAThread)Thread.currentThread();
    String strNumDigits = t.getStrDigits();
    super.computeKey(strNumDigits);
  }

  public static void main(String[] args){
    ThreadedRSAKey key = new ThreadedRSAKey();
    for (int i=0; i " + n);
    System.out.println("public  => " + encrypt);
    System.out.println("private => " + decrypt);
  }
}


 * Primes.java Generates large prime numbers.
***

import java.math.BigInteger;

/** A few utilities to generate a large random BigInteger,
 *  and find the next prime number above a given BigInteger.
 
public class Primes {
  // Note that BigInteger.ZERO was new in JDK 1.2, and 1.1
  // code is being used to support the most servlet engines.
  private static final BigInteger ZERO = new BigInteger("0");
  private static final BigInteger ONE = new BigInteger("1");
  private static final BigInteger TWO = new BigInteger("2");
  
  // Likelihood of false prime is less than 1/2^ERR_VAL
  // Assumedly BigInteger uses the Miller-Rabin test or
  // equivalent, and thus is NOT fooled by Carmichael numbers.
  // See section 33.8 of Cormen et al. Introduction to
  // Algorithms for details.
  private static final int ERR_VAL = 100;
  
  public static BigInteger nextPrime(BigInteger start) {
    if (isEven(start))
      start = start.add(ONE);
    else
      start = start.add(TWO);
    if (start.isProbablePrime(ERR_VAL))
      return(start);
    else
      return(nextPrime(start));
  }

  private static boolean isEven(BigInteger n) {
    return(n.mod(TWO).equals(ZERO));
  }

  private static StringBuffer[] digits =
    { new StringBuffer("0"), new StringBuffer("1"),
      new StringBuffer("2"), new StringBuffer("3"),
      new StringBuffer("4"), new StringBuffer("5"),
      new StringBuffer("6"), new StringBuffer("7"),
      new StringBuffer("8"), new StringBuffer("9") };

  private static StringBuffer randomDigit() {
    int index = (int)Math.floor(Math.random() * 10);
    return(digits[index]);
  }
  
  public static BigInteger random(int numDigits) {
    StringBuffer s = new StringBuffer("");
    for(int i=0; i 0)
      numDigits = Integer.parseInt(args[0]);
    else
      numDigits = 150;
    BigInteger start = random(numDigits);
    for(int i=0; i<50; i++) {
      start = nextPrime(start);
      System.out.println("Prime " + i + " = " + start);
    }
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10296
Categories:Programming Code Examples, Java/J2EE/J2ME, Advanced Swing
Tags:Java/J2EE/J2MEAdvanced Swing
Post Data:2017-01-02 16:04:31

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

Buggy Counter Applet.java Demonstrates that data shared by multiple threads is candidate for a potential race condition #Programming Code Examples #Java/J2EE/J2ME #Advanced Swing

import java.applet.Applet;
import java.awt.*;

/** Emulates the Counter and Counter2 classes, but this time
 *  from an applet that invokes multiple versions of its own run
 *  method. This version is likely to work correctly
 *  except when  an important customer is visiting.

public class BuggyCounterApplet extends Applet
                                implements Runnable{
  private int totalNum = 0;
  private int loopLimit = 5;

  // Start method of applet, not the start method of the thread. 
  // The applet start method is called by the browser after init is
  // called. 
  public void start() {
    Thread t;
    for(int i=0; i<3; i++) {
      t = new Thread(this);
      t.start();
    }
  }

  private void pause(double seconds) {
    try { Thread.sleep(Math.round(1000.0*seconds)); }
    catch(InterruptedException ie) {}
  }

  public void run() {
    int currentNum = totalNum;
    System.out.println("Setting currentNum to " + currentNum);
    totalNum = totalNum + 1;
    for(int i=0; i<looplimit ; i++) {
      System.out.println("Counter " + currentNum + ": " + i);
      pause(Math.random());
    }
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10295
Categories:Programming Code Examples, Java/J2EE/J2ME, Advanced Swing
Tags:Java/J2EE/J2MEAdvanced Swing
Post Data:2017-01-02 16:04:31

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

Driver class that creates three threaded objects (Counter2) that count from 0 to 4. #Programming Code Examples #Java/J2EE/J2ME #Advanced Swing

/** Try out a few instances of the Counter2 class. 

public class Counter2Test {
  public static void main(String[] args) {
    Counter2 c1 = new Counter2(5);
    Counter2 c2 = new Counter2(5);
    Counter2 c3 = new Counter2(5);
  }
}

/** A Runnable that counts up to a specified
 *  limit with random pauses in between each count.
 
public class Counter2 implements Runnable {
  private static int totalNum = 0;
  private int currentNum, loopLimit;

  public Counter2(int loopLimit) {
    this.loopLimit = loopLimit;
    currentNum = totalNum++;
    Thread t = new Thread(this);
    t.start();
  }

  private void pause(double seconds) {
    try { Thread.sleep(Math.round(1000.0*seconds)); }
    catch(InterruptedException ie) {}
  }
  
  public void run() {
    for(int i=0; i<looplimit ; i++) {
      System.out.println("Counter " + currentNum + ": " + i);
      pause(Math.random()); // Sleep for up to 1 second.
    }
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10294
Categories:Programming Code Examples, Java/J2EE/J2ME, Advanced Swing
Tags:Java/J2EE/J2MEAdvanced Swing
Post Data:2017-01-02 16:04:31

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

Counter2Test.java Driver class that creates three threaded objects (Counter2) that count from 0 to 4. #Programming Code Examples #Java/J2EE/J2ME #Advanced Swing

/** Try out a few instances of the Counter2 class. 

Driver class that creates three threaded objects (Counter2) that count from 0 to 4. In this case, the driver does not start the threads, as each thread is automatically started in Counter2's constructor. Uses the following class:
Counter2Test.java
Counter2.java
**************************    
public class Counter2Test {
  public static void main(String[] args) {
    Counter2 c1 = new Counter2(5);
    Counter2 c2 = new Counter2(5);
    Counter2 c3 = new Counter2(5);
  }
}

* Counter2.java A Runnable  that counts to a specified value and sleeps a random number of seconds in between counts. Here, the thread is started automatically when the object is instantiated.
/** A Runnable that counts up to a specified
 *  limit with random pauses in between each count.
 
public class Counter2 implements Runnable {
  private static int totalNum = 0;
  private int currentNum, loopLimit;

  public Counter2(int loopLimit) {
    this.loopLimit = loopLimit;
    currentNum = totalNum++;
    Thread t = new Thread(this);
    t.start();
  }

  private void pause(double seconds) {
    try { Thread.sleep(Math.round(1000.0*seconds)); }
    catch(InterruptedException ie) {}
  }
  
  public void run() {
    for(int i=0; i<looplimit ; i++) {
      System.out.println("Counter " + currentNum + ": " + i);
      pause(Math.random()); // Sleep for up to 1 second.
    }
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10293
Categories:Programming Code Examples, Java/J2EE/J2ME, Advanced Swing
Tags:Java/J2EE/J2MEAdvanced Swing
Post Data:2017-01-02 16:04:31

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

Template illustrating the second approach for creating a class with thread behavior. #Programming Code Examples #Java/J2EE/J2ME #Advanced Swing

Template illustrating the second approach for creating a class with thread behavior. In this case, the class implements the Runnable interface while providing a run method for thread execution. 
public class ThreadedClass extends AnyClass implements Runnable {
  public void run() {
    // Thread behavior here.
  }

  public void startThread() {
    Thread t = new Thread(this);
    t.start(); // Calls back to the run method in "this."
  }

  ...
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10292
Categories:Programming Code Examples, Java/J2EE/J2ME, Advanced Swing
Tags:Java/J2EE/J2MEAdvanced Swing
Post Data:2017-01-02 16:04:31

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

Creates and starts three threaded objects #Programming Code Examples #Java/J2EE/J2ME #Advanced Swing

Creates and starts three threaded objects which count from 0 to 4. Uses the following class:
CounterTest.java
Counter.java
/** Try out a few instances of the Counter class. 
 public class CounterTest {
  public static void main(String[] args) {
    Counter c1 = new Counter(5);
    Counter c2 = new Counter(5);
    Counter c3 = new Counter(5);
    c1.start();
    c2.start();
    c3.start();
  }
}

Counter.java:A class that inherits from Thread and defines a run method that counts up to a specified value, pausing for a random time interval in between value counts.
/** A subclass of Thread that counts up to a specified
 *  limit with random pauses in between each count.
 
public class Counter extends Thread {
  private static int totalNum = 0;
  private int currentNum, loopLimit;

  public Counter(int loopLimit) {
    this.loopLimit = loopLimit;
    currentNum = totalNum++;
  }

  private void pause(double seconds) {
    try { Thread.sleep(Math.round(1000.0*seconds)); }
    catch(InterruptedException ie) {}
  }

  /** When run finishes, the thread exits. */
  
  public void run() {
    for(int i=0; i<looplimit ; i++) {
      System.out.println("Counter " + currentNum + ": " + i);
      pause(Math.random()); // Sleep for up to 1 second
    }
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10291
Categories:Programming Code Examples, Java/J2EE/J2ME, Advanced Swing
Tags:Java/J2EE/J2MEAdvanced Swing
Post Data:2017-01-02 16:04:31

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

Template illustrating the first approach for creating a class with thread behavior. #Programming Code Examples #Java/J2EE/J2ME #Advanced Swing

/** Taken from Core Web Programming from 
 *  Prentice Hall and Sun Microsystems Press,
  *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class ThreadClass extends Thread {
 public void run() {
   // Thread behavior here.
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10290
Categories:Programming Code Examples, Java/J2EE/J2ME, Advanced Swing
Tags:Java/J2EE/J2MEAdvanced Swing
Post Data:2017-01-02 16:04:31

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada