import java.awt.*;
import java.awt.event.*;
public class UpperTF extends Frame {
public static void main(String argv[]) {
new UpperTF().setVisible(true);
}
public UpperTF() {
setLayout(new FlowLayout());
TextField tf = new TextField(10);
add(tf);
tf.addKeyListener(
new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (Character.isLetter(e.getKeyChar()))
e.setModifiers(Event.SHIFT_MASK);
}
});
pack();
addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
}
public Dimension getPreferredSize() {
return new Dimension(200,200);
}
}
|
|
|
Этот совет Java содержит программу, которая преобразует данный красный, зеленый и синий (RGB Color Space) в соответствующие оттенка, насыщенности и интенсивности значений (HSI цветовом пространстве).
import java.awt.Color;
import java.io.PrintStream;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class RGB2HSIConverter
{
public RGB2HSIConverter()
{
}
public static void main(String args[])
{
if(args.length > 2)
{
int ai[] = new int[3];
for(int i = 0; i < 3; i++)
ai[i] = Integer.parseInt(args[i]);
float af[] = Color.RGBtoHSB(ai[0], ai[1], ai[2], null);
String args1[] = {
"H=", "S=", "I="
};
DecimalFormat decimalformat = new DecimalFormat("0.000");
for(int j = 0; j < 3; j++)
System.out.println(args1[j] + decimalformat.format(af[j]));
} else
{
System.err.println("usage: java RGB2HSIConverter <r> <g> <b>");
System.exit(1);
}
}
}
|
|
Вы можете использовать следующий код для получения IP адреса в апплете:
String ip = (new Socket(getDocumentBase().getHost(), getDocumentBase().getPort()))
.getLocalAddress().getHostAddress();
|
|
Вы можете приостановить выполнение своей программы / Thread помощью сна () класса Thread класс. Следующем примере показано, как сделать это:
public class Wait {
public static void oneSec() {
try {
Thread.currentThread().sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void manySec(long s) {
try {
Thread.currentThread().sleep(s * 1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class TestWait {
public static void main(String args[]) {
System.out.println("Wait one second");
Wait.oneSec();
System.out.println("Done\nWait five seconds");
Wait.manySec(5);
System.out.println("Done");
}
}
|
|
|
JDK 5.0 обеспечивает типизированный массив списка. Перед JDK 5.0 Список массивов хранения объектов типа объекта. Но теперь тип элементов ArrayList могут быть указаны.
Синтаксис:
ArrayList Список \u003d Новый ArrayList ();
Пример:
import java.util.ArrayList;
public class MyArrayList {
public static void main(String[] args) {
Seller sel = new Seller();
Buyer buy = new Buyer();
// declare an array list of type Seller
ArrayList<Seller> list = new ArrayList<Seller>();
list.add(sel); // add object of type Seller which is permisible
list.add(buy); // this statement will give an error
}
}
|
|
Этот совет Java Swing демонстрирует метод реализации Icon Spinner. Это также включает в себя осуществление JSpinner с настраиваемым содержанием - иконы в этом случае. Стандартная модель счетчика может быть использован при помощи обычного редактора.
import javax.swing.*;
import java.awt.*;
public class IconSpinner extends JFrame {
public IconSpinner() {
super("JSpinner Icon Test");
setSize(300,80);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(new GridLayout(0,2));
Icon nums[] = new Icon[] {
new ImageIcon("1.gif"),
new ImageIcon("2.gif"),
new ImageIcon("3.gif"),
new ImageIcon("4.gif"),
new ImageIcon("5.gif"),
new ImageIcon("6.gif")
};
JSpinner s1 = new JSpinner(new SpinnerListModel(nums));
s1.setEditor(new IconEditor(s1));
c.add(new JLabel(" Icon Spinner"));
c.add(s1);
setVisible(true);
}
public static void main(String args[]) {
new IconSpinner();
}
}
|
|

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.geom.AffineTransform;
import java.awt.geom.GeneralPath;
import java.awt.geom.Rectangle2D;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class TransformersRotation extends JComponent {
Shape axes, shape;
int length = 54, arrowLength = 4, tickSize = 4;
public TransformersRotation() {
axes = createAxes();
shape = createShape();
}
protected Shape createAxes() {
GeneralPath path = new GeneralPath();
// Axes.
path.moveTo(-length, 0);
path.lineTo(length, 0);
path.moveTo(0, -length);
path.lineTo(0, length);
// Arrows.
path.moveTo(length - arrowLength, -arrowLength);
path.lineTo(length, 0);
path.lineTo(length - arrowLength, arrowLength);
path.moveTo(-arrowLength, length - arrowLength);
path.lineTo(0, length);
path.lineTo(arrowLength, length - arrowLength);
// Half-centimeter tick marks
float cm = 72 / 2.54f;
float lengthCentimeter = length / cm;
for (float i = 0.5f; i < lengthCentimeter; i += 1.0f) {
float tick = i * cm;
path.moveTo(tick, -tickSize / 2);
path.lineTo(tick, tickSize / 2);
path.moveTo(-tick, -tickSize / 2);
path.lineTo(-tick, tickSize / 2);
path.moveTo(-tickSize / 2, tick);
path.lineTo(tickSize / 2, tick);
path.moveTo(-tickSize / 2, -tick);
path.lineTo(tickSize / 2, -tick);
}
// Full-centimeter tick marks
for (float i = 1.0f; i < lengthCentimeter; i += 1.0f) {
float tick = i * cm;
path.moveTo(tick, -tickSize);
path.lineTo(tick, tickSize);
path.moveTo(-tick, -tickSize);
path.lineTo(-tick, tickSize);
path.moveTo(-tickSize, tick);
path.lineTo(tickSize, tick);
path.moveTo(-tickSize, -tick);
path.lineTo(tickSize, -tick);
}
return path;
}
protected Shape createShape() {
float cm = 72 / 2.54f;
return new Rectangle2D.Float(cm, cm, 2 * cm, cm);
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
// Use antialiasing.
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// Move the origin to 75, 75.
AffineTransform at = AffineTransform.getTranslateInstance(75, 75);
g2.transform(at);
// Draw the shapes in their original locations.
g2.setPaint(Color.black);
g2.draw(axes);
g2.draw(shape);
// Transform the Graphics2D.
g2.transform(AffineTransform.getRotateInstance(-Math.PI / 6));
// Draw the "new" shapes in dashed.
Stroke stroke = new BasicStroke(1, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_BEVEL, 0, new float[] { 3, 1 }, 0);
g2.setStroke(stroke);
g2.draw(axes);
g2.draw(shape);
}
public static void main(String[] a) {
JFrame f = new JFrame();
f.getContentPane().add(new TransformersRotation());
f.setSize(350, 200);
f.show();
}
}
|
|
|
Этот образец кода необходим для полной и свободной памяти во время работы с консолью.
public class MemoryExp {
public static void main(String[] args) {
System.out.println("Total Memory"+Runtime.getRuntime().totalMemory());
System.out.println("Free Memory"+Runtime.getRuntime().freeMemory());
}
}
|
|
|
Этот совет Java иллюстрирует методы получения и установки свойств Bean. Этот совет использует слова и заявления для установления свойств. Разработчик может приобрести и установить три типа свойств объекта, примитивный тип, и массива. Оба этих классов использовать имя метода, который получает или устанавливает собственности.
Object obj = new MyBean();
try {
// Developer may get the value of prop1
Expression expr = new Expression(obj, "getProp1",
new Object[0]);
expr.execute();
String s = (String)expr.getValue();
// Developer may set the value of prop1
Statement stmt = new Statement(obj, "setProp1",
new Object[]{"new string"});
stmt.execute();
// Now developer may get the value of prop2
expr = new Expression(obj, "getProp2", new Object[0]);
expr.execute();
int i = ((Integer)expr.getValue()).intValue();
// Now developer may set the value of prop2
stmt = new Statement(obj, "setProp2",
new Object[]{new Integer(123)});
stmt.execute();
// Further get the value of prop1
expr = new Expression(obj, "getProp3", new Object[0]);
expr.execute();
byte[] bytes = (byte[])expr.getValue();
// Finally setting the value of prop1
stmt = new Statement(obj, "setProp3",
new Object[]{new byte[]{0x12, 0x23}});
stmt.execute();
} catch (Exception e) {
}
public class MyBean {
// Property prop1
String prop1;
public String getProp1() {
return prop1;
}
public void setProp1(String s) {
prop1 = s;
}
// Property prop2
int prop2;
public int getProp2() {
return prop2;
}
public void setProp2(int i) {
prop2 = i;
}
// Property prop3
byte[] prop3;
public byte[] getProp3() {
return prop3;
}
public void setProp3(byte[] bytes) {
prop3 = bytes;
}
}
|
|
|
В большинстве случаев DTD определения распределяется между многочисленными XML-документы, которые он описывает. В такой ситуации это будет более удобно разместить такое DTD в посвящает документ доступен на данный URL (Calles Система-ID) или название (государственно-ID). Таким образом, все документы XML при помощи типов, определенных в этом DTD-файл будет просто сослаться его, как это показано в образце ниже:
<!-- file: purchase-order.dtd -->
<!-- declaration of the root element and its attributes -->
<!ELEMENT purchase-order (purchased-by, order-items)>
<!ATTLIST purchase-order
date CDATA #REQUIRED
number CDATA #REQUIRED
>
<!ELEMENT purchased-by (address)>
<!ATTLIST purchased-by
name CDATA #REQUIRED
>
<!ELEMENT address (#PCDATA)>
<!-- order-items can contains at least on item -->
<!ELEMENT order-items (item+)>
<!ELEMENT item EMPTY>
<!ATTLIST item
code CDATA #REQUIRED
type CDATA #REQUIRED
label CDATA #REQUIRED
>
<!-- file: sample.xml -->
<?xml version="1.0"?>
<!-- Sample of linked DTD definition -->
<!DOCTYPE purchase-order SYSTEM "purchase-order.dtd">
<!--
In order to constrain the contents of XML-document
a DTD-definition may be refered in DOCTYPE instruction.
-->
<purchase-order date="2005-10-31" number="12345">
<purchased-by name="My name">
<address>My address</address>
</purchased-by>
<order-items>
<!--
here is an example of empty element
i.e. containing no nested elements
-->
<item code="687" type="CD" label="Some music" />
<item code="129851" type="DVD" label="Some video"/>
</order-items>
</purchase-order>
|
Страница 1 из 612345»...Последняя »