Апплеты могут читать довольно много системных переменных с помощью:
String ss = System.getProperty(String key):
java.version
java.vendor
java.vendor.url
java.class.version
os.name
os.arch
os.version
file.separator
path.separator
line.separator
Апплетам запрещено читать следующие системные переменные:
java.home
java.class.path
user.name
user.home
user.dir
|
Этот совет Java Swing иллюстрирует метод создания и наполнения дерево. Простой тест, чтобы увидеть, как мы можем построить дерево и заполнить ее. Это приложение также использует пользовательский подготовки отчетов и редакторов.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
import java.util.*;
public class EmailTree extends JFrame {
JTree tree;
String[][] addresses = {
{"
", "
", "
"},
{"
"},
{"
", "
"},
{"
"},
{"
", "
"},
{"
"}
};
public EmailTree() {
super("Hashtable Test");
setSize(400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE); // 1.3 & higher
// addWindowListener(new BasicWindowMonitor()); // 1.1 & 1.2
}
public void init() {
Hashtable h = new Hashtable();
Hashtable paul = new Hashtable();
paul.put("Work", addresses[0]);
paul.put("Home", addresses[1]);
Hashtable damian = new Hashtable();
damian.put("Work", addresses[2]);
damian.put("Pager", addresses[3]);
damian.put("Home", addresses[4]);
Hashtable angela = new Hashtable();
angela.put("Home", addresses[5]);
h.put("Paul", paul);
h.put("Damian", damian);
h.put("Angela", angela);
tree = new JTree(h);
DefaultTreeCellRenderer renderer =
(DefaultTreeCellRenderer)tree.getCellRenderer();
renderer.setOpenIcon(new ImageIcon("mailboxdown.gif"));
renderer.setClosedIcon(new ImageIcon("mailboxup.gif"));
renderer.setLeafIcon(new ImageIcon("letter.gif"));
EmailTreeCellEditor emailEditor = new EmailTreeCellEditor();
DefaultTreeCellEditor editor = new DefaultTreeCellEditor(
tree, renderer, emailEditor);
tree.setCellEditor(editor);
tree.setEditable(true);
getContentPane().add(tree, BorderLayout.CENTER);
}
public static void main(String args[]) {
EmailTree tt = new EmailTree();
tt.init();
tt.setVisible(true);
}
}
|
|
|
Все компоненты Swing наследует от javax.swing.JComponent класс. JComponent само наследует от java.awt.Component класс, который означает, что все компоненты Swing также AWT компоненты. Ниже приводится список компонентов (с их краткими описаниями) в Swing.
cellpadding="2" cellspacing="2">
|
| JButton |
A push button that can display text, images, or both. |
| JCheckBox |
A toggle button for displaying choices that are not mutually exclusive. |
| JCheckBoxMenuItem |
A checkbox designed for use in menus. |
| JColorChooser |
A complex, customizable component that allows the user to select a color from one or more color spaces. Used in conjunction with the javax.swing.colorchooser package. |
| JComboBox |
A combination of a text entry field and a drop-down list of choices. The user can type a selection or choose one from the list. |
| JComponent |
The root of the Swing component hierarchy. Adds Swing-specific features such as tooltips and support for double-buffering. |
| JEditorPane |
A powerful text editor, customizable via an EditorKit object. Predefined editor kits exist for displaying and editing HTML- and RTF-format text. |
| JFileChooser |
A complex component that allows the user to select a file or directory. Supports filtering and optional file previews. Used in conjunction with the javax.swing.filechooser package. |
| JLabel |
A simple component that displays text, an image, or both. Does not respond to input. |
| JList |
A component that displays a selectable list of choices. The choices are usually strings or images, but arbitrary objects may also be displayed. |
| JMenu |
A pull-down menu in a JMenuBar or a submenu within another menu. |
| JMenuBar |
A component that displays a set of pull-down menus. |
| JMenuItem |
A selectable item within a menu. |
| JOptionPane |
A complex component suitable for displaying simple dialog boxes. Defines useful static methods for displaying common dialog types. |
| JPasswordField |
A text input field for sensitive data, such as passwords. For security, does not display the text as it is typed. |
| JPopupMenu |
A window that pops up to display a menu. Used by JMenu and for standalone pop-up menus. |
| JProgressBar |
A component that displays the progress of a time-consuming operation. |
| JRadioButton |
A toggle button for displaying mutually exclusive choices. |
| JRadioButtonMenuItem |
A radio button for use in menus. |
| JScrollBar |
A horizontal or vertical scrollbar. |
| JSeparator |
A simple component that draws a horizontal or vertical line. Used to visually divide complex interfaces into sections. |
| JSlider |
A component that simulates a slider control like those found on stereo equalizers. Allows the user to select a numeric value by dragging a knob. Can display tick marks and labels. |
| JTable |
A complex and powerful component for displaying tables and editing their contents. Typically used to display strings but may be customized to display any type of data. Used in conjunction with the javax.swing.table package. |
| JTextArea |
A component for displaying and editing multiple lines of plain text. Based on JTextComponent. |
| JTextComponent |
The root component of a powerful and highly customizable text display and editing system. Part of the javax.swing.text package. |
| JTextField |
A component for the display, input, and editing of a single line of plain text. Based on JTextComponent. |
| JTextPane |
A subclass of JEditorPane for displaying and editing formatted text that is not in HTML or RTF format. Suitable for adding simple word processing functionality to an application. |
| JToggleButton |
The parent component of both JCheckBox and JRadioButton. |
| JToolBar |
A component that displays a set of user-selectable tools or actions. |
| JToolTip |
A lightweight pop-up window that displays simple documentation or tips when the mouse pointer lingers over a component. |
| JTree |
A powerful component for the display of tree-structured data. Data values are typically strings, but the component can be customized to display any kind of data. Used in conjunction with the javax.swing.tree package. |
|
Этот совет Java демонстрирует метод получения байта из ByteBuffer. ByteBuffer имеет потенциал, который определяет, сколько байт она содержит. Этот потенциал не может измениться. Байт ByteBuffer также можно извлечь с помощью относительного версия получить (), которая использует положения и предельных свойствах буфера. В частности, эта версия получить () возвращает байт на позицию и выдвигает позицию за другой. получить () не может получить байт прошлого предела (хотя предел может быть меньше мощности). Положение всегда <\u003d предел и предел всегда <\u003d потенциал.
// Create an empty ByteBuffer with a 10 byte capacity
ByteBuffer bbuf = ByteBuffer.allocate(10);
// Retrieve the capacity of the ByteBuffer
int capacity = bbuf.capacity(); // 10
// The position is not affected by the absolute get() method.
byte b = bbuf.get(5); // position=0
// Set the position
bbuf.position(5);
// Use the relative get()
b = bbuf.get();
// Get the new position
int pos = bbuf.position(); // 6
// Get remaining byte count
int rem = bbuf.remaining(); // 4
// Set the limit
bbuf.limit(7); // remaining=1
// This convenience method sets the position to 0
bbuf.rewind(); // remaining=7
|
|
|
Этот образец кода считывает файл XML с помощью DOM парсер. DOM парсер загружает XML-файла в память и делает объектную модель его. Это модальное объект может быть пройден получить ее элементов.
Этот код будет проанализировать следующие MyXMLFile.xml файл и распечатать его элементов на консоль.
XML-файла: MyXMLFile.xml
<?xml version="1.0"?>
<company>
<employee>
<firstname>Tom</firstname>
<lastname>Cruise</lastname>
</employee>
<employee>
<firstname>Paul</firstname>
<lastname>Enderson</lastname>
</employee>
<employee>
<firstname>George</firstname>
<lastname>Bush</lastname>
</employee>
</company>
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class XMLReader {
public static void main(String argv[]) {
try {
File file = new File("c:\\MyXMLFile.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
System.out.println("Root element " + doc.getDocumentElement().getNodeName());
NodeList nodeLst = doc.getElementsByTagName("employee");
System.out.println("Information of all employees");
for (int s = 0; s < nodeLst.getLength(); s++) {
Node fstNode = nodeLst.item(s);
if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
Element fstElmnt = (Element) fstNode;
NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("firstname");
Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
NodeList fstNm = fstNmElmnt.getChildNodes();
System.out.println("First Name : " + ((Node) fstNm.item(0)).getNodeValue());
NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("lastname");
Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
NodeList lstNm = lstNmElmnt.getChildNodes();
System.out.println("Last Name : " + ((Node) lstNm.item(0)).getNodeValue());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
|
|
Программа печатает ниже классов URL, при нынешней системе загрузчика классов:
import java.net.URL;
import java.net.URLClassLoader;
public class PrintClasspath {
public static void main(String[] args) {
//Get the System Classloader
ClassLoader sysClassLoader = ClassLoader.getSystemClassLoader();
//Get the URLs
URL[] urls = ((URLClassLoader)sysClassLoader).getURLs();
for(int i=0; i< urls.length; i++)
{
System.out.println(urls[i].getFile());
}
}
}
|
|
|
Этот совет Java иллюстрирует особый способ обхода через кнопки. Обычно обход делается с помощью "вкладку" клавишу на клавиатуре в том же порядке, в котором были разработаны кнопки. Этот метод делает возможным обход на основе статей в алфавитном порядке кнопки этикетках.
import java.awt.*;
import java.util.*;
import javax.swing.*;
public class AlphaButtonPolicy extends FocusTraversalPolicy {
private SortedMap getSortedButtons(Container focusCycleRoot) {
if (focusCycleRoot == null) {
throw new IllegalArgumentException(
"focusCycleRoot can't be null");
}
SortedMap result = new TreeMap(); // Will sort all buttons by text.
sortRecursive(result, focusCycleRoot);
return result;
}
private void sortRecursive(Map buttons, Container container) {
for (int i = 0; i < container.getComponentCount(); i++) {
Component c = container.getComponent(i);
if (c instanceof JButton) { // Found another button to sort.
buttons.put(((JButton)c).getText(), c);
}
if (c instanceof Container) { // Found a container to search.
sortRecursive(buttons, (Container)c);
}
}
}
// The rest of the code implements the FocusTraversalPolicy interface.
public Component getFirstComponent(Container focusCycleRoot) {
SortedMap buttons = getSortedButtons(focusCycleRoot);
if (buttons.isEmpty()) { return null; }
return (Component)buttons.get(buttons.firstKey());
}
public Component getLastComponent(Container focusCycleRoot) {
SortedMap buttons = getSortedButtons(focusCycleRoot);
if (buttons.isEmpty()) { return null; }
return (Component)buttons.get(buttons.lastKey());
}
public Component getDefaultComponent(Container focusCycleRoot) {
return getFirstComponent(focusCycleRoot);
}
public Component getComponentAfter(Container focusCycleRoot,
Component aComponent) {
if (!(aComponent instanceof JButton)) { return null; }
SortedMap buttons = getSortedButtons(focusCycleRoot);
// Find all buttons after the current one.
String nextName = ((JButton)aComponent).getText() + "\0";
SortedMap nextButtons = buttons.tailMap(nextName);
if (nextButtons.isEmpty()) { // Wrapped back to beginning
if (!buttons.isEmpty()) {
return (Component)buttons.get(buttons.firstKey());
}
return null; // Degenerate case of no buttons.
}
return (Component)nextButtons.get(nextButtons.firstKey());
}
public Component getComponentBefore(Container focusCycleRoot,
Component aComponent) {
if (!(aComponent instanceof JButton)) { return null; }
SortedMap buttons = getSortedButtons(focusCycleRoot);
SortedMap prevButtons = // Find all buttons before this one.
buttons.headMap(((JButton)aComponent).getText());
if (prevButtons.isEmpty()) { // Wrapped back to end.
if (!buttons.isEmpty()) {
return (Component)buttons.get(buttons.lastKey());
}
return null; // Degenerate case of no buttons.
}
return (Component)prevButtons.get(prevButtons.lastKey());
}
}
|
|
|
Java предоставляет управляющих последовательностей для ряда неправительственных организаций графические символы. Все символы могут быть указаны как в шестнадцатеричном характер Unicode (\\ uxxxx) с некоторыми как восьмеричное символа (\\ DDD, где первая деревня ограничивается 0-3, а остальные 0-7 - то же, что и \\ u0000-\\ u00ff).
\n New line
\t Tab
\b Backspace
\r Carriage return
\f Formfeed
\\ Backslash
\' Single quotation mark
\" Double quotation mark
\d Octal
\xd Hexadecimal
\ud Unicode character
|
Этот совет Java Swing иллюстрирует метод осуществления прокрутки в вертикальной и горизонтальной направлении. Разработчик может реализовать это в своих приложениях для обеспечения легкого просмотра функциональности своим пользователям для навигации по длинным документам. Разработчик может поставлять ориентации (через JSlider.HORIZONTAL или JSlider.VERTICAL) и диапазон и начальное значение в конструктор.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ScrollBarExample extends JPanel {
JLabel label;
public ScrollBarExample() {
super(true);
label=new JLabel();
setLayout(new BorderLayout());
JScrollBar hbar = new JScrollBar(
JScrollBar.HORIZONTAL, 30, 20, 0, 300);
JScrollBar vbar = new JScrollBar(
JScrollBar.VERTICAL, 30, 40, 0, 300);
hbar.setUnitIncrement(2);
hbar.setBlockIncrement(1);
hbar.addAdjustmentListener(new MyAdjustmentListener());
vbar.addAdjustmentListener(new MyAdjustmentListener());
add(hbar, BorderLayout.SOUTH);
add(vbar, BorderLayout.EAST);
add(label, BorderLayout.CENTER);
}
class MyAdjustmentListener implements AdjustmentListener {
public void adjustmentValueChanged(AdjustmentEvent e) {
label.setText(" New Value is " + e.getValue() + " ");
repaint();
}
}
public static void main(String s[]) {
JFrame frame = new JFrame("Scroll Bar Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new ScrollBarExample());
frame.setSize(200,200);
frame.setVisible(true);
}
}
|
|

import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SimplestGradientPaint extends JPanel{
public static void main(String[] args) {
JFrame f = new JFrame();
f.getContentPane().add(new SimplestGradientPaint());
f.setSize(350, 250);
f.show();
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Ellipse2D e = new Ellipse2D.Float(40, 40, 120, 120);
GradientPaint gp = new GradientPaint(75, 75, Color.white, 95, 95,
Color.gray, true);
g2.setPaint(gp);
g2.fill(e);
}
}
|
|
Страница 1 из 612345»...Последняя »