Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
import java.util.Hashtable;
}
}
Let us consider some examples. Say that you want to display a list of employees belonging to an
organization. This should display the various attributes of employees. For example, employee id,
name, hourly rate, part-time status etc. The display will be more like a database table display of
rows and columns. In this case, the id,name, hourly rate are the columns. The number of rows
might differ based on the number of employees in the organization.
First Attempt:
Let us attempt to display such a data with JTable with minimum amount of code. The idea is to
only display the details in the table. The user should not be allowed to edit any data. Also, text-
based columns should be left-aligned and numerical values should be right-aligned.
The following code should help us do that:
package net.codejava.swing;
1 import javax.swing.JFrame;
2 import javax.swing.JScrollPane;
3 import javax.swing.JTable;
import javax.swing.SwingUtilities;
4 public class TableExample extends JFrame
5 {
6 public TableExample()
7 {
//headers for the table
8 String[] columns = new String[] {
9 "Id", "Name", "Hourly Rate", "Part Time"
10 };
11
12 //actual data for the table in a 2d array
13 Object[][] data = new Object[][] {
{1, "John", 40.0, false },
14 {2, "Rambo", 70.0, false },
15 {3, "Zorro", 60.0, true },
16 };
17 //create table with data
JTable table = new JTable(data, columns);
18
19
//add the table to the frame
20 this.add(new JScrollPane(table));
21
22 this.setTitle("Table Example");
23 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
24 this.pack();
this.setVisible(true);
25 }
26
27 public static void main(String[] args)
28 {
29 SwingUtilities.invokeLater(new Runnable() {
30 @Override
public void run() {
31 new TableExample();
32 }
33 });
34 }
}
This code attempts to build a table with minimum amount of effort. First of all, the column headers
are identified and declared in a String array columns. Next, a 2d Object array named data is
declared. Each inner array corresponds to a row of data. Within each array, the columns are
separated by commas.
Type of At least one abstract method and can have All methods are public
methods multiple concrete methods abstract
Variables Can have public, private, default or protected All variables as public static
Abstract class Inteface
variables final
Inheritance Concrete class can extend only one abstract Class can implement
class. multiple interface
Extends Abstract class can extend abstract class Interface can implement
other interaces
It is also considered that abstract class is faster that interface, since the compiler needs
to find the implementation and figure out the concrete class. But, the results show that
improve in performance is very minimal and it should not be consider during building
classes.
Define a default behavior for subclasses. It means that all child classes should
have perform same functionality.
}
Define a flow/procedure for a use case and provide some default implementation
and leave some implementation to the subclass.
In Swing, we can do that by using method addChoosableFileFilter(FileFilter filter) of the class JFileChooser.
Create a class that extends FileFilter abstract class and overrides its two methods:
o boolean accept(File f): returns true if the file f satisfies a filter condition. The
condition here is the extension of the file.
o String getDescription(): returns a description which is displayed in the dialog’s Files
of type section.
The following code shows an example of adding a filter for files of type PDF:
JFileChooser fileChooser = new JFileChooser();
fileChooser.addChoosableFileFilter(new FileFilter() {
However, what if we need to add several filters, such as for .docx, .xlsx files? Well,
one solution is repeating the above code for each file type – but that is not good in
terms of code reusability. So, it’s better to create a separate, generalized class for
extending the FileFilter abstract class, and parameterize the file extension and
description, as shown in the following code:
import java.io.File;
import javax.swing.filechooser.FileFilter;
fileChooser.addChoosableFileFilter(docFilter);
fileChooser.addChoosableFileFilter(pdfFilter);
fileChooser.addChoosableFileFilter(xlsFilter);
Before Java 6, we have to write the above code manually. Fortunately, since Java 6,
Swing adds a new class called FileNameExtensionFilter, which makes adding file
filters easier. For example:
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("PDF
Documents", "pdf"));
And following is a sample program that shows an open dialog when the button
Browse is clicked, with some filters for: PDF documents, MS Office documents, and
Images.
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.filechooser.FileNameExtensionFilter;
/**
* Demo of file extension filter. Applied since Java 1.6
* @author www.codejava.net
*
*/
public class FileExtensionFilterDemo extends JFrame {
private JButton buttonBrowse;
public FileExtensionFilterDemo() {
super("Demo File Type Filter");
setLayout(new FlowLayout());
buttonBrowse = new JButton("Browse...");
buttonBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
showOpenFileDialog();
}
});
getContentPane().add(buttonBrowse);
setSize(300, 100);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) { }
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new FileExtensionFilterDemo();
}
});
}
In this tutorial I will teach you how to write Java code using the java.util.Random
class to generate single or a set of random numbers in your program.
We are using the java.util.Random class for generating the random number.
}
}
If you run the above code following output will be displayed on the browser:
Cloneable interface in a class points out that it is legal for Object.clone() method to
copy instances of that class. In simple words, a class defines Cloneable Interface if it
wants its object to be cloned. However, it is not necessary that a Cloneable interface
contains a clone() method.
clone( ) method creates a duplicate object that has distinct identity but similar content.
It must also be noted that just invoking an Object's clone method on an instance does
not implement the Cloneable interface. If an object's class does not implement the
Cloneable interface, CloneNotSupportedException is thrown.
emp.setHireDay(2005,0,0);
emp1.raiseSalary(20);
System.out.println("Employee=" + emp);
System.out.println("copy=" + emp1);
salary = dou;
try{
cloned.hireDay = (Date)hireDay.clone();
return cloned;
catch(CloneNotSupportedException e){
System.out.println(e);
return null;
salary += raise;
}
Output:
C:\help>javac CloneTest.java
C:\help>java CloneTest
In this example, you will learn how to copy the data from one JTextField into another
JTextField. When you run this program it starts with two JTextField. Enter some data
into first JTextfield and select the entered text, right click, copy and then paste into
another JTextField.
You can use JTextField into your swing applications to develop data entry forms.
Output:
Enter some data into first text field (cell1). Highlight all the text in first cell. After
selecting you right click the mouse button and copy the text of cell 1.
public TCPopupEventQueue() {
//createPopupMenu();
}
center.add(new JLabel("cell1:"));
center.add(field);
center.add(new JLabel("cell2:"));
center.add(field1);
JPanel content = new JPanel( new FlowLayout(FlowLayout.LEFT) );
content.add( center, BorderLayout.SOUTH );
JFrame frame = new JFrame("cell copy past program");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(content);
frame.setSize(550,100);
frame.setVisible(true);
}
}