Download Part-23

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
PART 23
Java GUI Advanced
23.1 JList Component
JList is a component that displays a list of objects. It allows the user to select one or
more items.
import
import
import
import
import
import
import
import
import
java.awt.Color;
java.awt.EventQueue;
javax.swing.JFrame;
javax.swing.JPanel;
javax.swing.border.EmptyBorder;
javax.swing.JList;
javax.swing.ListSelectionModel;
javax.swing.event.ListSelectionListener;
javax.swing.event.ListSelectionEvent;
public class JListExample extends JFrame {
private JPanel contentPane;
String[] listColorNames = { "black", "blue", "green", "yellow","white" };
Color[] listColorValues = { Color.BLACK, Color.BLUE,Color.GREEN,Color.YELLOW, Color.WHITE};
public JListExample() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
final JList list = new JList(listColorNames);
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
contentPane.setBackground(listColorValues[list.getSelectedIndex()]);
}
});
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setSelectedIndex(0);
list.setBounds(109, 54, 144, 163);
contentPane.add(list);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JListExample frame = new JListExample();
frame.setVisible(true);
}
});
}
}
23.2 JTextArea component
A JTextArea is a multi-line text area that displays plain text. It is lightweight
component for working with text. The component does not handle scrolling. For this
task, we use JScrollPanecomponent.
import
import
import
import
import
import
import
import
import
import
javax.swing.JFrame;
javax.swing.JPanel;
javax.swing.border.EmptyBorder;
javax.swing.JOptionPane;
javax.swing.JTextArea;
javax.swing.JButton;
javax.swing.JScrollPane;
javax.swing.SwingUtilities;
java.awt.event.ActionListener;
java.awt.event.ActionEvent;
public class JTextAreaExample extends JFrame {
private JPanel contentPane;
public JTextAreaExample() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Independence hymn");
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(56, 11, 300, 177);
contentPane.add(scrollPane);
final JTextArea textArea = new JTextArea();
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
scrollPane.setViewportView(textArea);
JButton btnNewButton = new JButton("Show Me Text");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, textArea.getText());
}
});
btnNewButton.setBounds(156, 216, 141, 23);
contentPane.add(btnNewButton);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JTextAreaExample frame = new JTextAreaExample();
frame.setVisible(true);
}
});
}
}
The example shows a simple JTextArea component.
JTextArea textArea = new JTextArea();
This is the constructor of the JTextArea component.
textArea.setLineWrap(true);
Make the lines wrapped, if they are too long to fit the width.
textArea.setWrapStyleWord(true);
Here we specify, how is line going to be wrapped. In our case, lines will be wrapped at
word boundaries, whitespaces.
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(56, 11, 300, 177);
contentPane.add(scrollPane);
final JTextArea textArea = new JTextArea();
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
scrollPane.setViewportView(textArea);
To
make
the
text
scrollable,
we
put
the JTextArea component
into
the JScrollPane component.
23.3 JEditorPane component
JEditorPane is a kind of textArea which can display various text formats. By default,
JEditorPane supports HTML and RTF (Rich Text Format).
In practice, JEditorPane is typically used for displaying HTML only. JEditorPane
also supports RTF but very limited. You can set content for JEditorPane in the
following ways:

Pass URL object or URL string into constructor of JEditorPane.

Use setPage() method to set content of JEditorPane at runtime.

Pass content as a String to the setText() method.
To make JEditorPane read only, you use method setEditable(false). When displaying
HTML document, JEditorPane can detect HTML links and which link user clicks. To
handle the click event on links, you need to handle HyperlinkListener event.
In this example, we will create a very simple web browser to display any web page by
using JEditorPane component. In this example, we are also using JButton and
JTextField components.
import
import
import
import
import
import
import
import
import
import
import
javax.swing.JFrame;
javax.swing.JPanel;
javax.swing.border.EmptyBorder;
javax.swing.JLabel;
javax.swing.JTextField;
javax.swing.JButton;
javax.swing.JEditorPane;
javax.swing.JScrollPane;
javax.swing.SwingUtilities;
java.awt.event.ActionListener;
java.awt.event.ActionEvent;
public class JEditorPaneExample extends JFrame {
private JPanel contentPane;
private JTextField textField;
public JEditorPaneExample() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 850, 517);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblUrl = new JLabel("URL");
lblUrl.setBounds(10, 11, 36, 14);
contentPane.add(lblUrl);
textField = new JTextField();
textField.setBounds(56, 8, 688, 20);
contentPane.add(textField);
textField.setColumns(10);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 39, 800, 416);
contentPane.add(scrollPane);
final JEditorPane editorPane = new JEditorPane();
scrollPane.setViewportView(editorPane);
JButton btnNewButton = new JButton("GO");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
editorPane.setPage(textField.getText());
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
btnNewButton.setBounds(754, 7, 56, 23);
contentPane.add(btnNewButton);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JEditorPaneExample frame = new JEditorPaneExample();
frame.setVisible(true);
}
});
}
}
23.4 Swing Dialogs
Dialog windows or dialogs are an indispensable part of most modern GUI
applications. A dialog is defined as a conversation between two or more persons. In a
computer application a dialog is a window which is used to "talk" to the application. A
dialog is used to input data, modify data, change the application settings etc. Dialogs
are important means of communication between a user and a computer program.
In Java Swing toolkit, we can create two kinds of dialogs.

