Открыть Электронные книги
Категории
Открыть Аудиокниги
Категории
Открыть Журналы
Категории
Открыть Документы
Категории
1. Java................................................................... 2
2. Java.............................................................................................................................. 8
3. Java javadoc. ............... 13
4. Java.
Swing. ..................................................................................................................................................................... 15
5. Java. .................................................................................. 21
6. , Java. ............................................................................. 25
7. , JList, JScrollPane, HashMap. jar-. .......... 29
1. Java.
Java:
class HelloWorld{
public static void main(String[] args){
System.out.println("Hello, XXI Century World!");
}
}
Java.
(class).
class, ,
, Helloworld. , ,
(class body).
(method).
Java
, .
. main,
. ,
, main.
, ( ,
(return)) , .
, , .
void,
.
, , (arguments)
. , , .
, , .
Java String, .
, args.
(modifiers). : public , ;
static main()
-
, main() .
, , (method body), .
, main() ,
System.out.println
,
"Hello,
2lth
century
world!".
, .
if,
Java
switch,
(//
),
/++ .
( ) ++ (.
.1.1 1.2).
1.1. .
()
byte
-128 127
short
-32768 32767
int
-2147483648 2147483647
long
-9223372036854775808 9223372036854775807
char
1.2.
float
7-8
double
1,7-308<||<1,7308
17
: Java % ( ), ++ ()
() .
Java ,
. .
(declaration).
(reference) , .
, , ,
, , ,
double[] , b;
b double.
.
:
int I = 0, ar[], k = -1;
i k,
ar.
(installation). ,
, , -
. Java
new,
. ,
= new double[5];
b = new double[100];
ar = new int[50];
3
0. [0], [1],,
[4].
[5]
:
doublet] a = new double[5], b = new double[100];
int i = 0, ar[] = new int[50], k = -1;
,
.
, :
double[] = {0.01, -3.4, 2.89, 4.5, -6.7};
:
= new double[] {0.1, 0.2, -0.3, 0.45, -0.02};
, new, ,
:
System.out.println(new char[] {'H', 'e', '1', '1', 'o'});
,
. , = b b
100 double
.
"" null,
:
ar = null;
, , ,
.
,
, , ==b, , !=b. ,
, , .
,
length. .
. , , a.length
5, b.length 100, a ar.length 50.
: a[a.length-1], a[a.length-2]
. . :
double aMin = a[0], aMax = aMin;
for (int i = 1; i < a.length; i++){
if (a[i] < aMin) aMin = a[i];
if (a[i] > aMax) aMax = a[i];
}
-
:
System.out.println();
, +, ,
int n=5;
System.out.println(""+" "+"#"+n);
4
#5
.
, .
,
System.out.print();
:
Scanner in = new Scanner(System.in);
int m;
m = in.nextInt();
in Scanner ,
System.in, , . ,
, , in
(in.nextInt()). java.util.Scanner (import
java.util.Scanner;). , (nextInt,
nextShort, nextFloat, nextDouble .., ). , ,
:
import java.util.Scanner;
public class hi {
public static void main (String [] args){
int n, mas[];
float s=0;
Scanner in = new Scanner(System.in);
System.out.print(" : ");
n = in.nextInt();
mas = new int[n];
for (int i=0;i<mas.length; i++){
System.out.print(" "+i+"-"+" : ");
mas[i]=in.nextInt();
s+=mas[i];
}
s/=n;
System.out.println(". . : "+s);
}
}
:
: 3
0- : 3
1- : 2
2- : 2
. . : 2.3333333
7 . ,
:
import java.util.Scanner;
import java.text.NumberFormat;//
public class hi {
public static void main (String [] args){
int n, mas[];
float s=0;
Scanner in = new Scanner(System.in);
System.out.print(" : ");
n = in.nextInt();
mas = new int[n];
for (int i=0;i<mas.length; i++){
System.out.print(" "+i+"-"+" : ");
mas[i]=in.nextInt();
s+=mas[i];
}
s/=n;
NumberFormat nf = NumberFormat.getInstance(); // nf
//NumberFormat
// (NumberFormat.getInstance())
nf.setMaximumFractionDigits(2);//
// 2
System.out.println(". . : "+nf.format(s));
// s
5
}
}
:
: 3
0- : 3
1- : 2
2- : 2
. . : 2,33
. Java
Random. nextInt( ),
0..( 1).
java.util.Random. :
import java.text.NumberFormat;
import java.util.*; // java.util
public class hi {
public static void main (String [] args){
int n, mas[];
float s=0;
Scanner in = new Scanner(System.in);
System.out.print(" : ");
n = in.nextInt();
mas = new int[n];
Random random = new Random();// - .
for (int i=0;i<mas.length; i++){
mas[i]=random.nextInt(5);// .
// ( 0 4)
System.out.println(i+"-"+" : "+mas[i]);
s+=mas[i];
}
s/=n;
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);
System.out.println(". . : "+nf.format(s));
}
}
:
: 10
0- : 4
1- : 3
2- : 4
3- : 2
4- : 3
5- : 4
6- : 2
7- : 3
8- : 1
9- : 1
. . : 2,7
:
I.
1.
2.
. , 5, 1.
. a b.
, a b.
3. .
4. . -.
5. . ,
.
6. . ,
2 (.. ).
7. . ,
.
8. . , ,
.
9. . , .
10. 1, 2,..., n. , i i.
6
11. n. ,
.
12. N . , , .
13. . , ,
, .
14. N . ,
.
15. . , *, d+.
16. . , .
17. . , .
18. . ,
.
19. n. , .
20. , n . ,
, k.
21. A*n+. ,
.
22. . , .
II.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
.
, .
. .
.
( ). , (3;1), ..
3 1 , 3 1 , 1 3 .
. .
. , ,
, , .
.
.
. 2 : ,
.
A*N, N+, .
. ,
, .
.
n k. k- ,
.
n k. k- ,
.
. .
.
. .
.
. ,
.
. ,
.
. , . ,
.
. , . ,
.
. , . , .
. , . ,
.
. ,
.
. .
. .
2. Java.
- Java ++ (. . . ++), .
, ,
.
, , :
public class Auto {
private String firm; //
private int maxSpeed; // ,
public void setFirm(String firma){ // ( )
firm=firma;
//
}
public void setMaxSpeed(int speed){ // ( )
maxSpeed=speed;
//
}
public int getMaxSpeed(){
// ( )
return maxSpeed;
//
}
public String getFirm(){
return firm;
}
// ( )
//
public Auto(){
// ( )
firm=" ";
maxSpeed=0;
}
public Auto(String firma, int speed){ // ( )
firm=firma;
maxSpeed=speed;
}
}
, ( ):
public class test {
public static void main(String[] args) {
Auto myAuto1=new Auto("Ford",180); //
System.out.println(myAuto1.getFirm()+" "+myAuto1.getMaxSpeed());//
}
//
}
, :
import java.util.Scanner; //
public class test {
public static void main(String[] args) {
Auto myAuto1=new Auto(); //
Scanner in = new Scanner(System.in); //
System.out.print(" : ");
String nazv=in.next(); // !!! 1
//.. in.next() ,
// ,
myAuto1.setFirm(nazv); //
System.out.print(" : ");
int s=in.nextInt();
myAuto1.setMaxSpeed(s);
System.out.println(myAuto1.getFirm()+" "+myAuto1.getMaxSpeed());
}
}
public Car(String firma, int speed, String name, int n, Boolean f){
super(firma,speed); - (. Auto)
model=name; //
numDoors=n;
fullTime=f;
}
public void setModel(String name){
model=name;
}
public String getModel(){
return model;
}
public void setNumDoors(int n){
numDoors=n;
}
public int getNumDoors(){
return numDoors;
}
public void setFullTime(Boolean b){
fullTime=b;
}
public Boolean isFullTime(){
return fullTime;
}
public String toString(){
return getFirm()+" "+getMaxSpeed()+" "+model+" "+numDoors+" "+fullTime;
}
}
// Truck.java
import java.util.Scanner;
public class Truck extends Auto{
private String model;
private int power;
private Boolean trailer; //c
public Truck(){
super();
model="";
power=0;
trailer=false;
}
public Truck(String firma, int speed, String name, int n, Boolean f){
super(firma,speed);
model=name;
power=n;
trailer=f;
}
public void setModel(String name){
model=name;
}
public String getModel(){
return model;
}
public void setPower(int n){
power=n;
}
public int getPower(){
return power;
}
public void setTrailer(Boolean b){
trailer=b;
}
public Boolean isTrailer(){
return trailer;
}
public void setAllInfo(){
9
( test.java):
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Auto myAuto1=new Auto();
Scanner in = new Scanner(System.in);
System.out.print(" : ");
String nazv=in.next();
myAuto1.setFirm(nazv);
System.out.print(" : ");
int s=in.nextInt();
myAuto1.setMaxSpeed(s);
System.out.println("- : "+myAuto1.getFirm()+" "+myAuto1.getMaxSpeed());
System.out.println();
Car myCar1=new Car("Ford", 200,"Mustang",2,false);
Car myCar2=new Car();
System.out.print(" - : ");
nazv=in.next();
myCar2.setFirm(nazv);
System.out.print(" : ");
s=in.nextInt();
myCar2.setMaxSpeed(s);
System.out.print(" : ");
nazv=in.next();
myCar2.setModel(nazv);
System.out.print(" - : ");
s=in.nextInt();
myCar2.setNumDoors(s);
System.out.print(" (true/false): ");
Boolean f=in.nextBoolean();
System.out.println();
System.out.println(" : "+myCar1.toString());
System.out.println(" : "+myCar2.toString());
Truck myTruck=new Truck();
myTruck.setAllInfo();
System.out.println(myTruck.toString());
}
}
:
: Lada
: 130
- : Lada 130
- : Nissan
: 230
: Patrol
- : 5
(true/false): true
10
, (
). , Garage (), -
:
import java.util.ArrayList;// ArrayList
public class GarageCar {
private ArrayList<Auto> masCar=new ArrayList<Auto>();//
public void addCar(Auto m){//
masCar.add(m);
}
public GarageCar (){
}
public Boolean findCar(Auto m){ // m
return masCar.contains(m);
}
public GarageCar(ArrayList< Auto> n){//
//
masCar=n;
}
public void printGarage() {
//
System.out.println(" : ");
for (Auto a:masCar){
//
System.out.println("\t"+a.toString());
}
}
}
ArrayList.
. .. , ArrayList.
ArrayList:
ArrayList< > _=new ArrayList< >();
ArrayList add( ).
ArrayList ( ,
void ):
contains(m): Boolean true, m, false
add (int index, m) : void m index
clear() : void
get(int index) : __ , index
indexOf(m) : int m, ,
11
Auto, .. Car,
Truck.
for, printGarage(), ,
:
for (Auto a:masCar){
System.out.println("\t"+a.toString());
}
(foreach). a Auto,
, masCar,
ArrayList, ..
. , ( ArrayList).
:
public class testGarage {
public static void main(String[] args) {
GarageCar myGarage=new GarageCar(); //
Car myCar1=new Car("Ford", 200,"Mustang",2,false); //
myGarage.addCar(myCar1); //
myGarage.addCar(new Car("LADA", 140, "Kalina", 4, false));//
Truck myTruck=new Truck("Dove",160,"DTS",700,true);//
myGarage.addCar(myTruck); //
myGarage.printGarage(); //
if (myGarage.findCar(myCar1)) { //
System.out.println("");
}
else {
System.out.println("");
}
}
}
:
:
Ford 200 Mustang 2 false
LADA 140 Kalina 4 false
: Dove
: 160
: DTS
: 700
: true
ArrayList. ,
, instanceof
, ..
I.
:
:
, Auto . .
II.
1.
( , ):
. . ,
.
( instanceof).
2. . . ,
.
( instanceof).
3. . . ,
.
( instanceof).
4. . . ,
. (
instanceof).
12
5. . . ,
. ( instanceof).
6. . -. ,
. - (
instanceof).
7. . . ,
.
( instanceof).
8. . . ,
.
( instanceof).
9. . . ,
. ( instanceof).
10. . . ,
.
( instanceof).
11. . . ,
. (
instanceof).
12. . . ,
. (
instanceof).
3. Java
javadoc.
Eclipse javadoc Java. javadoc
JDK Java Development Kit ( Java). html , .
/**, */
:
Javadoc
@author
@version
@since
, ,
,
@see
, ,
,
@param
@return
@exception
@throws
@deprecated
{@link reference}
, ,
,
{@value}
, Auto :
13
/**
* -
* @author ..
*/
public class Auto {
/** */
private String firm;
/** */
private int maxSpeed;
/**
* {@link Auto#firm}
* @param firma - */
public void setFirm(String firma){
firm=firma;
}
/**
* {@link Auto#maxSpeed}
* @param speed - */
public void setMaxSpeed(int speed){
maxSpeed=speed;
}
/**
* {@link Auto#maxSpeed}
*@return */
public int getMaxSpeed(){
return maxSpeed;
}
/**
* {@link Auto#firm}
*@return */
public String getFirm(){
return firm;
}
/**
* " " , 0*/
public Auto(){
firm=" ";
maxSpeed=0;
}
/**
*
* @param firma -
* @param speed - */
public Auto(String firma, int speed){
firm=firma;
maxSpeed=speed;
}
}
. 1. .
, .
14
html-,
Project\Generate Javadoc.
(. 2),
Javadoc
(
,
C:\Program
Files\Java\jdk1.6.0_27\bin\javadoc.exe)
( , ).
, Next Finish,
html- .
(. 3):
. 2. Project\Generate Javadoc
. 3. .
. 4. .
:
. . 2 .
4.
Java. Swing.
Java
(AWT, Swing, SWT .). Swing
GUI (Graphical User Interface ).
15
. Java
JFrame. :
// MyFrame.java
import javax.swing.*;
public class MyFrame {
public static void main(String s[]) {
JFrame frame = new JFrame("FrameDemo");// FrameDemo
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//
// , ,
frame.setSize(175,100);//
frame.setVisible(true);//
}
}
.
,
. Java :
BorderLayout (. . 5),
: , , ,
, ( , , , , ); ,
- ,
;
FlowLayout ,
( ),
,
( ).
. 5. BorderLayout.
;
GridLayout . .
, ;
BoxLayout . ,
Box, ;
CardLayout , ..
( ).
BorderLayout, ..
:
, , ,
.
, (,
..).
,
.
JPanel . ,
, ,
.
JButton .
JCheckBox -;
JComboBox ;
JLabel , ;
JList ;
JPasswordField ;
JProgressBar ;
JRadioButton , -, ButtonGroup;
JSlider , ;
JSpinner , ;
JTable ;
JTextField ;
JTextArea ;
JTree ( ).
16
, , :
import java.awt.*;
import java.util.ArrayList;
import javax.swing.*;
public class MyFrame {
public static void main(String[] args) {
JFrame frame = new JFrame("FrameDemo");// FrameDemo
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//
// , ,
frame.setSize(500,400);//
JPanel myPanel1=new JPanel();//
myPanel1.setLayout(new FlowLayout());//
myPanel1.add(new JButton(" 1"));//
// -, , html-
JButton myButton2 = new JButton
("<html><b><font color=\"red\" size=14> 2</font></b></html>");
// ,
Component horizontalStrut = Box.createHorizontalStrut(40);// 40
myPanel1.add(horizontalStrut);//
myPanel1.add(myButton2); //
Box myBox1=new Box(BoxLayout.Y_AXIS);// Box BoxLayout
// (BoxLayout.Y_AXIS)
myBox1.add(Box.createVerticalStrut(20)); //
myBox1.add(new JLabel("1"));//
myBox1.add(Box.createVerticalGlue());//
// ,
myBox1.add(new JLabel("2"));//
myBox1.add(Box.createVerticalGlue());//
myBox1.add(new JCheckBox(""));//
myBox1.add(Box.createVerticalStrut(20));//
ButtonGroup myGroup=new ButtonGroup(); // ,
JPanel myPanel2=new JPanel();//
//
ArrayList<JRadioButton> masRB=new ArrayList<JRadioButton>();
myPanel2.setLayout(new GridLayout(3,2));//
// 3 2
// , ,
for (int i=0;i<6;i++){
masRB.add(new JRadioButton(" "+i));//
//masRB.get(i) i-
myGroup.add(masRB.get(i));//
myPanel2.add(masRB.get(i));//
}
masRB.get(0).setSelected(true);// 0-
// BorderLayout
frame.add(myPanel1,BorderLayout.NORTH);
frame.add(myBox1,BorderLayout.WEST);
frame.add(new JTextArea(),BorderLayout.CENTER);//
//
frame.add(myPanel2,BorderLayout.EAST);
frame.add(new JTextField(),BorderLayout.SOUTH); //
//
frame.setVisible(true);//
frame.pack(); // , ,
//
17
frame.setMinimumSize(frame.getSize());//
}
}
:
import java.awt.*;
import java.util.ArrayList;
import javax.swing.*;
public class MyFrame {
public static void main(String[] args) {
JFrame frame = new JFrame("FrameDemo");// FrameDemo
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,400);//
setNorth(frame); //
setWest(frame); //
setEast(frame); //
setCenter(frame); //
setSouth(frame); //
frame.setVisible(true);//
frame.pack(); //
frame.setMinimumSize(frame.getSize());
}
public static void setNorth(JFrame fr){ //
JPanel myPanel1=new JPanel();
myPanel1.setLayout(new FlowLayout());
myPanel1.add(new JButton(" 1"));
JButton myButton2 = new JButton
("<html><b><font color=\"red\" size=14> 2</font></b></html>");
Component horizontalStrut = Box.createHorizontalStrut(40);
myPanel1.add(horizontalStrut);
myPanel1.add(myButton2);
fr.add(myPanel1,BorderLayout.NORTH);
}
public static void setWest(JFrame fr){ //
Box myBox1=new Box(BoxLayout.Y_AXIS);
myBox1.add(Box.createVerticalStrut(20));
myBox1.add(new JLabel("1"));
myBox1.add(Box.createVerticalGlue());
myBox1.add(new JLabel("2"));
myBox1.add(Box.createVerticalGlue());
myBox1.add(new JCheckBox(""));
myBox1.add(Box.createVerticalStrut(20));
fr.add(myBox1,BorderLayout.WEST);
}
public static void setEast(JFrame fr){ //
ButtonGroup myGroup=new ButtonGroup();
JPanel myPanel2=new JPanel();
ArrayList<JRadioButton> masRB=new ArrayList<JRadioButton>();
myPanel2.setLayout(new GridLayout(3,2));
for (int i=0;i<6;i++){
masRB.add(new JRadioButton(" "+i));
myGroup.add(masRB.get(i));
myPanel2.add(masRB.get(i));
}
masRB.get(0).setSelected(true);
fr.add(myPanel2,BorderLayout.EAST);
}
public static void setCenter(JFrame fr){ //
fr.add(new JTextArea(),BorderLayout.CENTER);
}
public static void setSouth(JFrame fr){ //
fr.add(new JTextField(),BorderLayout.SOUTH);
}
}
:
I.
:
18
, , ,
.
II.
( ).
( , 3,
):
1.
JSlider
2.
3.
JSlider
19
4.
5.
6.
20
5. Java.
Java -
(listeners). .., , , .
: 1 ; 2
. .
1. .
,
. 6. .
(. 6).
import
import
import
import
java.awt.BorderLayout;
java.awt.event.ActionEvent; //
java.awt.event.ActionListener; //-
javax.swing.*;
2. .
- (, ActionListener
). ,
actionPerformed, .
, ,
(. 7).
import
import
import
import
. 7.
( 2).
java.awt.BorderLayout;
java.awt.event.ActionEvent;
java.awt.event.ActionListener;
javax.swing.*;
ActionEvent ActionListener,
:
(
( implements)
import
java.awt.event.*)
)
(
ActionEvent
ActionListener
AdjustmentEvent
ComponentEvent
(
)
ContainerEvent
(
, ..
JFrame, JPanel,
JScrollPane,
JDialog,
JFileDialog )
FocusEvent
( )
actionPerformed()
, Enter
(
JButton, JList, JTextField)
AdjustmentListener adjustmentValueChanged()
JScrollbar
componentHidden()
ComponentListener
componentMoved()
componentResized()
componentShown()
componentAdded()
ContainerListener
componentRemoved()
FocusListener
focusGained()
focusLost()
ItemEvent
ItemListener
KeyEvent (
)
, ..
itemStateChanged()
keyPressed()
KeyListener
keyReleased()
keyTyped()
22
( JCheckbox, JList, JComboBox .,
Item)
MouseEvent
( )
MouseListener
mouseClicked()
mouseEntered()
mouseExited()
mousePressed()
mouseReleased()
mouseDragged()
(..
)
MouseMotionListener
mouseMoved()
TextEvent
( )
TextListener
textValueChanged()
WindowEvent
(
)
windowActivated()
windowClosed()
windowClosing()
WindowListener
( JTextArea,
JTextField)
(
, )
windowDeactivated()
windowDeiconified()
windowlconified()
()
windowOpened()
( )
-,
, , . , ,
:
1- , -
MouseListener.
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
public class myAction2 extends JFrame{
public JFrame myFrame;
. 8. .
public JButton myButton;
public JTextField myText1;
public JCheckBox myCheck;
public JRadioButton myRButton;
public static JLabel myLabel; //static ,
public static void main(String[] args) {
new myAction2();
}
public myAction2(){
myFrame=new JFrame("");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myButton=new JButton("1"); //
myCheck=new JCheckBox("2");
myRButton=new JRadioButton("3");
myText1=new JTextField();
myLabel=new JLabel(" ");
JPanel myPanel=new JPanel();
myPanel.add(myButton);
myPanel.add(myCheck);
myPanel.add(myRButton);
myButton.addMouseListener(new MyMouseListener());//
myCheck.addMouseListener(new MyMouseListener()); //
myRButton.addMouseListener(new MyMouseListener());// MyMouseListener
myText1.addMouseListener(new MyMouseListener());
myFrame.add(myText1,BorderLayout.NORTH);
23
myFrame.add(myPanel,BorderLayout.CENTER);
myFrame.add(myLabel,BorderLayout.SOUTH);//
myFrame.setMinimumSize(new Dimension(200,100));// 200 100
myFrame.setVisible(true);
}
}
class MyMouseListener implements MouseListener{// -,
// MouseListener
public void mouseClicked(MouseEvent e) { } // MouseListener,
//
public void mouseEntered(MouseEvent e) {
// myLabel myAction2, ,
// ,
myAction2.myLabel.setText(e.getComponent().getClass().toString());
}
//
public void mouseExited(MouseEvent e) { }
public void mousePressed(MouseEvent e) {
,
, .
2- , -
MouseAdapter.
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
public class myAction2 extends JFrame{
public JFrame myFrame;
public JButton myButton;
public JTextField myText1;
public JCheckBox myCheck;
public JRadioButton myRButton;
public static JLabel myLabel;
public static void main(String[] args) {
new myAction2();
}
public myAction2(){
myFrame=new JFrame("");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myButton=new JButton("1");
myCheck=new JCheckBox("2");
myRButton=new JRadioButton("3");
myText1=new JTextField();
myLabel=new JLabel(" ");
JPanel myPanel=new JPanel();
myPanel.add(myButton);
myPanel.add(myCheck);
myPanel.add(myRButton);
myButton.addMouseListener(new MyMouseAdapter());
myCheck.addMouseListener(new MyMouseAdapter());
myRButton.addMouseListener(new MyMouseAdapter());
myText1.addMouseListener(new MyMouseAdapter());
myFrame.add(myText1,BorderLayout.NORTH);
myFrame.add(myPanel,BorderLayout.CENTER);
myFrame.add(myLabel,BorderLayout.SOUTH);
myFrame.setMinimumSize(new Dimension(200,100));
myFrame.setVisible(true);
}
}
class MyMouseAdapter extends MouseAdapter{ // -,
//MouseAdapter,
public void mouseEntered(MouseEvent e) {
myAction2.myLabel.setText(e.getComponent().getClass().toString());
}
}
24
- , ,
Listener Adapter.
:
I.
:
- :
ChangeListener, MouseWheelListener.
II.
. . . 4
3 (, ,
, JSlider ,
Enter - ..).
!
6. , Java.
Java JMenuBar,
, .
JMenuItem, .
, setJMenuBar JFrame.
, ,
(. 9):
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
. 9. .
public class MyMenu extends JFrame implements ActionListener{
private JTextField myText;
public static void main(String[] args) {
new MyMenu(" ");//
}
public MyMenu(String name){// ,
super(name); // - JFrame
JMenuBar myMenuBar=new JMenuBar();//
JMenu menu1=new JMenu("1");//
JMenu first=new JMenu("1_1"); //
menu1.add(first);//
JMenuItem[] first_1=new JMenuItem[3];//
for (int i=0;i<3;i++){ // ,
first_1[i]=new JMenuItem("1_1_"+(i+1));
first.add(first_1[i]);
first_1[i].addActionListener(this);// ,
}
//
JMenu second=new JMenu("1_2"); //
menu1.add(second); //
JMenuItem[] second_1=new JMenuItem[3]; //
for (int i=0;i<3;i++){ // ..
second_1[i]=new JMenuItem("1_2_"+(i+1));
second.add(second_1[i]);
second_1[i].addActionListener(this);
}
JMenu menu2=new JMenu("2"); //
JMenu first2=new JMenu("2_1");
menu2.add(first2);
JMenuItem[] first2_1=new JMenuItem[3];
for (int i=0;i<3;i++){
first2_1[i]=new JMenuItem("2_1_"+(i+1));
first2.add(first2_1[i]);
first2_1[i].addActionListener(this);
}
JMenu second2=new JMenu("2_2");
menu2.add(second2);
JMenuItem[] second2_1=new JMenuItem[3];
25
Java ,
, Swing,
paintComponent. , ,
:
// JMyPanel.java
import java.awt.*;
import javax.swing.JPanel;
public class JMyPanel extends JPanel{ // JPanel
//
public static enum Figure {LINE,OVAL,RECT,ROUNDRECT,CLEAR};
private Figure vibor=Figure.CLEAR; //
// CLEAR
public JMyPanel() {
} //
public void ris(String s) {//,
// s (. MyGraph.java)
vibor=Figure.valueOf(s); //,
repaint(); // , .. paintComponent
}
public void paintComponent(Graphics gr){ // Graphics
super.paintComponent(gr); //
// Graphics
Graphics2D g = (Graphics2D)gr; // Graphics2D
// ()
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
switch (vibor){ // ris vibor
case LINE:
g.drawLine(20, 20, 100, 100); break; //
case OVAL:
g.drawOval(20, 20, 100, 100); break; //
case RECT:
g.drawRect(20, 20, 100, 100); break; //
case ROUNDRECT: g.drawRoundRect(20, 20, 100, 100,60,60); break; //
// , , ,
// 2
case CLEAR: g.clearRect(0, 0, getSize().width, getSize().height);break; //
}
}
}
enum .
.
, . LINE
0, OVAL 1, RECT 2, ROUNDRECT 3, CLEAR 4.
, ordinal(), , vibor.ordinal()
vibor (0, 1, 2, 3 4).
, toString().
vibor.toString() : LINE, OVAL, RECT, ROUNDRECT CLEAR.
(
).
26
paintComponent(Graphics gr)
. gr Graphics g
Graphics2D, . Graphics2D Graphics
, , , Graphics,
.
. ,
, , (. 10):
. 10. .
// MyGraph.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyGraph extends JFrame implements ActionListener{
private JMyPanel
myPanel=new JMyPanel();//
JMyPanel, paintComponent:
public void paintComponent(Graphics gr){
super.paintComponent(gr);
Graphics2D g = (Graphics2D)gr;
BasicStroke pen;// ,
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
switch (vibor){
case LINE:
// 20 ,
pen=new BasicStroke(20,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND);
27
g.setStroke(pen);//
g.setColor(Color.blue);//
g.drawLine(20, 20, 100, 100); break;
case OVAL:
// ,
// ,
// ; ;
float[] dash = {10, 30};
// 10 , , ,
// 10 , , ,
//,
pen=new BasicStroke(10,BasicStroke.CAP_SQUARE,BasicStroke.JOIN_ROUND,10, dash,0 );
g.setStroke(pen);
g.setColor(Color.red);
// , ,
//30, 30 , 50, 50 , true
//
g.setPaint(new GradientPaint(30, 30, Color.red, 50, 50, Color.green, true));
//g.fill , Graphics2D,
//
g.fill(new Ellipse2D.Double(20, 20, 100, 100)); break;
case RECT:
float[] dash2 = {20, 20};
pen=new BasicStroke(5,BasicStroke.CAP_SQUARE,BasicStroke.JOIN_BEVEL,1, dash2,0 );
g.setStroke(pen);
g.setColor(Color.magenta);
g.drawRect(20, 20, 100, 100); break;
case ROUNDRECT:
float[] dash3 = {20, 20,2,20,2,20};
pen=new BasicStroke(10,BasicStroke.CAP_ROUND,BasicStroke.JOIN_BEVEL,1, dash3,0 );
g.setStroke(pen);
g.setColor(Color.yellow);
g.drawRoundRect(20, 20, 100, 100,60,60); break;
case CLEAR: g.clearRect(0, 0, getSize().width, getSize().height);break;
}
}
:
I.
,
.
II.
, ( ).
28
. 11. .
.
Java .
:
29
( FileWriter FileReader),
;
(
BufferedWriter
BufferedReader),
;
;
:
try {
//
}
catch (IOException e1) {
e1.printStackTrace();
}
try,
() catch, .
. 12. .
( . 12):
Box myBox2=new Box(BoxLayout.X_AXIS); //
JButton button3=new JButton("...");//
myBox2.add(button3);
final FileDialog fdlg=new FileDialog(this, "");//
//
button3.addActionListener(new ActionListener() { //
public void actionPerformed(ActionEvent e) {
fdlg.setMode(FileDialog.SAVE); //
fdlg.setTitle(" "); //
fdlg.setVisible(true); //
FileWriter myWriter = null;// FileWriter null
try { //,
// FileWriter ,
//
myWriter=new FileWriter(fdlg.getDirectory()+fdlg.getFile());
// BufferedWriter, myWriter
BufferedWriter myBWriter=new BufferedWriter(myWriter);
for(int i=0;i<myListModel.getSize();i++){ //
myBWriter.write(""+myListModel.getElementAt(i));// BufferedWriter
myBWriter.newLine(); //
}
myBWriter.close();//
myWriter.close();
} catch (IOException e1) {
e1.printStackTrace(); // ,
}
}
});
myBox2.add(Box.createHorizontalGlue()); // ,
JButton button4=new JButton("...");//
button4.addActionListener(new ActionListener() { //
public void actionPerformed(ActionEvent e) {
fdlg.setMode(FileDialog.LOAD); //
fdlg.setTitle(" ");//
fdlg.setVisible(true); //
FileReader myReader = null;
try { //,
// FileReader ,
//
myWriter=new FileWriter(fdlg.getDirectory()+fdlg.getFile());
30
myReader=new FileReader(fdlg.getDirectory()+fdlg.getFile());
myListModel.clear(); // , ..
// BufferedReader, myReader
BufferedReader myBReader=new BufferedReader(myReader);
String s; //
// s , ( ,
// ), s
while ((s=myBReader.readLine())!=null){
myListModel.addElement(s);
}
myBReader.close();//
myReader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
myBox2.add(button4);//
add(myBox2,BorderLayout.SOUTH);//
, .
. ,
. , ,
:
JPanel panel1=null;
private static Image image;
static File f1;
:
myList.addListSelectionListener(new ListSelectionListener() {//
public void valueChanged(ListSelectionEvent e) {
JList tempList=(JList)e.getSource();// , ,
//
f1=new File(tempList.getSelectedValue().toString()+".jpg"); // f1
// jpg (
// - ),
//,
try { //
image=ImageIO.read(f1); // Image
loadImage(image); //
} catch (IOException e1) {//
showDialog(); //
panel1.repaint(); //
}
}
});
:
panel1=new JPanel();
Box centerBox=new Box(BoxLayout.X_AXIS); //
centerBox.add(myScroll); //
centerBox.add(panel1); //
add(centerBox,BorderLayout.CENTER); //
:
public void loadImage(Image im){ //
Graphics2D g = (Graphics2D)panel1.getGraphics(); //
g.drawImage(im, 0, 0, null); //
}
public void showDialog(){ //
JDialog myDialog=new JDialog(); //
myDialog.setModal(true); // , .. ,
//
myDialog.add(new JLabel("No file!!!")); //
myDialog.pack(); //
//
myDialog.setLocation(getLocation().x+getWidth()/2, getLocation().y+getHeight()/2);
myDialog.setVisible(true);//
}
31
. 13. , .
, .
, - .
HashMap. <,
>. .. . ,
<, >:
import java.util.HashMap;
public class SampleHash {
public static void main(String[] args) {
// HashMap,
HashMap<String, String> myHash=new HashMap<String, String>();
myHash.put("", "891234567"); //
myHash.put("", "892233345"); //
myHash.put("", "893137567"); //
System.out.println(myHash); //
System.out.println(myHash.get("")); // ,
}
}
:
{=891234567, =892233345, =893137567}
891234567
, ( JPopupMenu) HashMap (. 14):
. 14. .
2
private static HashMap<String, String> myHash=new HashMap<String, String>(); // HashMap
static JPopupMenu myPopup; //
myPopup=new JPopupMenu(); //
JMenuItem myItem1=new JMenuItem(" "); //
myItem1.addActionListener(new ActionListener() { //
public void actionPerformed(ActionEvent e) {
loadFromFile(myList.getSelectedValue().toString()); // , ,
//
}
});
myPopup.add(myItem1); //
myList.setComponentPopupMenu(myPopup); //
myList.addMouseListener(new MouseAdapter() { //
public void mousePressed(MouseEvent e) { //
32
myList.setSelectedIndex(myList.locationToIndex(e.getPoint())); //
// ,
}
});
myList.addListSelectionListener:
myList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
// path , myHash
String path=myHash.get(myList.getSelectedValue().toString());
loadImage(path); // loadImage
}
});
loadImage:
public void loadImage(String path){
try {
if (path!=null) { //
f1=new File(path); //
image=ImageIO.read(f1); //
Graphics2D g = (Graphics2D)panel1.getGraphics(); //
g.setColor(panel1.getBackground()); //
g.clearRect(0, 0, panel1.getWidth(), panel1.getHeight()); // ,
//
g.drawImage(image, 0, 0, null); //
} else throw new IOException(); //
catch (IOException e1) { // ,
panel1.repaint(); //
}
}
loadFromFile,
, myHash
:
public void loadFromFile(String s){
FileDialog fdlg=new FileDialog(this, " ",FileDialog.LOAD);
fdlg.setFile("*.jpg"); // *.jpg
fdlg.setVisible(true);
myHash.put(s, fdlg.getDirectory()+fdlg.getFile()); // myHash
//
loadImage(fdlg.getDirectory()+fdlg.getFile());//
}
:
import
import
import
import
java.awt.*;
java.awt.event.*;
java.io.*;
java.util.HashMap;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.*;
public class ListWithHashPopUp extends JFrame{
JPanel panel1=null;
private static Image image;
static File f1;
private static HashMap<String, String> myHash=new HashMap<String, String>();
static JPopupMenu myPopup;
public static void main(String[] args) {
ListWithHashPopUp window= new ListWithHashPopUp(" ");
window.setVisible(true);
window.pack();
window.setMinimumSize(window.getSize());
}
public ListWithHashPopUp(String s){
super(s);
final DefaultListModel myListModel = new DefaultListModel();
for (int i=0;i<10;i++){
myListModel.addElement(""+i);
}
final JList myList=new JList();
JScrollPane myScroll = new JScrollPane(myList);
33
myList.setModel(myListModel);
myPopup=new JPopupMenu();
JMenuItem myItem1=new JMenuItem(" ");
myItem1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
loadFromFile(myList.getSelectedValue().toString());
}
});
myPopup.add(myItem1);
myList.setComponentPopupMenu(myPopup);
myList.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
myList.setSelectedIndex(myList.locationToIndex(e.getPoint()));
}
});
myList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
String path=myHash.get(myList.getSelectedValue().toString());
loadImage(path);
}
});
Box myBox1=new Box(BoxLayout.Y_AXIS);
final JTextField myText=new JTextField();
myBox1.add(myText);
Box box1=new Box(BoxLayout.X_AXIS);
JButton button1=new JButton(" ");
box1.add(button1);
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
myListModel.addElement(myText.getText());
}
});
JButton button2=new JButton(" ");
button2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
while (myListModel.contains(myText.getText())){
myListModel.removeElement(myText.getText());
}
}
});
box1.add(button2);
JButton buttonClear=new JButton(" ");
buttonClear.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
myListModel.clear();
}
});
box1.add(buttonClear);
myBox1.add(box1);
panel1=new JPanel();
Box centerBox=new Box(BoxLayout.X_AXIS);
centerBox.add(myScroll);
centerBox.add(panel1);
add(centerBox,BorderLayout.CENTER);
add(myBox1,BorderLayout.NORTH);
}
public void loadImage(String path){
try {
if (path!=null) {
f1=new File(path);
image=ImageIO.read(f1);
Graphics2D g = (Graphics2D)panel1.getGraphics();
g.setColor(panel1.getBackground());
g.clearRect(0, 0, panel1.getWidth(), panel1.getHeight());
g.drawImage(image, 0, 0, null);
}
34
Eclipse, ,
Java . jar- (
exe-). :
,
, main,
(
Browse).
Finish ,
, .
.
:
I.
, , ,
(, ). HashMap, .
II.
jar- , 4-.
35