|
В предоставлении услуг в области компьютерной науки, транспорта и исследование операций очереди буфера, где хранятся различные организации, такие как данные, объекты, лица, или события, и ждет, чтобы быть обработаны. Наиболее известные эксплуатацию очереди First-In-First-Out (FIFO) очереди процесс в очереди FIFO, первый элемент в очереди будет одним из первых, это равносильно тому, что всякий раз, когда элемент добавлены, все элементы, которые были добавлены до, должны быть устранены до начала нового элемента может быть вызван.
Существуют два основных операций, связанных с очередью: епдиеие и йедиеие. Добавляет означает добавление нового элемента в задней части а Dequeue очередь ссылается на удаление переднего элемента из очереди и возвращает его в пункт.
Следующий код показывает, как реализовать очередь с помощью массивов:
// ArrayQueue class
//
// CONSTRUCTION: with no initializer
//
// ******************PUBLIC OPERATIONS*********************
// void enqueue( x ) --> Insert x
// Object getFront( ) --> Return least recently inserted item
// Object dequeue( ) --> Return and remove least recent item
// boolean isEmpty( ) --> Return true if empty; else false
// void makeEmpty( ) --> Remove all items
// ******************ERRORS********************************
// getFront or dequeue on empty queue
/**
* Array-based implementation of the queue.
* @author Mark Allen Weiss
*/
public class ArrayQueue implements Queue
{
/**
* Construct the queue.
*/
public ArrayQueue( )
{
theArray = new Object[ DEFAULT_CAPACITY ];
makeEmpty( );
}
/**
* Test if the queue is logically empty.
* @return true if empty, false otherwise.
*/
public boolean isEmpty( )
{
return currentSize == 0;
}
/**
* Make the queue logically empty.
*/
public void makeEmpty( )
{
currentSize = 0;
front = 0;
back = -1;
}
/**
* Return and remove the least recently inserted item
* from the queue.
* @return the least recently inserted item in the queue.
* @throws UnderflowException if the queue is empty.
*/
public Object dequeue( )
{
if( isEmpty( ) )
throw new UnderflowException( "ArrayQueue dequeue" );
currentSize--;
Object returnValue = theArray[ front ];
front = increment( front );
return returnValue;
}
/**
* Get the least recently inserted item in the queue.
* Does not alter the queue.
* @return the least recently inserted item in the queue.
* @throws UnderflowException if the queue is empty.
*/
public Object getFront( )
{
if( isEmpty( ) )
throw new UnderflowException( "ArrayQueue getFront" );
return theArray[ front ];
}
/**
* Insert a new item into the queue.
* @param x the item to insert.
*/
public void enqueue( Object x )
{
if( currentSize == theArray.length )
doubleQueue( );
back = increment( back );
theArray[ back ] = x;
currentSize++;
}
/**
* Internal method to increment with wraparound.
* @param x any index in theArray's range.
* @return x+1, or 0 if x is at the end of theArray.
*/
private int increment( int x )
{
if( ++x == theArray.length )
x = 0;
return x;
}
/**
* Internal method to expand theArray.
*/
private void doubleQueue( )
{
Object [ ] newArray;
newArray = new Object[ theArray.length * 2 ];
// Copy elements that are logically in the queue
for( int i = 0; i < currentSize; i++, front = increment( front ) )
newArray[ i ] = theArray[ front ];
theArray = newArray;
front = 0;
back = currentSize - 1;
}
private Object [ ] theArray;
private int currentSize;
private int front;
private int back;
private static final int DEFAULT_CAPACITY = 10;
}
/**
* Exception class for access in empty containers
* such as stacks, queues, and priority queues.
* @author Mark Allen Weiss
*/
public class UnderflowException extends RuntimeException
{
/**
* Construct this exception object.
* @param message the error message.
*/
public UnderflowException( String message )
{
super( message );
}
}
// Queue interface
//
// ******************PUBLIC OPERATIONS*********************
// void enqueue( x ) --> Insert x
// Object getFront( ) --> Return least recently inserted item
// Object dequeue( ) --> Return and remove least recent item
// boolean isEmpty( ) --> Return true if empty; else false
// void makeEmpty( ) --> Remove all items
// ******************ERRORS********************************
// getFront or dequeue on empty queue
/**
* Protocol for queues.
* @author Mark Allen Weiss
*/
public interface Queue
{
/**
* Insert a new item into the queue.
* @param x the item to insert.
*/
void enqueue( Object x );
/**
* Get the least recently inserted item in the queue.
* Does not alter the queue.
* @return the least recently inserted item in the queue.
* @exception UnderflowException if the queue is empty.
*/
Object getFront( );
/**
* Return and remove the least recently inserted item
* from the queue.
* @return the least recently inserted item in the queue.
* @exception UnderflowException if the queue is empty.
*/
Object dequeue( );
/**
* Test if the queue is logically empty.
* @return true if empty, false otherwise.
*/
boolean isEmpty( );
/**
* Make the queue logically empty.
*/
void makeEmpty( );
}
|
|
|
Этот совет Java Swing показывает счетчик, что рулоны с конца списка в начале. Этот совет описывает пользовательский Spinner модель, которая наведет курсор в конце списка в начало (или наоборот).
import javax.swing.*;
import java.util.List;
public class RolloverSpinnerListModel extends SpinnerListModel {
public RolloverSpinnerListModel(Object[] items) { super(items); }
public RolloverSpinnerListModel(List items) { super(items); }
public Object getNextValue() {
Object nv = super.getNextValue();
if (nv != null) {
return nv;
}
return getList().get(0);
}
public Object getPreviousValue() {
Object pv = super.getPreviousValue();
if (pv != null) {
return pv;
}
List l = getList();
return l.get(l.size() - 1);
}
}
|
|
|
Вещания определяется как отправка пакет для всех узлов сети на подсети. Подсеть IP сетевая маска делит IP адрес на две части: идентификатор сети и узлов идентификатора. Широковещательный адрес определяется как адрес IP, где установлены все биты узла идентификатора.
Таким образом, посылается широковещательный пакет из программы Java (или из программы на любом другом языке, если на то пошло), просто требует от вас указать широковещательный адрес в качестве пункта назначения для пакета.
|
|
Этот совет Java иллюстрирует метод чтения изображения из файла, входящего потока, или URL. Этот совет также включает отображение изображений на экране. Кроме того, javax.imageio пакет используется для считывания изображения из файла. Этот пример работает только над J2SE 1.4.
Image image = null;
try {
// Read from a file
File sourceimage = new File("source.gif");
image = ImageIO.read(sourceimage);
// Read from an input stream
InputStream is = new BufferedInputStream(
new FileInputStream("source.gif"));
image = ImageIO.read(is);
// Read from a URL
URL url = new URL("http://javist.ru/source.gif");
image = ImageIO.read(url);
} catch (IOException e) {
}
// Use a label to display the image
JFrame frame = new JFrame();
JLabel label = new JLabel(new ImageIcon(image));
frame.getContentPane().add(label, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
|
|
|
Вы можете получить список дисков системы с помощью listRoots () Метод файла класса:
File[] roots = File.listRoots();
for(int i=0;i<roots.length;i++)
System.out.println("Root["+i+"]:" + roots[i]);
|
|
Этот совет Java Swing иллюстрирует быстрое утилита для вывода графической информации устройства. Этот совет будет работать на системах с несколькими мониторами. Разработчики могут принять к сведению, что каждая GraphicsDevice имеет ряд объектов GraphicsConfiguration связанные с ней. Эти объекты указать различные конфигурации, в которых GraphicsDevice могут быть использованы.
import java.awt.*;
import javax.swing.*;
public class GuiScreens {
public static void main(String[] args) {
Rectangle virtualBounds = new Rectangle();
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gs = ge.getScreenDevices();
JFrame frame[][] = new JFrame[gs.length][];
for (int j = 0; j < gs.length; j++) {
GraphicsDevice gd = gs[j];
System.out.println("Device " + j + ": " + gd);
GraphicsConfiguration[] gc = gd.getConfigurations();
frame[j] = new JFrame[gc.length];
for (int i=0; i < gc.length; i++) {
System.out.println(" Configuration " + i + ": " + gc[i]);
System.out.println(" Bounds: " + gc[i].getBounds());
virtualBounds = virtualBounds.union(gc[i].getBounds());
frame[j][i] = new JFrame("Config: " + i, gc[i]);
frame[j][i].setBounds(50, 50, 400, 100);
frame[j][i].setLocation(
(int)gc[i].getBounds().getX() + 50,
(int)gc[i].getBounds().getY() + 50);
frame[j][i].getContentPane().add(
new JTextArea("Config:\n" + gc[i]));
frame[j][i].setVisible(true);
}
System.out.println("Overall bounds: " + virtualBounds);
}
}
}
|
|
|
Этот совет Java Swing иллюстрирует метод реализации фантазия каретка для вашего приложения. Разработчики могут использовать это в игровых приложениях, чтобы предоставить анимированный каретки для пользователей.

import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
public class FancyCaret extends DefaultCaret {
protected synchronized void damage(Rectangle r) {
if (r == null) return;
// give values to x,y,width,height (inherited from java.awt.Rectangle)
x = r.x;
y = r.y;
height = r.height;
// A value for width was probably set by paint(), which we leave alone.
// But the first call to damage() precedes the first call to paint(), so
// in this case we must be prepared to set a valid width, or else paint()
// will receive a bogus clip area and caret will not get drawn properly.
if (width <= 0) width = getComponent().getWidth();
repaint(); // calls getComponent().repaint(x, y, width, height)
}
public void paint(Graphics g) {
JTextComponent comp = getComponent();
if (comp == null) return;
int dot = getDot();
Rectangle r = null;
char dotChar;
try {
r = comp.modelToView(dot);
if (r == null) return;
dotChar = comp.getText(dot, 1).charAt(0);
} catch (BadLocationException e) { return; }
if ( (x != r.x) || (y != r.y) ) {
// paint() has been called directly, without a previous call to
// damage(), so do some cleanup. (This happens, for example, when the
// text component is resized.)
repaint(); // erase previous location of caret
x = r.x; // Update dimensions (width gets set later in this method)
y = r.y;
height = r.height;
}
g.setColor(comp.getCaretColor());
g.setXORMode(comp.getBackground()); // do this to draw in XOR mode
if (dotChar == '\n') {
int diam = r.height;
if (isVisible())
g.fillArc(r.x-diam/2, r.y, diam, diam, 270, 180); // half circle
width = diam / 2 + 2;
return;
}
if (dotChar == '\t') try {
Rectangle nextr = comp.modelToView(dot+1);
if ((r.y == nextr.y) && (r.x < nextr.x)) {
width = nextr.x - r.x;
if (isVisible()) g.fillRoundRect(r.x, r.y, width, r.height, 12, 12);
return;
}
else dotChar = ' ';
} catch (BadLocationException e) { dotChar = ' '; }
width = g.getFontMetrics().charWidth(dotChar);
if (isVisible()) g.fillRect(r.x, r.y, width, r.height);
}
public static void main(String args[]) {
JFrame frame = new JFrame("FancyCaret demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextArea area = new JTextArea(8, 32);
area.setCaret(new FancyCaret());
area.setText("VI\tVirgin Islands \nVA Virginia\nVT\tVermont");
frame.getContentPane().add(new JScrollPane(area), BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
|
|
|
DOM является высокий уровень-API для обработки XML-данных. DOM использует SAX анализ источников. Отличие от SAX является то, что нет необходимости для обработки XML Element напрямую. Весь документ состоит и возвращается экземпляр DocumentBuilder. Пример ниже показывает обычной загрузке XML с помощью DOM:
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import org.w3c.dom.*;
/**
* This sample program shows how to load XML data
* using DOM interface.
*/
public class Test {
public static void main(String[] args) {
try {
// first of all we request out
// DOM-implementation:
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
// then we have to create document-loader:
DocumentBuilder loader = factory.newDocumentBuilder();
// loading a DOM-tree...
Document document = loader.parse("sample.xml");
// at last, we get a root element:
Element tree = document.getDocumentElement();
// ... do something with document element ...
} catch (IOException ex) {
// any IO errors occur:
handleError(ex);
} catch (SAXException ex) {
// parse errors occur:
handleError(ex);
} catch (ParserConfigurationException ex) {
// document-loader cannot be created which,
// satisfies the configuration requested
handleError(ex);
} catch (FactoryConfigurationError ex) {
// DOM-implementation is not available
// or cannot be instantiated:
handleError(ex);
}
}
private static final void handleError(Throwable ex) {
// ... handle error here...
}
}
|
|
|
PixelGrabber класс имеющихся в java.awt.Image packate могут быть использованы для доступа пикселов изображения объекта. PixelGrabber класса могут приобрести данные пикселей, синхронно или асинхронно. Он может сохранить значения пикселов в указанном пользователем массив или создать подходящие сам массив.
В следующем примере показано, как использовать класс PixelGrabber получить данные из пиксел изображения объекта.
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.PixelGrabber;
public class PixelGrabberTest {
public PixelGrabberTest() {
}
public static void processImage(String inFile, String outFile) {
Image image = Toolkit.getDefaultToolkit().getImage(inFile);
try {
PixelGrabber grabber =
new PixelGrabber(image, 0, 0, -1, -1, false);
if (grabber.grabPixels()) {
int width = grabber.getWidth();
int height = grabber.getHeight();
if (isGreyscaleImage(grabber)) {
byte[] data = (byte[]) grabber.getPixels();
// Process greyscale image ...
}
else {
int[] data = (int[]) grabber.getPixels();
// Process Color image
}
}
}
catch (InterruptedException e1) {
e1.printStackTrace();
}
}
public static final boolean isGreyscaleImage(PixelGrabber pg) {
return pg.getPixels() instanceof byte[];
}
public static void main(String args[]) {
if (args.length > 1) {
processImage(args[0], args[1]);
System.exit(0);
} else {
System.err.println(
"usage: java PixelGrabberTest <infile> <outfile>");
System.exit(2);
}
}
}
|
|
|
Вы можете упаковать свои классы в банке файла и этот файл горшок может быть использован в классе пути.
После команд должна быть выполнена в различных целях в управлении файлов JAR.
- jar cf jar-file inputfiles: It is used to create new JAR.
- jar tf jar-file: It is used to view all the files of the JAR.
- jar xf jar-file: It is used to extract the JAR.
- java -jar app.jar: It is used to run a JAR if the manifest file is present in the JAR. This manifest file contains the information of the file having main method. Content of the manifest is:
Main-Class: classname
|
Страница 1 из 612345»...Последняя »