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

# ListEvents.java Uses the following classes:

    * CloseableFrame.java
    * SelectionReporter.java
    * ActionReporter.java
/././././././././././././
import java.awt.event.*;

/././././././

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

  /** Extends ListEvents with the twist that
   *  typing any of the letters of "JAVA" or "java"
   *  over the language list will result in "Java"
   *  being selected
   */

  public ListEvents2() {
    super();
    // Create a KeyAdapter and attach it to languageList.
    // Since this is an inner class, it has access
    // to nonpublic data (such as the ListEvent's
    // protected showJava method).
    KeyAdapter javaChooser = new KeyAdapter() {
      public void keyPressed(KeyEvent event) {
        int key = event.getKeyChar();
        if ("JAVAjava".indexOf(key) != -1) {
          showJava();
        }
      }
    };
    languageList.addKeyListener(javaChooser);
  }
}

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

/** A class to demonstrate list selection/deselection
 *  and action events.
 *
 /*******************/.>

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

  protected List languageList;
  private TextField selectionField, actionField;
  private String selection = "[NONE]", action;

  /** Build a Frame with list of language choices
   *  and two textfields to show the last selected
   *  and last activated items from this list.
   */
  public ListEvents() {
    super("List Events");
    setFont(new Font("Serif", Font.BOLD, 16));
    add(makeLanguagePanel(), BorderLayout.WEST);
    add(makeReportPanel(), BorderLayout.CENTER);
    pack();
    setVisible(true);
  }

  // Create Panel containing List with language choices.
  // Constructor puts this at left side of Frame.
  
  private Panel makeLanguagePanel() {
    Panel languagePanel = new Panel();
    languagePanel.setLayout(new BorderLayout());
    languagePanel.add(new Label("Choose Language"), 
                      BorderLayout.NORTH);
    languageList = new List(3);
    String[] languages =
      { "Ada", "C", "C++", "Common Lisp", "Eiffel",
        "Forth", "Fortran", "Java", "Pascal",
        "Perl", "Scheme", "Smalltalk" };
    for(int i=0; i<languages .length; i++) {
      languageList.add(languages[i]);
    }
    showJava();
    languagePanel.add("Center", languageList);
    return(languagePanel);
  }

  // Creates Panel with two labels and two textfields.
  // The first will show the last selection in List; the
  // second, the last item activated. The constructor puts
  // this Panel at the right of Frame.

  private Panel makeReportPanel() {
    Panel reportPanel = new Panel();
    reportPanel.setLayout(new GridLayout(4, 1));
    reportPanel.add(new Label("Last Selection:"));
    selectionField = new TextField();
    SelectionReporter selectionReporter =
      new SelectionReporter(selectionField);
    languageList.addItemListener(selectionReporter);
    reportPanel.add(selectionField);
    reportPanel.add(new Label("Last Action:"));
    actionField = new TextField();
    ActionReporter actionReporter = 
      new ActionReporter(actionField);
    languageList.addActionListener(actionReporter);
    reportPanel.add(actionField);
    return(reportPanel);
  }

  /** Select and show "Java". */
  
  protected void showJava() {
    languageList.select(7);
    languageList.makeVisible(7);
  }
}
*********************
SelectionReporter.java
*********************
import java.awt.*;
import java.awt.event.*;

/** Whenever an item is selected, it is displayed
 *  in the textfield that was supplied to the
 *  SelectionReporter constructor.
 *
 *******************************
public class SelectionReporter implements ItemListener {
  private TextField selectionField;

  public SelectionReporter(TextField selectionField) {
    this.selectionField = selectionField;
  }

  public void itemStateChanged(ItemEvent event) {
    if (event.getStateChange() == event.SELECTED) {
      List source = (List)event.getSource();
      selectionField.setText(source.getSelectedItem());
    } else
      selectionField.setText("");
  }
}
*********************
ActionReporter.java
*******************
import java.awt.*;
import java.awt.event.*;

/** Whenever an item is activated, it is displayed
 *  in the textfield that was supplied to the
 *  ActionReporter constructor.
 *
 *************************

public class ActionReporter implements ActionListener {
  private TextField actionField;

  public ActionReporter(TextField actionField) {
    this.actionField = actionField;
  }

  public void actionPerformed(ActionEvent event) {
    List source = (List)event.getSource();
    actionField.setText(source.getSelectedItem());
  }
}

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

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

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

Checkboxes.java Inherits from CloseableFrame.java. 
******************
import java.awt.*;

/./././././././././

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

  public Checkboxes() {
    super("Checkboxes");
    setFont(new Font("SansSerif", Font.BOLD, 18));
    setLayout(new GridLayout(0, 2));
    Checkbox box;
    for(int i=0; i<12; i++) {
      box = new Checkbox("Checkbox " + i);
      if (i%2 == 0) {
        box.setState(true);
      }
      add(box);
    }
    pack();
    setVisible(true);
  }
}

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

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 Frame that can actually quit #Programming Code Examples #Java/J2EE/J2ME #Advanced Swing

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

/** A Frame that you can actually quit. Used as the starting 
 *  point for most Java 1.1 graphical applications.
 *

public class CloseableFrame extends Frame {
  public CloseableFrame(String title) {
    super(title);
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
  }

  /** Since we are doing something permanent, we need
   *  to call super.processWindowEvent first.
   */
  
  public void processWindowEvent(WindowEvent event) {
    super.processWindowEvent(event); // Handle listeners.
    if (event.getID() == WindowEvent.WINDOW_CLOSING) {
      // If the frame is used in an applet, use dispose().
      System.exit(0);
    }
  }
}

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

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

Places a Panel holding 100 buttons in a ScrollPane #Programming Code Examples #Java/J2EE/J2ME #Advanced Swing

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

/** Places a Panel holding 100 buttons in a ScrollPane that is
 *  too small to hold it.
 *
  */

public class ScrollPaneTest extends Applet {
  public void init() {
    setLayout(new BorderLayout());
    ScrollPane pane = new ScrollPane();
    Panel bigPanel = new Panel();
    bigPanel.setLayout(new GridLayout(10, 10));
    for(int i=0; i<100; i++) {
      bigPanel.add(new Button("Button " + i));
    }
    pane.add(bigPanel);
    add(pane, BorderLayout.CENTER);
  }
}

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

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

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