*
o PrintExample.java Demonstrates printing a Graphics2D object.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.print.*;
/** An example of a printable window in Java 1.2. The key point
* here is that any component is printable in Java 1.2.
* However, you have to be careful to turn off double buffering
* globally (not just for the top-level window).
* See the PrintUtilities class for the printComponent method
* that lets you print an arbitrary component with a single
* function call.
*
*/
public class PrintExample extends JFrame
implements ActionListener {
public static void main(String[] args) {
new PrintExample();
}
public PrintExample() {
super("Printing Swing Components in JDK 1.2");
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
Container content = getContentPane();
JButton printButton = new JButton("Print");
printButton.addActionListener(this);
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground(Color.white);
buttonPanel.add(printButton);
content.add(buttonPanel, BorderLayout.SOUTH);
DrawingPanel drawingPanel = new DrawingPanel();
content.add(drawingPanel, BorderLayout.CENTER);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent event) {
PrintUtilities.printComponent(this);
}
}
Uses the following classes:
+ PrintUtilities.java Simple utility class to support printing graphical windows in JDK 1.2.
import java.awt.*;
import javax.swing.*;
import java.awt.print.*;
/** A simple utility class that lets you very simply print
* an arbitrary component in JDK 1.2. Just pass the
* component to PrintUtilities.printComponent. The
* component you want to print doesn't need a print method
* and doesn't have to implement any interface or do
* anything special at all.
*
* If you are going to be printing many times, it is marginally
* more efficient to first do the following:
*
* PrintUtilities printHelper =
* new PrintUtilities(theComponent);
*
* then later do printHelper.print(). But this is a very tiny
* difference, so in most cases just do the simpler
* PrintUtilities.printComponent(componentToBePrinted).
*
*/
public class PrintUtilities implements Printable {
protected Component componentToBePrinted;
public static void printComponent(Component c) {
new PrintUtilities(c).print();
}
public PrintUtilities(Component componentToBePrinted) {
this.componentToBePrinted = componentToBePrinted;
}
public void print() {
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintable(this);
if (printJob.printDialog())
try {
printJob.print();
} catch(PrinterException pe) {
System.out.println("Error printing: " + pe);
}
}
// General print routine for JDK 1.2. Use PrintUtilities2
// for printing in JDK 1.3.
public int print(Graphics g, PageFormat pageFormat,
int pageIndex) {
if (pageIndex > 0) {
return(NO_SUCH_PAGE);
} else {
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pageFormat.getImageableX(),
pageFormat.getImageableY());
disableDoubleBuffering(componentToBePrinted);
componentToBePrinted.paint(g2d);
enableDoubleBuffering(componentToBePrinted);
return(PAGE_EXISTS);
}
}
/** The speed and quality of printing suffers dramatically if
* any of the containers have double buffering turned on,
* so this turns it off globally. This step is only
* required in JDK 1.2.
*/
public static void disableDoubleBuffering(Component c) {
RepaintManager currentManager =
RepaintManager.currentManager(c);
currentManager.setDoubleBufferingEnabled(false);
}
/** Reenables double buffering globally. This step is only
* required in JDK 1.2.
*/
public static void enableDoubleBuffering(Component c) {
RepaintManager currentManager =
RepaintManager.currentManager(c);
currentManager.setDoubleBufferingEnabled(true);
}
}
//
+ DrawingPanel.java A basic JPanel containing a Java 2D drawing.
import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
/** A window with a custom paintComponent method.
* Illustrates that you can make a general-purpose method
* that can print any component, regardless of whether
* that component performs custom drawing.
* See the PrintUtilities class for the printComponent method
* that lets you print an arbitrary component with a single
* function call.
*
*/
public class DrawingPanel extends JPanel {
private int fontSize = 90;
private String message = "Java 2D";
private int messageWidth;
public DrawingPanel() {
setBackground(Color.white);
Font font = new Font("Serif", Font.PLAIN, fontSize);
setFont(font);
FontMetrics metrics = getFontMetrics(font);
messageWidth = metrics.stringWidth(message);
int width = messageWidth*5/3;
int height = fontSize*3;
setPreferredSize(new Dimension(width, height));
}
/** Draws a black string with a tall angled "shadow"
* of the string behind it.
*/
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
int x = messageWidth/10;
int y = fontSize*5/2;
g2d.translate(x, y);
g2d.setPaint(Color.lightGray);
AffineTransform origTransform = g2d.getTransform();
g2d.shear(-0.95, 0);
g2d.scale(1, 3);
g2d.drawString(message, 0, 0);
g2d.setTransform(origTransform);
g2d.setPaint(Color.black);
g2d.drawString(message, 0, 0);
}
}
o PrintUtilities2.java Simple utility class to support printing graphical windows in JDK 1.3 and later. Inherits from PrintUtilities.java.
import java.awt.*;
import javax.swing.*;
import java.awt.print.*;
/** A simple utility class for printing an arbitrary
* component in JDK 1.3. The class relies on the
* fact that in JDK 1.3 the JComponent class overrides
* print (in Container) to automatically set a flag
* that disables double buffering before the component
* is painted. If the printing flag is set, paint calls
* printComponent, printBorder, and printChildren.
*
* To print a component, just pass the component to
* PrintUtilities2.printComponent(componentToBePrinted).
*
*/
public class PrintUtilities2 extends PrintUtilities {
public static void printComponent(Component c) {
new PrintUtilities2(c).print();
}
public PrintUtilities2(Component componentToBePrinted) {
super(componentToBePrinted);
}
// General print routine for JDK 1.3. Use PrintUtilities1
// for printing in JDK 1.2.
public int print(Graphics g, PageFormat pageFormat,
int pageIndex) {
if (pageIndex > 0) {
return(NO_SUCH_PAGE);
} else {
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pageFormat.getImageableX(),
pageFormat.getImageableY());
componentToBePrinted.print(g2d);
return(PAGE_EXISTS);
}
}
}
* FileTransfer.java Demonstrates the proper technique for updating Swing components in a multithreaded program.
/**
// Final version of FileTransfer. Modification of the
// label is thread safe.
public class FileTransfer extends Thread {
private String filename;
private JLabel label;
public FileTransfer(String filename, JLabel label) {
this.filename = filename;
this.label = label;
}
public void run() {
try {
// Place the runnable object to update the label
// on the event queue. The invokeAndWait method
// will block until the label is updated.
SwingUtilities.invokeAndWait(
new Runnable() {
public void run() {
label.setText("Transferring " + filename);
}
});
} catch(InvocationTargetException ite) {
} catch(InterruptedException ie) { }
// Transfer file to server. Lengthy process.
doTransfer(...);
// Perform the final update to the label from
// within the runnable object. Use invokeLater;
// blocking is not necessary.
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
label.setText("Transfer completed");
}
});
}
}
* WindowUtilities.java Utility class that simplifies creating a window and setting the look and feel.
* ExitListener.java A WindowListener with support to close the window.
Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10302
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
May 13
Printing in Java 2 #Programming Code Examples #Java/J2EE/J2ME #Advanced Swing
May 13
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
May 13
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
May 13
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. *
-
*
- 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. *
* 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
May 13
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
May 13
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
May 13
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
May 13
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
May 13
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
May 13
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
