BetterCircleTest.java #Programming Code Examples #Java/J2EE/J2ME #Advanced Swing

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

/** Position circles down the diagonal so that their borders
 *  just touch. Illustrates that Java 1.1 lightweight 
 *  components can be partially transparent.
 *
  */

public class BetterCircleTest extends Applet {
  public void init() {
    setBackground(Color.lightGray);
    setLayout(null);
    BetterCircle circle;
    int radius = getSize().width/6;
    int deltaX = round(2.0 * (double)radius / Math.sqrt(2.0));
    for (int x=radius; x<6*radius; x=x+deltaX) {
      circle = new BetterCircle(Color.black, radius);
      add(circle);
      circle.setCenter(x, x);
    }
  }

  private int round(double num) {
    return((int)Math.round(num));
  }
}
********************************
BetterCircle.java
********************************
import java.awt.*;

/** An improved variation of the Circle class that uses Java 1.1
 *  lightweight components instead of Canvas.
 *
  */

public class BetterCircle extends Component {
  private Dimension preferredDimension;
  private int width, height;
  
  public BetterCircle(Color foreground, int radius) {
    setForeground(foreground);
    width = 2*radius;
    height = 2*radius;
    preferredDimension = new Dimension(width, height);
    setSize(preferredDimension);
  }

  public void paint(Graphics g) {
    g.setColor(getForeground());
    g.fillOval(0, 0, width, height);
  }

  public void setCenter(int x, int y) {
    setLocation(x - width/2, y - height/2);
  }

  /** Report the original size as the preferred size.
   *  That way, the BetterCircle doesn't get
   *  shrunk by layout managers.
   */
  
  public Dimension getPreferredSize() {
    return(preferredDimension);
  }

  /** Report same thing for minimum size as
   *  preferred size.
   */
  
  public Dimension getMinimumSize() {
    return(preferredDimension);
  }
}
*******************************

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10322
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

Implementation of a simple browser in Swing (The user can specify a URL to load into the browser (JEditorPane)) #Programming Code Examples #Java/J2EE/J2ME #Advanced Swing

Browser.java Implementation of a simple browser in Swing. The user can specify a URL to load into the browser (JEditorPane). By attaching an Hyperlink Listener, the editor pane is responsive to hyperlinks selected by the user. Uses the following class and image:
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;

/** Very simplistic "Web browser" using Swing. Supply a URL on
 *  the command line to see it initially and to set the
 *  destination of the "home" button.
 *
  */