Custom dialogs

standard dialogs
Custom
dialogs are
the JDialog class.
created
by
the
programmer.
They
are
based
on
Standard dialogs predefined dialogs available in the Swing toolkit. For example
MessageDialog, InputDialog, JColorChooser or JFileChooser. These are dialogs
for common programming tasks like showing text, receiving input , loading and saving
files etc. They save programmer's time and enhance using some standard behaviour.
There are two basic types of dialogs. Modal and modeless.

Modal dialogs does not allow input to other top level windows. An open file
dialog is a good example of a modal dialog. While choosing a file to open, no
other operation should be permitted.

Modeless dialogs allow input to other windows. A typical modeless dialog is a
find text dialog.
23.5 JFileChooser
JFileChooser is a standard dialog for selecting a file from the file system.
import
import
import
import
import
import
import
import
import
import
import
import
java.awt.EventQueue;
javax.swing.JFileChooser;
javax.swing.JFrame;
javax.swing.JPanel;
javax.swing.border.EmptyBorder;
javax.swing.filechooser.FileFilter;
javax.swing.filechooser.FileNameExtensionFilter;
javax.swing.JButton;
java.awt.event.ActionListener;
java.awt.event.ActionEvent;
java.io.File;
javax.swing.JEditorPane;
public class JFileChooserExample extends JFrame {
private JPanel contentPane;
public JFileChooserExample() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
final JEditorPane editorPane = new JEditorPane();
editorPane.setBounds(20, 50, 387, 187);
contentPane.add(editorPane);
JButton btnNewButton = new JButton("Open File");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fileopen = new JFileChooser();
FileFilter filter = new FileNameExtensionFilter("txt files", "txt");
fileopen.addChoosableFileFilter(filter);
int answer = fileopen.showDialog(null, "Open file");
if (answer == JFileChooser.APPROVE_OPTION) {
File file = fileopen.getSelectedFile();
try {
editorPane.setPage("File:///"+ file);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
});
btnNewButton.setBounds(10, 11, 89, 23);
contentPane.add(btnNewButton);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JFileChooserExample frame = new JFileChooserExample();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
The code example will demonstrate how to use a file chooser dialog in order to load
file contents into the text area component.
JFileChooser fileopen = new JFileChooser();
This is the constructor of the file chooser dialog.
FileFilter filter = new FileNameExtensionFilter("txt files", "txt");
fileopen.addChoosableFileFilter(filter);
Here we define the file filter. In our case, we will have txt files with extension .txt. We
have also the default All files option.
int answer = fileopen.showDialog(null, "Open file");
Here we show the file chooser dialog. Upon clicking on the open file button, the return
value is equal to JFileChooser.APPROVE_OPTION.
if (ret == JFileChooser.APPROVE_OPTION) {
File file = fileopen.getSelectedFile();
try {
editorPane.setPage("File:///"+ file);
} catch (Exception e1) {
e1.printStackTrace();
}
}
Here we get the name of the selected file. We read the contents of the file and set the
text into the editorPane.
23.6 JColorChooser
JColorChooser is a standard dialog for selecting a color.
import
import
import
import
import
import
import
import
import
import
javax.swing.JColorChooser;
javax.swing.JFrame;
javax.swing.JPanel;
javax.swing.SwingUtilities;
javax.swing.border.EmptyBorder;
javax.swing.JButton;
javax.swing.border.LineBorder;
java.awt.Color;
java.awt.event.ActionListener;
java.awt.event.ActionEvent;
public class JColorChooserExample extends JFrame {
private JPanel contentPane;
public JColorChooserExample() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
final JPanel panel = new JPanel();
panel.setBorder(new LineBorder(new Color(0, 0, 0)));
panel.setBounds(67, 74, 220, 145);
contentPane.add(panel);
JButton btnNewButton = new JButton("Choose Color");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Color color = JColorChooser.showDialog(null, "Choose Color", Color.white);
panel.setBackground(color);
}
});
btnNewButton.setBounds(10, 11, 111, 23);
contentPane.add(btnNewButton);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JColorChooserExample frame = new JColorChooserExample();
frame.setVisible(true);
}
});
}
}
In the example, we have a panel. We will change the background color of the panel by
selecting a color from the color chooser dialog.
Color color = JColorChooser.showDialog(null, "Choose Color", Color.white);
panel.setBackground(color);
This code shows a color chooser dialog. The showDialog() method returns the
selected color value. We change the display panel background to the newly selected
color.
23.7 Menus in Java Swing
A menubar is one of the most visible parts of the GUI application. It is a group of
commands located in various menus.
In Java Swing, to implement a menubar, we use three objects. A JMenuBar,
a JMenu and aJMenuItem.
We begin with a simple menubar example.
import
import
import
import
java.awt.event.ActionEvent;
java.awt.event.ActionListener;
javax.swing.ImageIcon;
javax.swing.JFrame;
import
import
import
import
javax.swing.JMenu;
javax.swing.JMenuBar;
javax.swing.JMenuItem;
javax.swing.SwingUtilities;
public class Example extends JFrame {
public Example() {
JMenuBar menubar = new JMenuBar();
ImageIcon icon = new ImageIcon(getClass().getResource("exit.png"));
JMenu filemenu = new JMenu("File");
JMenuItem eMenuItem = new JMenuItem("Exit", icon);
eMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
filemenu.add(eMenuItem);
menubar.add(filemenu);
setJMenuBar(menubar);
setTitle("Simple menu");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Example ex = new Example();
ex.setVisible(true);
}
});
}
}
Our example will show a menu with one item. Selecting the exit menu item we close
the application.
JMenuBar menubar = new JMenuBar();
Here we create a menubar.
ImageIcon icon = new ImageIcon(getClass().getResource("exit.png"));
We will display an icon in the menu.
23.8 JTable
JTables are used to display data held in multi-dimensional arrays. This is useful for
displaying
players,
customers,
data
from
various
sensor
etc.
The default model of a table displays the data you put in as a table with all the cells
editable, as if it were in Microsoft Excel. Each cell is of the same size.
To fill the table, we need arrays of data. The headings for the table is a simple String
array, and the data in the table is a 2D Object Array.
import
import
import
import
import
import
javax.swing.JFrame;
javax.swing.JPanel;
javax.swing.SwingUtilities;
javax.swing.border.EmptyBorder;
javax.swing.JTable;
javax.swing.JScrollPane;
public class JTableExample extends JFrame {
private JPanel contentPane;
private JTable table;
// The data used as the titles for the table.
String[] title = {"No.", "Country", "Player", "Position"};
// The data used in the table, placed as a multi-dimensional array.
Object[][] playerdata = {
{4, "United States", "Sterling Davis" , "Forward"},
{6, "Germany", "Moritz Wohlers", "Forward/Centre"},
{7, "United Kingdom", "Ross Hutton", "Centre"},
{8, "Belgium", "Hugo Sterk", "Guard"},
{10, "United Kingdom", "Andy Pearson", "Forward"},
{11, "United States", "Robert Yanders", "Guard"},
{12, "United Kingdom", "Graham Hunter", "Guard"},
{14, "United Kingdom", "Julius Joseph", "Guard/Forward"},
{15, "United Kingdom", "Gareth Murray", "Forward"},
{21, "United States", "Maurice Hampton", "Guard"}};
public JTableExample() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(35, 45, 344, 119);
contentPane.add(scrollPane);
table = new JTable(playerdata, title);
scrollPane.setViewportView(table);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
JTableExample frame = new JTableExample();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
The JTable itself is instantiated really easily. We pass the 2D array in, then the
headings for the table.
JTable table = new JTable(playerdata, title);
We add the table to a scroll pane for two reasons: One reason is for scrolling, the
other is: without scroll pane the headings aren't shown.
Related documents