|
Этот совет Java иллюстрирует метод выхода из приложений при закрытой раме. В Java, когда закрыты нажатии кнопки нет действий, которые определены по умолчанию. Разработчик целом хотел бы завершить свое применение при закрытой раме.
// Application frame
Frame applicationframe = new Frame();
// Add a listener for the frame close event
applicationframe.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
// Exit the application
System.exit(0);
}
});
|
|
|
Прогресс бар используются длинные задачи, чтобы показать пользователю, сколько времени осталось до завершения задачи.
Прогресс бары осуществляются в Swing помощью JProgressBar класс. Пример кода ниже показано, как использовать прогресс баров в Swing приложения:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Progress extends JFrame {
JProgressBar current;
JTextArea out;
JButton find;
Thread runner;
int num = 0;
public Progress() {
super("Progress");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel();
pane.setLayout(new FlowLayout());
current = new JProgressBar(0, 2000);
current.setValue(0);
current.setStringPainted(true);
pane.add(current);
setContentPane(pane);
}
public void iterate() {
while (num < 2000) {
current.setValue(num);
try {
Thread.sleep(1000);
} catch (InterruptedException e) { }
num += 95;
}
}
public static void main(String[] arguments) {
Progress frame = new Progress();
frame.pack();
frame.setVisible(true);
frame.iterate();
}
}
|
|
Sun Microsystems предлагает широкий спектр документации (официальные документы, API спецификации, руководство программиста, и более), достижимые из theirdocumentation странице: http://java.sun.com/docs/index.html
Этот сайт имеет несколько руководств и советов.
Вы также можете посмотреть на followingurls Для дополнительной информации:
|
Вы можете преобразовать целое число в коде ASCII методом литья как показано ниже:
char c = 'A';
int i = (int) c; // i will have the value 65 decimal
|
|
|
Этот совет Java иллюстрирует способ создания списка. Отзыв здесь описываются различные аспекты связанные списки, такие как добавление элементов в списке, извлечение и удаление элементов элемента из списка.
// Create a link list
List list = new LinkedList(); // Doubly-linked list
list = new ArrayList(); // List implemented as growable array
// Append an element to the list
list.add("a");
// Insert an element at the head (0) of the list
list.add(0, "b");
// Get the number of elements in the list
int size = list.size(); // 2
// Retrieving the element at the end of the list
Object element = list.get(list.size()-1); // a
// Retrieving the element at the head of the list
element = list.get(0); // b
// Deleting occurrance of the first element of the link list
boolean b = list.remove("b"); // true
b = list.remove("b"); // false
// Remove the element at a particular index
element = list.remove(0); // a
|
|
|
Вы можете отобразить чисел в научной нотации java.text помощью пакета. Конкретно DecimalFormat класса в java.text пакет может быть использован для этой цели.
В следующем примере показано, как это сделать:
import java.text.*;
import java.math.*;
public class TestScientific {
public static void main(String args[]) {
new TestScientific().doit();
}
public void doit() {
NumberFormat formatter = new DecimalFormat();
int maxinteger = Integer.MAX_VALUE;
System.out.println(maxinteger); // 2147483647
formatter = new DecimalFormat("0.######E0");
System.out.println(formatter.format(maxinteger)); // 2,147484E9
formatter = new DecimalFormat("0.#####E0");
System.out.println(formatter.format(maxinteger)); // 2.14748E9
int mininteger = Integer.MIN_VALUE;
System.out.println(mininteger); // -2147483648
formatter = new DecimalFormat("0.######E0");
System.out.println(formatter.format(mininteger)); // -2.147484E9
formatter = new DecimalFormat("0.#####E0");
System.out.println(formatter.format(mininteger)); // -2.14748E9
double d = 0.12345;
formatter = new DecimalFormat("0.#####E0");
System.out.println(formatter.format(d)); // 1.2345E-1
formatter = new DecimalFormat("000000E0");
System.out.println(formatter.format(d)); // 12345E-6
}
}
|
|
|
Вам нужно использовать декомпилятор. Вы можете найти список Декомпиляторы для Java
|
|
Вкладках панели отображается компонент из группы компонентов, когда выбран один из вкладок панели's. Это компактная компонента.
Этот образец кода делает вкладок панели с двумя вкладками.

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
public class TabbedPane extends JFrame {
public TabbedPane() {
setTitle("Tabbed Pane");
JTabbedPane jtp = new JTabbedPane();
getContentPane().add(jtp);
JPanel jp1 = new JPanel();
JPanel jp2 = new JPanel();
JLabel label1 = new JLabel();
label1.setText("You are in area of Tab1");
JLabel label2 = new JLabel();
label2.setText("You are in area of Tab2");
jp1.add(label1);
jp2.add(label2);
jtp.addTab("Tab1", jp1);
jtp.addTab("Tab2", jp2);
}
public static void main(String[] args) {
TabbedPane tp = new TabbedPane();
tp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tp.setVisible(true);
}
}
|
|
|
Это можно сделать, открыв сокет к порту "дневной" (порт 13) (на Unix или NT машину).
import java.net.*;
import java.io.*;
public class GetTime {
public static void main(String args[]) {
if (args.length != 1) {
System.out.println("Usage: GetTime HOST");
return;
}
try {
Socket s = new Socket(args[0],13);
InputStream is = s.getInputStream();
while (true) {
byte b[] = new byte[100];
int i=is.read(b);
if (i==-1) return;
System.out.print(new String(b,0,i));
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
|
|
|
Окончательный класс класс Java, который не может быть продлен. Это означает, что окончательное класс не может стать ни суперкласса иметь подклассы.
Пример окончательных классов представлены в таблице:
final class MySecureClass {
// This class cannot be extended
}
|
|