public class Browser extends JFrame implements HyperlinkListener, 
                                               ActionListener {
  public static void main(String[] args) {
    if (args.length == 0)
      new Browser("http://www.corewebprogramming.com/");
    else
      new Browser(args[0]);
  }

  private JIconButton homeButton;
  private JTextField urlField;
  private JEditorPane htmlPane;
  private String initialURL;

  public Browser(String initialURL) {
    super("Simple Swing Browser");
    this.initialURL = initialURL;
    addWindowListener(new ExitListener());
    WindowUtilities.setNativeLookAndFeel();

    JPanel topPanel = new JPanel();
    topPanel.setBackground(Color.lightGray);
    homeButton = new JIconButton("home.gif");
    homeButton.addActionListener(this);
    JLabel urlLabel = new JLabel("URL:");
    urlField = new JTextField(30);
    urlField.setText(initialURL);
    urlField.addActionListener(this);
    topPanel.add(homeButton);
    topPanel.add(urlLabel);
    topPanel.add(urlField);
    getContentPane().add(topPanel, BorderLayout.NORTH);

    try {
        htmlPane = new JEditorPane(initialURL);
        htmlPane.setEditable(false);
        htmlPane.addHyperlinkListener(this);
        JScrollPane scrollPane = new JScrollPane(htmlPane);
        getContentPane().add(scrollPane, BorderLayout.CENTER);
    } catch(IOException ioe) {
       warnUser("Can't build HTML pane for " + initialURL 
                + ": " + ioe);
    }

    Dimension screenSize = getToolkit().getScreenSize();
    int width = screenSize.width * 8 / 10;
    int height = screenSize.height * 8 / 10;
    setBounds(width/8, height/8, width, height);
    setVisible(true);
  }

  public void actionPerformed(ActionEvent event) {
    String url;
    if (event.getSource() == urlField) {
      url = urlField.getText();
    } else { // Clicked "home" button instead of entering URL.
      url = initialURL;
    }
    try {
      htmlPane.setPage(new URL(url));
      urlField.setText(url);
    } catch(IOException ioe) {
      warnUser("Can't follow link to " + url + ": " + ioe);
    }
  }

  public void hyperlinkUpdate(HyperlinkEvent event) {
    if (event.getEventType() == 
        HyperlinkEvent.EventType.ACTIVATED) {
      try {
        htmlPane.setPage(event.getURL());
        urlField.setText(event.getURL().toExternalForm());
      } catch(IOException ioe) {
        warnUser("Can't follow link to " 
                + event.getURL().toExternalForm() + ": " + ioe);
      }
    }
  }

  private void warnUser(String message) {
    JOptionPane.showMessageDialog(this, message, "Error", 
                                  JOptionPane.ERROR_MESSAGE);
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10315
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

creating a simple Swing application using a JFrame #Programming Code Examples #Java/J2EE/J2ME #Advanced Swing

JFrameExample.java Demonstrates creating a simple Swing application using a JFrame. As with a JApplet, components must be added to the content pane, instead of the window directly.import java.awt.*;
import javax.swing.*;

/** Tiny example showing the main difference in using 
 *  JFrame instead of Frame: using the content pane
 *  and getting the Java (Metal) look and feel by default
 *  instead of the native look and feel.
 *
 */

public class JFrameExample {
  public static void main(String[] args) {
    WindowUtilities.setNativeLookAndFeel();
    JFrame f = new JFrame("This is a test");
    f.setSize(400, 150);
    Container content = f.getContentPane();
    content.setBackground(Color.white);
    content.setLayout(new FlowLayout()); 
    content.add(new JButton("Button 1"));
    content.add(new JButton("Button 2"));
    content.add(new JButton("Button 3"));
    f.addWindowListener(new ExitListener());
    f.setVisible(true);
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10305
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

A simple applet (JApplet) created in Swing. #Programming Code Examples #Java/J2EE/J2ME #Advanced Swing

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

/** Tiny example showing the main differences in using 
 *  JApplet instead of Applet: using the content pane,
 *  getting Java (Metal) look and feel by default, and
 *  having BorderLayout be the default instead of FlowLayout.
 *
  */
 
public class JAppletExample extends JApplet {
  public void init() {
    WindowUtilities.setNativeLookAndFeel();
    Container content = getContentPane();
    content.setBackground(Color.white);
    content.setLayout(new FlowLayout()); 
    content.add(new JButton("Button 1"));
    content.add(new JButton("Button 2"));
    content.add(new JButton("Button 3"));
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10304
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

Multimedia Training

Preview Mail



ইলাস্ট্রেটরে তৈরি করুন টাইপোগ্রাফিক লোগো

Author-Check- Article-or-Video
পূর্ববর্তী পোস্টে টাইপোগ্রাফি সম্পর্কে কিছুটা ধারনা পেয়েছেন এবং একটি হাউজিং কোম্পানির লোগো দেখেছেন। বলাই বাহুল্য সেটি ছিল একটি টাইপোগ্রাফিক লোগো। আজকের পোস্টে এই লোগোটি তৈরি করে দেখাবো। তার আগে লোগোটি এক নজর দেখে নিন আর যারা আগের পোস্ট মিস করেছেন তারা আগের পোস্ট পড়ে আসতে পারেন। না পোড়লেও অবশ্য …

Illustrator Bangla Tutorial (Part-23) (ইলাসট্রেটর বাংলা টিউটোরিয়াল (পার্ট-২৩))

Author-Check- Article-or-Video

Illustrator Bangla Tutorial (Part-22) (ইলাসট্রেটর বাংলা টিউটোরিয়াল (পার্ট-২২))

Author-Check- Article-or-Video

Illustrator Bangla Tutorial (Part-21) (ইলাসট্রেটর বাংলা টিউটোরিয়াল (পার্ট-২১))

Author-Check- Article-or-Video

Illustrator Bangla Tutorial (Part-20) (ইলাসট্রেটর বাংলা টিউটোরিয়াল (পার্ট-২০))

Author-Check- Article-or-Video

Illustrator Bangla Tutorial (Part-19) (ইলাসট্রেটর বাংলা টিউটোরিয়াল (পার্ট-১৯))

Author-Check- Article-or-Video

Illustrator Bangla Tutorial (Part-18) (ইলাসট্রেটর বাংলা টিউটোরিয়াল (পার্ট-১৮))

Author-Check- Article-or-Video

Illustrator Bangla Tutorial (Part-17) (ইলাসট্রেটর বাংলা টিউটোরিয়াল (পার্ট-১৭))

Author-Check- Article-or-Video

Illustrator Bangla Tutorial (Part-16) (ইলাসট্রেটর বাংলা টিউটোরিয়াল (পার্ট-১৬))

Author-Check- Article-or-Video

Illustrator Bangla Tutorial (Part-15) (ইলাসট্রেটর বাংলা টিউটোরিয়াল (পার্ট-১৫))

Author-Check- Article-or-Video

Illustrator Bangla Tutorial (Part-14) (ইলাসট্রেটর বাংলা টিউটোরিয়াল (পার্ট-১৪))

Author-Check- Article-or-Video

Illustrator Bangla Tutorial (Part-13) (ইলাসট্রেটর বাংলা টিউটোরিয়াল (পার্ট-১৩))

Author-Check- Article-or-Video

Illustrator Bangla Tutorial (Part-12) (ইলাসট্রেটর বাংলা টিউটোরিয়াল (পার্ট-১২))

Author-Check- Article-or-Video

Illustrator Bangla Tutorial (Part-11) (ইলাসট্রেটর বাংলা টিউটোরিয়াল (পার্ট-১১))

Author-Check- Article-or-Video

Illustrator Bangla Tutorial (Part-10) (ইলাসট্রেটর বাংলা টিউটোরিয়াল (পার্ট-১০))

Author-Check- Article-or-Video

Illustrator Bangla Tutorial (Part-9) (ইলাসট্রেটর বাংলা টিউটোরিয়াল (পার্ট-৯))

Author-Check- Article-or-Video

Illustrator Bangla Tutorial (Part-8) (ইলাসট্রেটর বাংলা টিউটোরিয়াল (পার্ট-৮))

Author-Check- Article-or-Video

Illustrator Bangla Tutorial (Part-7) (ইলাসট্রেটর বাংলা টিউটোরিয়াল (পার্ট-৭))

Author-Check- Article-or-Video

Illustrator Bangla Tutorial (Part-6) (ইলাসট্রেটর বাংলা টিউটোরিয়াল (পার্ট-৬))

Author-Check- Article-or-Video

Illustrator Bangla Tutorial (Part-5) (ইলাসট্রেটর বাংলা টিউটোরিয়াল (পার্ট-৫))

Author-Check- Article-or-Video

We are hiring: Apply Below

An Intern: A Learning Opportunity
Business Development Specialist/Partner
Online Tutor and Course Developer
Campus Ambassadors

Big Data, Data Science, Analytics, Cloud, Security, AI, Robotics, Database, BI, Development: Software, Web, Mobile

Check official website for more information click here

Printing in Java 2 #Programming Code Examples #Java/J2EE/J2ME #Advanced Swing

    *
          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

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