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
Related