76
1 Grafika 2D

Grafika - Ostravská univerzitahunka/vyuka/javaOOP/obop2/jvcv07/Grafika.pdf · Grafika 2D. 2 Obsah 1. Příklad uživatelského formuláře 2. Úvod 3. Metody paint() repaint() 4

  • Upload
    others

  • View
    22

  • Download
    0

Embed Size (px)

Citation preview

1

Grafika 2D

2

Obsah

1. Příklad uživatelského formuláře

2. Úvod

3. Metody paint() repaint()

4. Práce s barvami

5. Práce s fonty

6. Správa fontů – metriky fontů

7. Kresleníčar, obdélníků a oválů

8. Kreslení výsečí

9. Kreslení polygonů a lomených čar

10. Třída JTable

3

1. Příklad uživatelského formuláře

• Do formuláře je možné zadat celkem 4 různé typy údajů– JList – vybrat jméno ze seznamu (státu)

– JTextField – jméno a email

– JRadioButton – indikace svobodný / ženatý, vdaný

– JTextArea – oblast pro poznámky

– JButton – tlačítka

– JPanel – pro rozvržení komponent

4

Příklad uživatelského formuláře

• Třída MiscGUI implementuje rozhraníActionListener pro svá tři tlačítka

• rozvržení okna: BorderLayout –top, left, bottomoblasti jsou obsazeny s JPanelcenter– komponenta JTextArea – víceřádkový editor

• top - tlačítka:– JPanel má rozvržení FlowLayout

• left – JLabel, JList– JPanel má rozvržení BoxLayout, JList zapouzdřuje

tzv. výběrový model

5

Příklad uživatelského formuláře

6

Příklad uživatelského formuláře

• Bottom – JTextFields a JRadioButton– JPanel má rozvržení FlowLayout

– JTextField jméno, email

• Center – JTextArea– textová oblast pro zápis komentáře

Osnova

7

import import import import javaxjavaxjavaxjavax.swing.*;.swing.*;.swing.*;.swing.*;

import import import import javajavajavajava....awtawtawtawt.*;.*;.*;.*;

import import import import javajavajavajava....awtawtawtawt....eventeventeventevent.*;.*;.*;.*;

classclassclassclass MaceGUIMaceGUIMaceGUIMaceGUI extendsextendsextendsextends JFrameJFrameJFrameJFrame implementsimplementsimplementsimplements ActionListenerActionListenerActionListenerActionListener {{{{

private private private private ContainerContainerContainerContainer pane;pane;pane;pane;

private private private private JPanelJPanelJPanelJPanel buttonsbuttonsbuttonsbuttons, , , , miscmiscmiscmisc, , , , stListstListstListstList;;;;

private private private private JListJListJListJList list;list;list;list;

private private private private JRadioButtonJRadioButtonJRadioButtonJRadioButton marriedmarriedmarriedmarried;;;;

private private private private JTextFieldJTextFieldJTextFieldJTextField email, email, email, email, namenamenamename;;;;

private private private private JTextAreaJTextAreaJTextAreaJTextArea reasonsreasonsreasonsreasons;;;;

////////tridnitridnitridnitridni atributyatributyatributyatributy

private private private private finalfinalfinalfinal static static static static StringStringStringString submitsubmitsubmitsubmit = " = " = " = " SubmitSubmitSubmitSubmit ";";";";

private private private private finalfinalfinalfinal static static static static StringStringStringString clearclearclearclear = " = " = " = " ClearClearClearClear ";";";";

private private private private finalfinalfinalfinal static static static static StringStringStringString exit = " Exit ";exit = " Exit ";exit = " Exit ";exit = " Exit ";

private private private private finalfinalfinalfinal static static static static StringStringStringString promptNpromptNpromptNpromptN = = = =

""""FirstFirstFirstFirst andandandand lastlastlastlast namenamenamename ";";";";

private private private private finalfinalfinalfinal static static static static StringStringStringString promptEpromptEpromptEpromptE = = = =

"E"E"E"E----mail mail mail mail addressaddressaddressaddress ";";";";

private private private private finalfinalfinalfinal static static static static StringStringStringString promptRpromptRpromptRpromptR = = = =

" My charisma " My charisma " My charisma " My charisma needsneedsneedsneeds enhancementenhancementenhancementenhancement becausebecausebecausebecause";";";";

private private private private finalfinalfinalfinal static static static static StringStringStringString[ ] [ ] [ ] [ ] statesstatesstatesstates = = = =

{ "{ "{ "{ "IllinoisIllinoisIllinoisIllinois", "", "", "", "IndianaIndianaIndianaIndiana", "", "", "", "IowaIowaIowaIowa", "Kansas", "Minnesota", ", "Kansas", "Minnesota", ", "Kansas", "Minnesota", ", "Kansas", "Minnesota",

"Michigan", ""Michigan", ""Michigan", ""Michigan", "MissouriMissouriMissouriMissouri", "", "", "", "NebraskaNebraskaNebraskaNebraska", "Ohio", "", "Ohio", "", "Ohio", "", "Ohio", "WisconsinWisconsinWisconsinWisconsin" };" };" };" };

Osnova

8

public public public public MaceGUIMaceGUIMaceGUIMaceGUI() {() {() {() {

super( "super( "super( "super( "MidwestMidwestMidwestMidwest AssociationAssociationAssociationAssociation forforforfor Charisma Charisma Charisma Charisma EnhancementEnhancementEnhancementEnhancement" );" );" );" );

pane = pane = pane = pane = getContentPanegetContentPanegetContentPanegetContentPane();();();();

buttonsbuttonsbuttonsbuttons = = = = newnewnewnew JPanelJPanelJPanelJPanel( ( ( ( newnewnewnew FlowLayoutFlowLayoutFlowLayoutFlowLayout() );() );() );() );

miscmiscmiscmisc = = = = newnewnewnew JPanelJPanelJPanelJPanel( ( ( ( newnewnewnew FlowLayoutFlowLayoutFlowLayoutFlowLayout() );() );() );() );

stListstListstListstList = = = = newnewnewnew JPanelJPanelJPanelJPanel();();();();

marriedmarriedmarriedmarried = = = = newnewnewnew JRadioButtonJRadioButtonJRadioButtonJRadioButton( "( "( "( "MarriedMarriedMarriedMarried", ", ", ", falsefalsefalsefalse ););););

email = email = email = email = newnewnewnew JTextFieldJTextFieldJTextFieldJTextField( ( ( ( promptEpromptEpromptEpromptE ););););

namenamenamename = = = = newnewnewnew JTextFieldJTextFieldJTextFieldJTextField( ( ( ( promptNpromptNpromptNpromptN ););););

reasonsreasonsreasonsreasons = = = = newnewnewnew JTextAreaJTextAreaJTextAreaJTextArea( ( ( ( promptRpromptRpromptRpromptR ););););

list = list = list = list = newnewnewnew JListJListJListJList( ( ( ( statesstatesstatesstates ); //** ); //** ); //** ); //** MidwestMidwestMidwestMidwest statestatestatestate namesnamesnamesnames

initinitinitinit(); (); (); ();

setVisiblesetVisiblesetVisiblesetVisible( ( ( ( truetruetruetrue ););););

setDefaultCloseOperationsetDefaultCloseOperationsetDefaultCloseOperationsetDefaultCloseOperation( ( ( ( JFrameJFrameJFrameJFrame.EXIT_ON_CLOSE );.EXIT_ON_CLOSE );.EXIT_ON_CLOSE );.EXIT_ON_CLOSE );

}}}}

public public public public voidvoidvoidvoid actionPerformedactionPerformedactionPerformedactionPerformed( ( ( ( ActionEventActionEventActionEventActionEvent e ) {e ) {e ) {e ) {

StringStringStringString cmdcmdcmdcmd = e.= e.= e.= e.getActionCommandgetActionCommandgetActionCommandgetActionCommand();();();();

ifififif ( ( ( ( cmdcmdcmdcmd....equalsequalsequalsequals( ( ( ( submitsubmitsubmitsubmit ) )) )) )) )

submitFormsubmitFormsubmitFormsubmitForm();();();();

elseelseelseelse ifififif ( ( ( ( cmdcmdcmdcmd....equalsequalsequalsequals( ( ( ( clearclearclearclear ) )) )) )) )

clearFormclearFormclearFormclearForm();();();();

elseelseelseelse ifififif ( ( ( ( cmdcmdcmdcmd....equalsequalsequalsequals( exit ) )( exit ) )( exit ) )( exit ) )

SystemSystemSystemSystem.exit( 0 );.exit( 0 );.exit( 0 );.exit( 0 );

}}}}

Osnova

9

private private private private voidvoidvoidvoid submitFormsubmitFormsubmitFormsubmitForm() {() {() {() {

StringStringStringString t = (list.t = (list.t = (list.t = (list.getSelectedValuegetSelectedValuegetSelectedValuegetSelectedValue() == () == () == () == nullnullnullnull) ? ") ? ") ? ") ? "nonenonenonenone" : " : " : " :

list.list.list.list.getSelectedValuegetSelectedValuegetSelectedValuegetSelectedValue().().().().toStringtoStringtoStringtoString();();();();

post( post( post( post( namenamenamename....getTextgetTextgetTextgetText(), email.(), email.(), email.(), email.getTextgetTextgetTextgetText(), t,(), t,(), t,(), t,

((((marriedmarriedmarriedmarried....isSelectedisSelectedisSelectedisSelected()) ? "()) ? "()) ? "()) ? "marriedmarriedmarriedmarried" : "not " : "not " : "not " : "not mariedmariedmariedmaried", ", ", ",

reasonsreasonsreasonsreasons....getTextgetTextgetTextgetText() ); () ); () ); () );

}}}}

private private private private voidvoidvoidvoid clearFormclearFormclearFormclearForm() {() {() {() {

reasonsreasonsreasonsreasons....setTextsetTextsetTextsetText( ( ( ( promptRpromptRpromptRpromptR ););););

namenamenamename....setTextsetTextsetTextsetText( ( ( ( promptNpromptNpromptNpromptN ););););

email.email.email.email.setTextsetTextsetTextsetText( ( ( ( promptEpromptEpromptEpromptE ););););

marriedmarriedmarriedmarried....setSelectedsetSelectedsetSelectedsetSelected( ( ( ( falsefalsefalsefalse ););););

list.list.list.list.getSelectionModelgetSelectionModelgetSelectionModelgetSelectionModel().().().().clearSelectionclearSelectionclearSelectionclearSelection();();();();

}}}}

//*** //*** //*** //*** ForForForFor nownownownow, a , a , a , a stubstubstubstub functionfunctionfunctionfunction thatthatthatthat printsprintsprintsprints to to to to thethethethe standard standard standard standard errorerrorerrorerror....

private private private private voidvoidvoidvoid post( post( post( post( StringStringStringString n, n, n, n, StringStringStringString e, e, e, e, StringStringStringString s, s, s, s,

StringStringStringString m, m, m, m, StringStringStringString r ) {r ) {r ) {r ) {

SystemSystemSystemSystem....errerrerrerr....printlnprintlnprintlnprintln( n + " " + e + " " + s + "( n + " " + e + " " + s + "( n + " " + e + " " + s + "( n + " " + e + " " + s + "\\\\n" + m + "n" + m + "n" + m + "n" + m + "\\\\n" + r );n" + r );n" + r );n" + r );

}}}}

private private private private voidvoidvoidvoid initinitinitinit() {() {() {() {

JLabelJLabelJLabelJLabel j;j;j;j;

Font f = Font f = Font f = Font f = nullnullnullnull;;;;

pane.pane.pane.pane.setLayoutsetLayoutsetLayoutsetLayout( ( ( ( newnewnewnew BorderLayoutBorderLayoutBorderLayoutBorderLayout() );() );() );() );

buttonsbuttonsbuttonsbuttons....setBackgroundsetBackgroundsetBackgroundsetBackground( ( ( ( ColorColorColorColor....graygraygraygray ););););

email.email.email.email.setFontsetFontsetFontsetFont( f = ( f = ( f = ( f = newnewnewnew Font( "Dialog", Font.BOLD, 12 ) );Font( "Dialog", Font.BOLD, 12 ) );Font( "Dialog", Font.BOLD, 12 ) );Font( "Dialog", Font.BOLD, 12 ) );

namenamenamename....setFontsetFontsetFontsetFont( f );( f );( f );( f );

reasonsreasonsreasonsreasons....setFontsetFontsetFontsetFont( f );( f );( f );( f );

Osnova

10

reasonsreasonsreasonsreasons....setLineWrapsetLineWrapsetLineWrapsetLineWrap( ( ( ( truetruetruetrue ););););

miscmiscmiscmisc....addaddaddadd( ( ( ( namenamenamename ); ); ); ); miscmiscmiscmisc....addaddaddadd( email ); ( email ); ( email ); ( email ); miscmiscmiscmisc....addaddaddadd( ( ( ( marriedmarriedmarriedmarried ););););

list.list.list.list.setFontsetFontsetFontsetFont( f );( f );( f );( f );

list.list.list.list.setBackgroundsetBackgroundsetBackgroundsetBackground( ( ( ( ColorColorColorColor....cyancyancyancyan ););););

list.list.list.list.getSelectionModelgetSelectionModelgetSelectionModelgetSelectionModel().().().().setSelectionModesetSelectionModesetSelectionModesetSelectionMode( ( ( (

ListSelectionModelListSelectionModelListSelectionModelListSelectionModel.SINGLE_SELECTION );.SINGLE_SELECTION );.SINGLE_SELECTION );.SINGLE_SELECTION );

stListstListstListstList....setLayoutsetLayoutsetLayoutsetLayout( ( ( ( newnewnewnew BoxLayoutBoxLayoutBoxLayoutBoxLayout( ( ( ( stListstListstListstList, , , , BoxLayoutBoxLayoutBoxLayoutBoxLayout.Y_AXIS ) );.Y_AXIS ) );.Y_AXIS ) );.Y_AXIS ) );

stListstListstListstList....addaddaddadd( j = ( j = ( j = ( j = newnewnewnew JLabelJLabelJLabelJLabel( "( "( "( "HomeHomeHomeHome statestatestatestate " ) );" ) );" ) );" ) );

j.j.j.j.setFontsetFontsetFontsetFont( f );( f );( f );( f );

j.j.j.j.setForegroundsetForegroundsetForegroundsetForeground( ( ( ( ColorColorColorColor....blackblackblackblack ););););

stListstListstListstList....addaddaddadd( list );( list );( list );( list );

addButtonaddButtonaddButtonaddButton( ( ( ( submitsubmitsubmitsubmit ); ); ); ); addButtonaddButtonaddButtonaddButton( ( ( ( clearclearclearclear ); ); ); ); addButtonaddButtonaddButtonaddButton( exit );( exit );( exit );( exit );

pane.pane.pane.pane.addaddaddadd( ( ( ( buttonsbuttonsbuttonsbuttons, , , , BorderLayoutBorderLayoutBorderLayoutBorderLayout.NORTH );.NORTH );.NORTH );.NORTH );

pane.pane.pane.pane.addaddaddadd( ( ( ( reasonsreasonsreasonsreasons, , , , BorderLayoutBorderLayoutBorderLayoutBorderLayout.CENTER );.CENTER );.CENTER );.CENTER );

pane.pane.pane.pane.addaddaddadd( ( ( ( stListstListstListstList, , , , BorderLayoutBorderLayoutBorderLayoutBorderLayout.WEST );.WEST );.WEST );.WEST );

pane.pane.pane.pane.addaddaddadd( ( ( ( miscmiscmiscmisc, , , , BorderLayoutBorderLayoutBorderLayoutBorderLayout.SOUTH );.SOUTH );.SOUTH );.SOUTH );

packpackpackpack();();();();

}}}}

private private private private voidvoidvoidvoid addButtonaddButtonaddButtonaddButton( ( ( ( StringStringStringString namenamenamename ) {) {) {) {

JButtonJButtonJButtonJButton b = b = b = b = newnewnewnew JButtonJButtonJButtonJButton( ( ( ( namenamenamename ););););

b.b.b.b.setFontsetFontsetFontsetFont( ( ( ( newnewnewnew Font( "Dialog", Font.BOLD, 14 ) );Font( "Dialog", Font.BOLD, 14 ) );Font( "Dialog", Font.BOLD, 14 ) );Font( "Dialog", Font.BOLD, 14 ) );

b.b.b.b.addActionListeneraddActionListeneraddActionListeneraddActionListener( ( ( ( thisthisthisthis ); ); ); );

buttonsbuttonsbuttonsbuttons....addaddaddadd( b ); ( b ); ( b ); ( b );

}}}}

}}}}

Osnova

11

class class class class MaceGUITesterMaceGUITesterMaceGUITesterMaceGUITester {{{{

public static void main( String[ ] public static void main( String[ ] public static void main( String[ ] public static void main( String[ ] argsargsargsargs ) {) {) {) {

new new new new MaceGUIMaceGUIMaceGUIMaceGUI();();();();

}}}}

}}}}

12

2. ÚvodTřídy a rozhraní 2D grafiky

Classes and interfaces from the Java2D API that appear in package java.awt

Object

Color

Component

Font

FontMetrics

Graphics

Polygon

Graphics2D interface java.awt.Paint

interface java.awt.Shape

interface java.awt.Stroke

Classes from the Java2D API that appear in package java.awt.geom

GradientPaint

BasicStroke

TexturePaint

RectangularShape

GeneralPath

Line2D

RoundRectangle2D

Arc2D

Ellipse2D

Rectangle2D

13

Úvod

• Souřadnicový systém Javy– Schéma pro identifikaci všech bodů na obrazovce

– Levý horní roh - souřadnice (0,0)

– Bod složen z x a y souřadnice

14

Systém souřadnic – měří se v pixlech

X a xis

Y a xis

(0, 0)

(x, y)

+x

+y

15

3. Metody Paint() Repaint()

• Když se má komponenta poprvé objevit v okně, musí být nakreslena – metoda paint()

• Metoda paint() je součástí třídy Component – ta očekává argument typu Graphics

• Abstraktním třída Graphics je nadtřídou pro třídy grafického kontextu – mají informace pro kreslení

• Později – požadavek na znovu nakresleníkomponenty (repaint())– např. drawString() –řetězec může být překreslen

jiným řetězcem

16

Metody Paint() Repaint()

• Programátor může při repaint() opět zavolat metodu paint(), ale:

– metoda repaint() – neočekává žádnéargumenty a volá metodu update() s odpovídajícím grafickým kontextem a metoda update() volá metodu paint()

– každá komponenta má dvojici metod validate(), invalidate() – jenž mohou být vyvolány, k zabezpečení změn ve vlastnostech (atributech) komponenty – viz následující příklad metoda actionPerformed()

Osnova

17

import import import import javaxjavaxjavaxjavax.swing.*;.swing.*;.swing.*;.swing.*;

import import import import javajavajavajava....awtawtawtawt.*;.*;.*;.*;

import import import import javajavajavajava....awtawtawtawt....eventeventeventevent.*;.*;.*;.*;

classclassclassclass OneButtonOneButtonOneButtonOneButton extendsextendsextendsextends JFrameJFrameJFrameJFrame {{{{

private private private private ContainerContainerContainerContainer c;c;c;c;

private private private private JButtonJButtonJButtonJButton b;b;b;b;

private private private private StringStringStringString msg1, msg2, msg1, msg2, msg1, msg2, msg1, msg2, displayedMsgdisplayedMsgdisplayedMsgdisplayedMsg;;;;

private private private private ColorColorColorColor fillColorfillColorfillColorfillColor = = = = ColorColorColorColor....whitewhitewhitewhite;;;;

private private private private booleanbooleanbooleanboolean toggletoggletoggletoggle;;;;

private Font f;private Font f;private Font f;private Font f;

private private private private intintintint countcountcountcount;;;;

public public public public OneButtonOneButtonOneButtonOneButton() {() {() {() {

super( "Repaint super( "Repaint super( "Repaint super( "Repaint ExampleExampleExampleExample" );" );" );" );

c = c = c = c = getContentPanegetContentPanegetContentPanegetContentPane();();();();

displayedMsgdisplayedMsgdisplayedMsgdisplayedMsg = msg1 = "= msg1 = "= msg1 = "= msg1 = "HelloHelloHelloHello, , , , worldworldworldworld!";!";!";!";

msg2 = "msg2 = "msg2 = "msg2 = "WhatWhatWhatWhat, , , , memememe worryworryworryworry?";?";?";?";

b = b = b = b = newnewnewnew JButtonJButtonJButtonJButton( " ( " ( " ( " ToggleToggleToggleToggle " );" );" );" );

b.b.b.b.addActionListeneraddActionListeneraddActionListeneraddActionListener( ( ( ( newnewnewnew ActionListenerActionListenerActionListenerActionListener() {() {() {() {

public public public public voidvoidvoidvoid actionPerformedactionPerformedactionPerformedactionPerformed( ( ( ( ActionEventActionEventActionEventActionEvent e ) {e ) {e ) {e ) {

displayedMsgdisplayedMsgdisplayedMsgdisplayedMsg = (= (= (= (toggletoggletoggletoggle) ? msg1 : msg2;) ? msg1 : msg2;) ? msg1 : msg2;) ? msg1 : msg2;

fillColorfillColorfillColorfillColor = (= (= (= (toggletoggletoggletoggle) ? ) ? ) ? ) ? ColorColorColorColor....whitewhitewhitewhite : : : : ColorColorColorColor....cyancyancyancyan;;;;

toggletoggletoggletoggle = != != != !toggletoggletoggletoggle;;;;

repaint();repaint();repaint();repaint(); // // // // vyvolavyvolavyvolavyvola update, update, update, update, cozcozcozcoz vyvolavyvolavyvolavyvola paintpaintpaintpaint

ifififif(++(++(++(++countcountcountcount > 4){> 4){> 4){> 4){

c.c.c.c.addaddaddadd((((newnewnewnew JLabelJLabelJLabelJLabel("("("("WowWowWowWow!"));!"));!"));!"));

c.c.c.c.validatevalidatevalidatevalidate();();();();

countcountcountcount = 0;= 0;= 0;= 0;

}}}}

} } );} } );} } );} } );

Osnova

18

c.c.c.c.setLayoutsetLayoutsetLayoutsetLayout( ( ( ( newnewnewnew FlowLayoutFlowLayoutFlowLayoutFlowLayout() );() );() );() );

c.c.c.c.addaddaddadd( b ); ( b ); ( b ); ( b );

setDefaultCloseOperationsetDefaultCloseOperationsetDefaultCloseOperationsetDefaultCloseOperation( ( ( ( JFrameJFrameJFrameJFrame.EXIT_ON_CLOSE );.EXIT_ON_CLOSE );.EXIT_ON_CLOSE );.EXIT_ON_CLOSE );

c.c.c.c.setFontsetFontsetFontsetFont( f = ( f = ( f = ( f = newnewnewnew Font( "Dialog", Font.BOLD, 14 ) );Font( "Dialog", Font.BOLD, 14 ) );Font( "Dialog", Font.BOLD, 14 ) );Font( "Dialog", Font.BOLD, 14 ) );

setSizesetSizesetSizesetSize( 300, 200 );( 300, 200 );( 300, 200 );( 300, 200 );

setVisiblesetVisiblesetVisiblesetVisible( ( ( ( truetruetruetrue ););););

}}}}

public public public public voidvoidvoidvoid paintpaintpaintpaint( ( ( ( GraphicsGraphicsGraphicsGraphics g )g )g )g ) {{{{

super.super.super.super.paintpaintpaintpaint( g ); // ( g ); // ( g ); // ( g ); // vymazevymazevymazevymaze panepanepanepane

g.draw3DRect( 50, 70, 150, 70, g.draw3DRect( 50, 70, 150, 70, g.draw3DRect( 50, 70, 150, 70, g.draw3DRect( 50, 70, 150, 70, truetruetruetrue ););););

g.g.g.g.setColorsetColorsetColorsetColor( ( ( ( fillColorfillColorfillColorfillColor ););););

g.fill3DRect( 50, 70, 150, 70, g.fill3DRect( 50, 70, 150, 70, g.fill3DRect( 50, 70, 150, 70, g.fill3DRect( 50, 70, 150, 70, truetruetruetrue ););););

g.g.g.g.setColorsetColorsetColorsetColor( ( ( ( ColorColorColorColor....blackblackblackblack ););););

g.g.g.g.setFontsetFontsetFontsetFont( f ); ( f ); ( f ); ( f );

g.g.g.g.drawStringdrawStringdrawStringdrawString( ( ( ( displayedMsgdisplayedMsgdisplayedMsgdisplayedMsg, 70, 100 ); , 70, 100 ); , 70, 100 ); , 70, 100 );

}}}}

}}}}

Osnova

19

classclassclassclass OneButtonTesterOneButtonTesterOneButtonTesterOneButtonTester {{{{

public static public static public static public static voidvoidvoidvoid mainmainmainmain( ( ( ( StringStringStringString[ ] [ ] [ ] [ ] argsargsargsargs ) {) {) {) {

newnewnewnew OneButtonOneButtonOneButtonOneButton();();();();

}}}}

}}}}

20

Metoda validate()

• Poté co je přidaný JLabel objekt do kontejneru, metoda kontejneru validate() zabezpečí, že nověpřidaný objekt návěští je uspořádán a zobrazen správným způsobem.

• Metoda invalidate() signalizuje, že se nějakým způsobem změnila komponenta, což má dopad na zobrazení. Např. font tlačítka se zvětšil a text jižnevejde do vymezeného prostoru – indikace že je nutné překreslení.

• Metoda invalidate() je obyčejně volána automaticky, když mají změny dopad na zobrazení

21

4. Práce s barvami

• Třída Color– Definuje metody a konstanty pro práci s barvami

– Barvy jsou tvořeny komponentami red, green a blue

• RGB hodnoty

22

Grafické konstanty a jejich RGB hodnoty

CCCCoooolllloooorrrr konstanty Color RGB hodnota public final static Color ORANGE orange 255, 200, 0 public final static Color PINK pink 255, 175, 175

public final static Color CYAN cyan 0, 255, 255

public final static Color MAGENTA magenta 255, 0, 255

public final static Color YELLOW yellow 255, 255, 0

public final static Color BLACK black 0, 0, 0

public final static Color WHITE white 255, 255, 255

public final static Color GRAY gray 128, 128, 128

public final static Color LIGHT_GRAY light gray 192, 192, 192

public final static Color DARK_GRAY dark gray 64, 64, 64

public final static Color RED red 255, 0, 0

public final static Color GREEN green 0, 255, 0

public final static Color BLUE blue 0, 0, 255

23

Metody třídy ColorMetody Popis Konstanty Color a metody

public Color( int r, int g, int b )

Vytvoří barvu (Color) založenou na komponentách red, green a blue vyjádřené jako celé číslo v rozsahu od 0 do 255.

public Color( float r, float g, float b )

Vytvoří barvu založenou na komponentách red, green a blue vyjádřené jako floating-point hodnoty od 0.0 do 1.0.

public int getRed() Vrací hodnotu mezi 0 a 255 reprezentující obsah červené.

public int getGreen()

Vrací hodnotu mezi 0 a 255 reprezentující obsah zelené.

public int getBlue() Vrací hodnotu mezi 0 a 255 reprezentující obsah modré.

Methody Graphics pro práci s Colors

public Color getColor()

Vrací objekt třídy Color reprezentující aktuální barvu pro grafický kontext.

public void setColor( Color c )

Nastavuje aktuální barvu pro kresleni s grafickým kontextem.

Osnova

24

// // // // DemonstratingDemonstratingDemonstratingDemonstrating ColorsColorsColorsColors....

packagepackagepackagepackage graf_06;graf_06;graf_06;graf_06;

import import import import javajavajavajava....awtawtawtawt....GraphicsGraphicsGraphicsGraphics;;;;

import import import import javajavajavajava....awtawtawtawt....ColorColorColorColor;;;;

import import import import javaxjavaxjavaxjavax.swing..swing..swing..swing.JPanelJPanelJPanelJPanel;;;;

public public public public classclassclassclass ColorJPanelColorJPanelColorJPanelColorJPanel extendsextendsextendsextends JPanelJPanelJPanelJPanel

{{{{

// // // // drawdrawdrawdraw rectanglesrectanglesrectanglesrectangles andandandand StringsStringsStringsStrings in in in in differentdifferentdifferentdifferent colorscolorscolorscolors

public public public public voidvoidvoidvoid paintComponentpaintComponentpaintComponentpaintComponent( ( ( ( GraphicsGraphicsGraphicsGraphics g )g )g )g )

{{{{

super.super.super.super.paintComponentpaintComponentpaintComponentpaintComponent( g ); // ( g ); // ( g ); // ( g ); // callcallcallcall superclasssuperclasssuperclasssuperclass's 's 's 's paintComponentpaintComponentpaintComponentpaintComponent

thisthisthisthis....setBackgroundsetBackgroundsetBackgroundsetBackground( ( ( ( ColorColorColorColor.WHITE );.WHITE );.WHITE );.WHITE );

// set // set // set // set newnewnewnew drawingdrawingdrawingdrawing colorcolorcolorcolor usingusingusingusing integersintegersintegersintegers

g.g.g.g.setColorsetColorsetColorsetColor( ( ( ( newnewnewnew ColorColorColorColor( 255, 0, 0 ) );( 255, 0, 0 ) );( 255, 0, 0 ) );( 255, 0, 0 ) );

g.g.g.g.fillRectfillRectfillRectfillRect( 15, 25, 100, 20 );( 15, 25, 100, 20 );( 15, 25, 100, 20 );( 15, 25, 100, 20 );

g.g.g.g.drawStringdrawStringdrawStringdrawString( "( "( "( "CurrentCurrentCurrentCurrent RGB: " + g.RGB: " + g.RGB: " + g.RGB: " + g.getColorgetColorgetColorgetColor(), 130, 40 );(), 130, 40 );(), 130, 40 );(), 130, 40 );

// set // set // set // set newnewnewnew drawingdrawingdrawingdrawing colorcolorcolorcolor usingusingusingusing floatsfloatsfloatsfloats

g.g.g.g.setColorsetColorsetColorsetColor( ( ( ( newnewnewnew ColorColorColorColor( 0.50f, 0.75f, 0.0f ) );( 0.50f, 0.75f, 0.0f ) );( 0.50f, 0.75f, 0.0f ) );( 0.50f, 0.75f, 0.0f ) );

g.g.g.g.fillRectfillRectfillRectfillRect( 15, 50, 100, 20 );( 15, 50, 100, 20 );( 15, 50, 100, 20 );( 15, 50, 100, 20 );

g.g.g.g.drawStringdrawStringdrawStringdrawString( "( "( "( "CurrentCurrentCurrentCurrent RGB: " + g.RGB: " + g.RGB: " + g.RGB: " + g.getColorgetColorgetColorgetColor(), 130, 65 );(), 130, 65 );(), 130, 65 );(), 130, 65 );

// set // set // set // set newnewnewnew drawingdrawingdrawingdrawing colorcolorcolorcolor usingusingusingusing static static static static ColorColorColorColor objectsobjectsobjectsobjects

g.g.g.g.setColorsetColorsetColorsetColor( ( ( ( ColorColorColorColor.BLUE );.BLUE );.BLUE );.BLUE );

g.g.g.g.fillRectfillRectfillRectfillRect( 15, 75, 100, 20 );( 15, 75, 100, 20 );( 15, 75, 100, 20 );( 15, 75, 100, 20 );

g.g.g.g.drawStringdrawStringdrawStringdrawString( "( "( "( "CurrentCurrentCurrentCurrent RGB: " + g.RGB: " + g.RGB: " + g.RGB: " + g.getColorgetColorgetColorgetColor(), 130, 90 );(), 130, 90 );(), 130, 90 );(), 130, 90 );

Osnova

25

// display // display // display // display individualindividualindividualindividual RGB RGB RGB RGB valuesvaluesvaluesvalues

ColorColorColorColor colorcolorcolorcolor = = = = ColorColorColorColor.MAGENTA;.MAGENTA;.MAGENTA;.MAGENTA;

g.g.g.g.setColorsetColorsetColorsetColor( ( ( ( colorcolorcolorcolor ););););

g.g.g.g.fillRectfillRectfillRectfillRect( 15, 100, 100, 20 );( 15, 100, 100, 20 );( 15, 100, 100, 20 );( 15, 100, 100, 20 );

g.g.g.g.drawStringdrawStringdrawStringdrawString( "RGB ( "RGB ( "RGB ( "RGB valuesvaluesvaluesvalues: " + : " + : " + : " + colorcolorcolorcolor....getRedgetRedgetRedgetRed() + ", " +() + ", " +() + ", " +() + ", " +

colorcolorcolorcolor....getGreengetGreengetGreengetGreen() + ", " + () + ", " + () + ", " + () + ", " + colorcolorcolorcolor....getBluegetBluegetBluegetBlue(), 130, 115 );(), 130, 115 );(), 130, 115 );(), 130, 115 );

} // } // } // } // endendendend methodmethodmethodmethod paintComponentpaintComponentpaintComponentpaintComponent

} // } // } // } // endendendend classclassclassclass ColorJPanelColorJPanelColorJPanelColorJPanel

Osnova

26

// // // // DemonstratingDemonstratingDemonstratingDemonstrating ColorsColorsColorsColors....

packagepackagepackagepackage graf_06;graf_06;graf_06;graf_06;

import import import import javaxjavaxjavaxjavax.swing..swing..swing..swing.JFrameJFrameJFrameJFrame;;;;

public public public public classclassclassclass ShowColorsShowColorsShowColorsShowColors

{{{{

// // // // executeexecuteexecuteexecute applicationapplicationapplicationapplication

public static public static public static public static voidvoidvoidvoid mainmainmainmain( ( ( ( StringStringStringString argsargsargsargs[] )[] )[] )[] )

{{{{

// // // // createcreatecreatecreate frameframeframeframe forforforfor ColorJPanelColorJPanelColorJPanelColorJPanel

JFrameJFrameJFrameJFrame frameframeframeframe = = = = newnewnewnew JFrameJFrameJFrameJFrame( "( "( "( "UsingUsingUsingUsing colorscolorscolorscolors" );" );" );" );

frameframeframeframe....setDefaultCloseOperationsetDefaultCloseOperationsetDefaultCloseOperationsetDefaultCloseOperation( ( ( ( JFrameJFrameJFrameJFrame.EXIT_ON_CLOSE );.EXIT_ON_CLOSE );.EXIT_ON_CLOSE );.EXIT_ON_CLOSE );

ColorJPanelColorJPanelColorJPanelColorJPanel colorJPanelcolorJPanelcolorJPanelcolorJPanel = = = = newnewnewnew ColorJPanelColorJPanelColorJPanelColorJPanel(); // (); // (); // (); // createcreatecreatecreate ColorJPanelColorJPanelColorJPanelColorJPanel

frameframeframeframe....addaddaddadd( ( ( ( colorJPanelcolorJPanelcolorJPanelcolorJPanel ); // ); // ); // ); // addaddaddadd colorJPanelcolorJPanelcolorJPanelcolorJPanel to to to to frameframeframeframe

frameframeframeframe....setSizesetSizesetSizesetSize( 400, 180 ); // set ( 400, 180 ); // set ( 400, 180 ); // set ( 400, 180 ); // set frameframeframeframe sizesizesizesize

frameframeframeframe....setVisiblesetVisiblesetVisiblesetVisible( ( ( ( truetruetruetrue ); // display ); // display ); // display ); // display frameframeframeframe

} // } // } // } // endendendend mainmainmainmain

} // } // } // } // endendendend classclassclassclass ShowColorsShowColorsShowColorsShowColors

Osnova

27

Jednoduchý příklad využívající barev

import import import import javaxjavaxjavaxjavax.swing.*;.swing.*;.swing.*;.swing.*;

import import import import javajavajavajava....awtawtawtawt....eventeventeventevent.*;.*;.*;.*;

import import import import javajavajavajava....awtawtawtawt.*;.*;.*;.*;

classclassclassclass ColorMenuExColorMenuExColorMenuExColorMenuEx extendsextendsextendsextends JFrameJFrameJFrameJFrame implementsimplementsimplementsimplements ActionListenerActionListenerActionListenerActionListener {{{{

private private private private JMenuBarJMenuBarJMenuBarJMenuBar menuBarmenuBarmenuBarmenuBar;;;;

private private private private JMenuJMenuJMenuJMenu colorMenucolorMenucolorMenucolorMenu;;;;

private private private private JMenuJMenuJMenuJMenu controlMenucontrolMenucontrolMenucontrolMenu;;;;

private static private static private static private static finalfinalfinalfinal ColorColorColorColor origorigorigorig = = = = ColorColorColorColor....whitewhitewhitewhite;;;;

private static private static private static private static finalfinalfinalfinal StringStringStringString[ ] [ ] [ ] [ ] colorNamescolorNamescolorNamescolorNames = = = =

{ "{ "{ "{ "BlueBlueBlueBlue", "", "", "", "CyanCyanCyanCyan", "", "", "", "GrayGrayGrayGray", "", "", "", "OrangeOrangeOrangeOrange", "Pink" };", "Pink" };", "Pink" };", "Pink" };

private static private static private static private static finalfinalfinalfinal ColorColorColorColor[ ] [ ] [ ] [ ] colorscolorscolorscolors ====

{ { { { ColorColorColorColor....blueblueblueblue, , , , ColorColorColorColor....cyancyancyancyan, , , , ColorColorColorColor....graygraygraygray, , , , ColorColorColorColor....orangeorangeorangeorange, , , , ColorColorColorColor.pink };.pink };.pink };.pink };

private static private static private static private static finalfinalfinalfinal StringStringStringString[ ] [ ] [ ] [ ] controlscontrolscontrolscontrols = { "= { "= { "= { "RestoreRestoreRestoreRestore", "Exit" };", "Exit" };", "Exit" };", "Exit" };

public public public public ColorMenuExColorMenuExColorMenuExColorMenuEx() {() {() {() {

menuBarmenuBarmenuBarmenuBar = = = = newnewnewnew JMenuBarJMenuBarJMenuBarJMenuBar();();();();

colorMenucolorMenucolorMenucolorMenu = = = = newnewnewnew JMenuJMenuJMenuJMenu( "( "( "( "ColorsColorsColorsColors" );" );" );" );

controlMenucontrolMenucontrolMenucontrolMenu = = = = newnewnewnew JMenuJMenuJMenuJMenu( "( "( "( "ControlControlControlControl" );" );" );" );

initinitinitinit();();();();

setSizesetSizesetSizesetSize( 300, 150 );( 300, 150 );( 300, 150 );( 300, 150 );

getContentPanegetContentPanegetContentPanegetContentPane().().().().setBackgroundsetBackgroundsetBackgroundsetBackground( ( ( ( origorigorigorig ););););

setVisiblesetVisiblesetVisiblesetVisible( ( ( ( truetruetruetrue ););););

}}}}

Osnova

28

public public public public voidvoidvoidvoid actionPerformedactionPerformedactionPerformedactionPerformed( ( ( ( ActionEventActionEventActionEventActionEvent e ) {e ) {e ) {e ) {

StringStringStringString s = e.s = e.s = e.s = e.getActionCommandgetActionCommandgetActionCommandgetActionCommand();();();();

ifififif ( s.( s.( s.( s.equalsequalsequalsequals( "Exit" ) )( "Exit" ) )( "Exit" ) )( "Exit" ) )

SystemSystemSystemSystem.exit( 0 ); .exit( 0 ); .exit( 0 ); .exit( 0 );

elseelseelseelse ifififif ( s.( s.( s.( s.equalsequalsequalsequals( "( "( "( "RestoreRestoreRestoreRestore" ) )" ) )" ) )" ) )

getContentPanegetContentPanegetContentPanegetContentPane().().().().setBackgroundsetBackgroundsetBackgroundsetBackground( ( ( ( origorigorigorig ););););

elseelseelseelse

setColorsetColorsetColorsetColor( s );( s );( s );( s );

}}}}

private private private private voidvoidvoidvoid initinitinitinit() {() {() {() {

initMenuinitMenuinitMenuinitMenu( ( ( ( colorMenucolorMenucolorMenucolorMenu, , , , colorNamescolorNamescolorNamescolorNames ); ); ); );

initMenuinitMenuinitMenuinitMenu( ( ( ( controlMenucontrolMenucontrolMenucontrolMenu, , , , controlscontrolscontrolscontrols ););););

menuBarmenuBarmenuBarmenuBar....addaddaddadd( ( ( ( colorMenucolorMenucolorMenucolorMenu ); ); ); ); menuBarmenuBarmenuBarmenuBar....addaddaddadd( ( ( ( controlMenucontrolMenucontrolMenucontrolMenu ););););

setJMenuBarsetJMenuBarsetJMenuBarsetJMenuBar( ( ( ( menuBarmenuBarmenuBarmenuBar ););););

}}}}

private private private private voidvoidvoidvoid initMenuinitMenuinitMenuinitMenu( ( ( ( JMenuJMenuJMenuJMenu menu, menu, menu, menu, StringStringStringString[ ] [ ] [ ] [ ] itemsitemsitemsitems ) {) {) {) {

forforforfor ( ( ( ( intintintint i = 0; i < i = 0; i < i = 0; i < i = 0; i < itemsitemsitemsitems....lengthlengthlengthlength; i++ ) {; i++ ) {; i++ ) {; i++ ) {

JMenuItemJMenuItemJMenuItemJMenuItem itemitemitemitem = = = = newnewnewnew JMenuItemJMenuItemJMenuItemJMenuItem( ( ( ( itemsitemsitemsitems[ i ] );[ i ] );[ i ] );[ i ] );

itemitemitemitem....addActionListeneraddActionListeneraddActionListeneraddActionListener( ( ( ( thisthisthisthis ););););

menu.menu.menu.menu.addaddaddadd( ( ( ( itemitemitemitem ););););

} } } }

}}}}

private private private private voidvoidvoidvoid setColorsetColorsetColorsetColor( ( ( ( StringStringStringString c ) {c ) {c ) {c ) {

forforforfor ( ( ( ( intintintint i = 0; i < i = 0; i < i = 0; i < i = 0; i < colorNamescolorNamescolorNamescolorNames....lengthlengthlengthlength; i++ ) ; i++ ) ; i++ ) ; i++ )

ifififif ( c.( c.( c.( c.equalsequalsequalsequals( ( ( ( colorNamescolorNamescolorNamescolorNames[ i ] ) ) {[ i ] ) ) {[ i ] ) ) {[ i ] ) ) {

getContentPanegetContentPanegetContentPanegetContentPane().().().().setBackgroundsetBackgroundsetBackgroundsetBackground( ( ( ( colorscolorscolorscolors[ i ] );[ i ] );[ i ] );[ i ] );

breakbreakbreakbreak;;;;

}}}}

}}}}

}}}}

Osnova

29

class class class class ColorMenuExTesterColorMenuExTesterColorMenuExTesterColorMenuExTester {{{{

public static void main( String[ ] public static void main( String[ ] public static void main( String[ ] public static void main( String[ ] argsargsargsargs ) {) {) {) {

new new new new ColorMenuExColorMenuExColorMenuExColorMenuEx();();();();

}}}}

}}}}

Osnova

30

Příklad umožňujícívýběr barev

// // // // ChoosingChoosingChoosingChoosing colorscolorscolorscolors withwithwithwith JColorChooserJColorChooserJColorChooserJColorChooser....

packagepackagepackagepackage graf_08;graf_08;graf_08;graf_08;

import import import import javajavajavajava....awtawtawtawt....BorderLayoutBorderLayoutBorderLayoutBorderLayout;;;;

import import import import javajavajavajava....awtawtawtawt....ColorColorColorColor;;;;

import import import import javajavajavajava....awtawtawtawt....eventeventeventevent....ActionEventActionEventActionEventActionEvent;;;;

import import import import javajavajavajava....awtawtawtawt....eventeventeventevent....ActionListenerActionListenerActionListenerActionListener;;;;

import import import import javaxjavaxjavaxjavax.swing..swing..swing..swing.JButtonJButtonJButtonJButton;;;;

import import import import javaxjavaxjavaxjavax.swing..swing..swing..swing.JFrameJFrameJFrameJFrame;;;;

import import import import javaxjavaxjavaxjavax.swing..swing..swing..swing.JColorChooserJColorChooserJColorChooserJColorChooser;;;;

import import import import javaxjavaxjavaxjavax.swing..swing..swing..swing.JPanelJPanelJPanelJPanel;;;;

public public public public classclassclassclass ShowColors2JFrame ShowColors2JFrame ShowColors2JFrame ShowColors2JFrame extendsextendsextendsextends JFrameJFrameJFrameJFrame

{{{{

private private private private JButtonJButtonJButtonJButton changeColorJButtonchangeColorJButtonchangeColorJButtonchangeColorJButton;;;;

private private private private ColorColorColorColor colorcolorcolorcolor = = = = ColorColorColorColor.LIGHT_GRAY;.LIGHT_GRAY;.LIGHT_GRAY;.LIGHT_GRAY;

private private private private JPanelJPanelJPanelJPanel colorJPanelcolorJPanelcolorJPanelcolorJPanel;;;;

// set // set // set // set upupupup GUIGUIGUIGUI

public ShowColors2JFrame()public ShowColors2JFrame()public ShowColors2JFrame()public ShowColors2JFrame()

{{{{

super( "super( "super( "super( "UsingUsingUsingUsing JColorChooserJColorChooserJColorChooserJColorChooser" );" );" );" );

// // // // createcreatecreatecreate JPanelJPanelJPanelJPanel forforforfor display display display display colorcolorcolorcolor

colorJPanelcolorJPanelcolorJPanelcolorJPanel = = = = newnewnewnew JPanelJPanelJPanelJPanel();();();();

colorJPanelcolorJPanelcolorJPanelcolorJPanel....setBackgroundsetBackgroundsetBackgroundsetBackground( ( ( ( colorcolorcolorcolor ););););

// set // set // set // set upupupup changeColorJButtonchangeColorJButtonchangeColorJButtonchangeColorJButton andandandand registerregisterregisterregister itsitsitsits eventeventeventevent handlerhandlerhandlerhandler

changeColorJButtonchangeColorJButtonchangeColorJButtonchangeColorJButton = = = = newnewnewnew JButtonJButtonJButtonJButton( "( "( "( "ChangeChangeChangeChange ColorColorColorColor" );" );" );" );

changeColorJButtonchangeColorJButtonchangeColorJButtonchangeColorJButton....addActionListeneraddActionListeneraddActionListeneraddActionListener((((

Osnova

31

newnewnewnew ActionListenerActionListenerActionListenerActionListener() // () // () // () // anonymnianonymnianonymnianonymni vnitrnivnitrnivnitrnivnitrni tridatridatridatrida

{{{{

// display // display // display // display JColorChooserJColorChooserJColorChooserJColorChooser whenwhenwhenwhen useruseruseruser clicksclicksclicksclicks buttonbuttonbuttonbutton

public public public public voidvoidvoidvoid actionPerformedactionPerformedactionPerformedactionPerformed( ( ( ( ActionEventActionEventActionEventActionEvent eventeventeventevent ))))

{{{{

colorcolorcolorcolor = = = = JColorChooserJColorChooserJColorChooserJColorChooser....showDialogshowDialogshowDialogshowDialog( ( ( (

ShowColors2JFrame.ShowColors2JFrame.ShowColors2JFrame.ShowColors2JFrame.thisthisthisthis, ", ", ", "ChooseChooseChooseChoose a a a a colorcolorcolorcolor", ", ", ", colorcolorcolorcolor ););););

// set default // set default // set default // set default colorcolorcolorcolor, , , , ifififif no no no no colorcolorcolorcolor isisisis returnedreturnedreturnedreturned

ifififif ( ( ( ( colorcolorcolorcolor == == == == nullnullnullnull ))))

colorcolorcolorcolor = = = = ColorColorColorColor.LIGHT_GRAY;.LIGHT_GRAY;.LIGHT_GRAY;.LIGHT_GRAY;

// // // // changechangechangechange contentcontentcontentcontent pane's pane's pane's pane's backgroundbackgroundbackgroundbackground colorcolorcolorcolor

colorJPanelcolorJPanelcolorJPanelcolorJPanel....setBackgroundsetBackgroundsetBackgroundsetBackground( ( ( ( colorcolorcolorcolor ););););

} // } // } // } // endendendend methodmethodmethodmethod actionPerformedactionPerformedactionPerformedactionPerformed

} // } // } // } // endendendend anonymousanonymousanonymousanonymous innerinnerinnerinner classclassclassclass

); // ); // ); // ); // endendendend callcallcallcall to to to to addActionListeneraddActionListeneraddActionListeneraddActionListener

addaddaddadd( ( ( ( colorJPanelcolorJPanelcolorJPanelcolorJPanel, , , , BorderLayoutBorderLayoutBorderLayoutBorderLayout.CENTER ); // .CENTER ); // .CENTER ); // .CENTER ); // addaddaddadd colorJPanelcolorJPanelcolorJPanelcolorJPanel

addaddaddadd( ( ( ( changeColorJButtonchangeColorJButtonchangeColorJButtonchangeColorJButton, , , , BorderLayoutBorderLayoutBorderLayoutBorderLayout.SOUTH ); // .SOUTH ); // .SOUTH ); // .SOUTH ); // addaddaddadd buttonbuttonbuttonbutton

setSizesetSizesetSizesetSize( 400, 130 ); // set ( 400, 130 ); // set ( 400, 130 ); // set ( 400, 130 ); // set frameframeframeframe sizesizesizesize

setVisiblesetVisiblesetVisiblesetVisible( ( ( ( truetruetruetrue ); // display ); // display ); // display ); // display frameframeframeframe

} // } // } // } // endendendend ShowColor2JFrame ShowColor2JFrame ShowColor2JFrame ShowColor2JFrame constructorconstructorconstructorconstructor

} // } // } // } // endendendend classclassclassclass ShowColors2JFrameShowColors2JFrameShowColors2JFrameShowColors2JFrame

Osnova

32

// // // // ChoosingChoosingChoosingChoosing colorscolorscolorscolors withwithwithwith JColorChooserJColorChooserJColorChooserJColorChooser....

packagepackagepackagepackage graf_08;graf_08;graf_08;graf_08;

import import import import javaxjavaxjavaxjavax.swing..swing..swing..swing.JFrameJFrameJFrameJFrame;;;;

public public public public classclassclassclass ShowColors2ShowColors2ShowColors2ShowColors2

{{{{

// // // // executeexecuteexecuteexecute applicationapplicationapplicationapplication

public static public static public static public static voidvoidvoidvoid mainmainmainmain( ( ( ( StringStringStringString argsargsargsargs[] )[] )[] )[] )

{{{{

ShowColors2JFrame ShowColors2JFrame ShowColors2JFrame ShowColors2JFrame applicationapplicationapplicationapplication = = = = newnewnewnew ShowColors2JFrame();ShowColors2JFrame();ShowColors2JFrame();ShowColors2JFrame();

applicationapplicationapplicationapplication....setDefaultCloseOperationsetDefaultCloseOperationsetDefaultCloseOperationsetDefaultCloseOperation( ( ( ( JFrameJFrameJFrameJFrame.EXIT_ON_CLOSE );.EXIT_ON_CLOSE );.EXIT_ON_CLOSE );.EXIT_ON_CLOSE );

} // } // } // } // endendendend mainmainmainmain

} // } // } // } // endendendend classclassclassclass ShowColors2ShowColors2ShowColors2ShowColors2

Osnova

33

34

Výsledky aplikace

35

5. Práce s fonty

• Třída Font– Obsahuje metody a konstanty pro práci s fonty

– Konstruktor třídy Font potřebuje tři argumenty• Jméno Fontu

– Monospaced, SansSerif, Serif, etc.

• Styl Fontu

– Font.PLAIN, Font.ITALIC and Font.BOLD

• Velikost Font

– Měřeno v bodech (1/72 of inch)

36

Metody a konstanty třídy FontMetody nebo konstanty Popis Konstanty Font, konstruktory a metody pro kreslení polygonů

public final static int PLAIN

Konstanta reprezentující a plain font style.

public final static int BOLD

Konstanta reprezentující a bold font style.

public final static int ITALIC

Konstanta reprezentující an italic font style.

public Font( String name, int style, int size )

Vytvoří objekt třídy Font se specifikovaným fontem, stylem a velikostí.

public int getStyle() Vrací celočíselnou hodnotu indikující aktuální styl fontu.

public int getSize() Vrací celočíselnou hodnotu indikující aktuální velikost fontu.

public String getName() Vrací aktuální jméno fontu jako řetězec.

public String getFamily() Vrací font’s family name jako řetězec.

public boolean isPlain() Testuje font na plain font styl.

public boolean isBold() Testuje font na a bold font styl.

public boolean isItalic() Testuje font na an italic font styl.

37

Metody a konstanty třídy Font

Metody nebo konstanty Popis Methods Graphics pro práci s fonty

public Font getFont() Vrací objekt třídy Font reprezentující aktuální font.

public void setFont( Font f )

Nastaví aktuální font na font, styl a velikost specifikované v proměnné f.

Osnova

38

Demonstrace využitítřídy Font

// Display // Display // Display // Display stringsstringsstringsstrings in in in in differentdifferentdifferentdifferent fontsfontsfontsfonts andandandand colorscolorscolorscolors....

packagepackagepackagepackage graf_12;graf_12;graf_12;graf_12;

import import import import javajavajavajava....awtawtawtawt.Font;.Font;.Font;.Font;

import import import import javajavajavajava....awtawtawtawt....ColorColorColorColor;;;;

import import import import javajavajavajava....awtawtawtawt....GraphicsGraphicsGraphicsGraphics;;;;

import import import import javaxjavaxjavaxjavax.swing..swing..swing..swing.JPanelJPanelJPanelJPanel;;;;

public public public public classclassclassclass FontJPanelFontJPanelFontJPanelFontJPanel extendsextendsextendsextends JPanelJPanelJPanelJPanel

{{{{

// display // display // display // display StringsStringsStringsStrings in in in in differentdifferentdifferentdifferent fontsfontsfontsfonts andandandand colorscolorscolorscolors

public public public public voidvoidvoidvoid paintComponentpaintComponentpaintComponentpaintComponent( ( ( ( GraphicsGraphicsGraphicsGraphics g )g )g )g )

{{{{

super.super.super.super.paintComponentpaintComponentpaintComponentpaintComponent( g ); // ( g ); // ( g ); // ( g ); // callcallcallcall superclasssuperclasssuperclasssuperclass's 's 's 's paintConponentpaintConponentpaintConponentpaintConponent

// set font to // set font to // set font to // set font to SerifSerifSerifSerif ((((TimesTimesTimesTimes), ), ), ), boldboldboldbold, 12pt , 12pt , 12pt , 12pt andandandand drawdrawdrawdraw a a a a stringstringstringstring

g.g.g.g.setFontsetFontsetFontsetFont( ( ( ( newnewnewnew Font( "Font( "Font( "Font( "SerifSerifSerifSerif", Font.BOLD, 12 ) );", Font.BOLD, 12 ) );", Font.BOLD, 12 ) );", Font.BOLD, 12 ) );

g.g.g.g.drawStringdrawStringdrawStringdrawString( "( "( "( "SerifSerifSerifSerif 12 point 12 point 12 point 12 point boldboldboldbold.", 20, 50 );.", 20, 50 );.", 20, 50 );.", 20, 50 );

// set font to // set font to // set font to // set font to MonospacedMonospacedMonospacedMonospaced ((((CourierCourierCourierCourier), ), ), ), italicitalicitalicitalic, 24pt , 24pt , 24pt , 24pt andandandand drawdrawdrawdraw a a a a stringstringstringstring

g.g.g.g.setFontsetFontsetFontsetFont( ( ( ( newnewnewnew Font( "Font( "Font( "Font( "MonospacedMonospacedMonospacedMonospaced", Font.ITALIC, 24 ) );", Font.ITALIC, 24 ) );", Font.ITALIC, 24 ) );", Font.ITALIC, 24 ) );

g.g.g.g.drawStringdrawStringdrawStringdrawString( "( "( "( "MonospacedMonospacedMonospacedMonospaced 24 point 24 point 24 point 24 point italicitalicitalicitalic.", 20, 70 );.", 20, 70 );.", 20, 70 );.", 20, 70 );

// set font to // set font to // set font to // set font to SansSerifSansSerifSansSerifSansSerif ((((HelveticaHelveticaHelveticaHelvetica), ), ), ), plainplainplainplain, 14pt , 14pt , 14pt , 14pt andandandand drawdrawdrawdraw a a a a stringstringstringstring

g.g.g.g.setFontsetFontsetFontsetFont( ( ( ( newnewnewnew Font( "Font( "Font( "Font( "SansSerifSansSerifSansSerifSansSerif", Font.PLAIN, 14 ) );", Font.PLAIN, 14 ) );", Font.PLAIN, 14 ) );", Font.PLAIN, 14 ) );

g.g.g.g.drawStringdrawStringdrawStringdrawString( "( "( "( "SansSerifSansSerifSansSerifSansSerif 14 point 14 point 14 point 14 point plainplainplainplain.", 20, 90 );.", 20, 90 );.", 20, 90 );.", 20, 90 );

Osnova

39

// set font to // set font to // set font to // set font to SerifSerifSerifSerif ((((TimesTimesTimesTimes), ), ), ), boldboldboldbold////italicitalicitalicitalic, 18pt , 18pt , 18pt , 18pt andandandand drawdrawdrawdraw a a a a stringstringstringstring

g.g.g.g.setColorsetColorsetColorsetColor( ( ( ( ColorColorColorColor.RED );.RED );.RED );.RED );

g.g.g.g.setFontsetFontsetFontsetFont( ( ( ( newnewnewnew Font( "Font( "Font( "Font( "SerifSerifSerifSerif", Font.BOLD + Font.ITALIC, 18 ) );", Font.BOLD + Font.ITALIC, 18 ) );", Font.BOLD + Font.ITALIC, 18 ) );", Font.BOLD + Font.ITALIC, 18 ) );

g.g.g.g.drawStringdrawStringdrawStringdrawString( g.( g.( g.( g.getFontgetFontgetFontgetFont().().().().getNamegetNamegetNamegetName() + " " + g.() + " " + g.() + " " + g.() + " " + g.getFontgetFontgetFontgetFont().().().().getSizegetSizegetSizegetSize() +() +() +() +

" point " point " point " point boldboldboldbold italicitalicitalicitalic.", 20, 110 );.", 20, 110 );.", 20, 110 );.", 20, 110 );

} // } // } // } // endendendend methodmethodmethodmethod paintComponentpaintComponentpaintComponentpaintComponent

} // } // } // } // endendendend classclassclassclass FontJPanelFontJPanelFontJPanelFontJPanel

Osnova

40

// // // // UsingUsingUsingUsing fontsfontsfontsfonts....

packagepackagepackagepackage graf_12;graf_12;graf_12;graf_12;

import import import import javaxjavaxjavaxjavax.swing..swing..swing..swing.JFrameJFrameJFrameJFrame;;;;

public public public public classclassclassclass FontsFontsFontsFonts

{{{{

// // // // executeexecuteexecuteexecute applicationapplicationapplicationapplication

public static public static public static public static voidvoidvoidvoid mainmainmainmain( ( ( ( StringStringStringString argsargsargsargs[] )[] )[] )[] )

{{{{

// // // // createcreatecreatecreate frameframeframeframe forforforfor FontJPanelFontJPanelFontJPanelFontJPanel

JFrameJFrameJFrameJFrame frameframeframeframe = = = = newnewnewnew JFrameJFrameJFrameJFrame( "( "( "( "UsingUsingUsingUsing fontsfontsfontsfonts" );" );" );" );

frameframeframeframe....setDefaultCloseOperationsetDefaultCloseOperationsetDefaultCloseOperationsetDefaultCloseOperation( ( ( ( JFrameJFrameJFrameJFrame.EXIT_ON_CLOSE );.EXIT_ON_CLOSE );.EXIT_ON_CLOSE );.EXIT_ON_CLOSE );

FontJPanelFontJPanelFontJPanelFontJPanel fontJPanelfontJPanelfontJPanelfontJPanel = = = = newnewnewnew FontJPanelFontJPanelFontJPanelFontJPanel(); // (); // (); // (); // createcreatecreatecreate FontJPanelFontJPanelFontJPanelFontJPanel

frameframeframeframe....addaddaddadd( ( ( ( fontJPanelfontJPanelfontJPanelfontJPanel ); // ); // ); // ); // addaddaddadd fontJPanelfontJPanelfontJPanelfontJPanel to to to to frameframeframeframe

frameframeframeframe....setSizesetSizesetSizesetSize( 420, 170 ); // set ( 420, 170 ); // set ( 420, 170 ); // set ( 420, 170 ); // set frameframeframeframe sizesizesizesize

frameframeframeframe....setVisiblesetVisiblesetVisiblesetVisible( ( ( ( truetruetruetrue ); // display ); // display ); // display ); // display frameframeframeframe

} // } // } // } // endendendend mainmainmainmain

} // } // } // } // endendendend classclassclassclass FontsFontsFontsFonts

41

6. Správa fontů –metriky fontů

• Metriky fontů– Height

– Descent (amount character dips below baseline)

– Ascent (amount character rises above baseline)

– Leading (difference between descent and ascent)

42

Metriky fontů

he ight Xy1İ asce nt

le ading

ba selinedescent

43

Metody tříd FontMetrics a Graphicszískání metrik fontů

Method Description FontMetrics methods

public int getAscent() Returns a value representing the ascent of a font in points.

public int getDescent() Returns a value representing the descent of a font in points.

public int getLeading() Returns a value representing the leading of a font in points.

public int getHeight() Returns a value representing the height of a font in points.

Graphics methods for getting a Font’s FontMetrics

public FontMetrics getFontMetrics() Returns the FontMetrics object for the current drawing Font.

public FontMetrics getFontMetrics( Font f ) Returns the FontMetrics object for the specified Font argument.

Osnova

44

// // // // FontMetricsFontMetricsFontMetricsFontMetrics andandandand GraphicsGraphicsGraphicsGraphics methodsmethodsmethodsmethods usefulusefulusefuluseful forforforfor obtainingobtainingobtainingobtaining font font font font metricsmetricsmetricsmetrics....

packagepackagepackagepackage graf_16;graf_16;graf_16;graf_16;

import import import import javajavajavajava....awtawtawtawt.Font;.Font;.Font;.Font;

import import import import javajavajavajava....awtawtawtawt....FontMetricsFontMetricsFontMetricsFontMetrics;;;;

import import import import javajavajavajava....awtawtawtawt....GraphicsGraphicsGraphicsGraphics;;;;

import import import import javaxjavaxjavaxjavax.swing..swing..swing..swing.JPanelJPanelJPanelJPanel;;;;

public public public public classclassclassclass MetricsJPanelMetricsJPanelMetricsJPanelMetricsJPanel extendsextendsextendsextends JPanelJPanelJPanelJPanel

{{{{

// display font // display font // display font // display font metricsmetricsmetricsmetrics

public public public public voidvoidvoidvoid paintComponentpaintComponentpaintComponentpaintComponent( ( ( ( GraphicsGraphicsGraphicsGraphics g )g )g )g )

{{{{

super.super.super.super.paintComponentpaintComponentpaintComponentpaintComponent( g ); // ( g ); // ( g ); // ( g ); // callcallcallcall superclasssuperclasssuperclasssuperclass's 's 's 's paintComponentpaintComponentpaintComponentpaintComponent

g.g.g.g.setFontsetFontsetFontsetFont( ( ( ( newnewnewnew Font( "Font( "Font( "Font( "SansSerifSansSerifSansSerifSansSerif", Font.BOLD, 12 ) );", Font.BOLD, 12 ) );", Font.BOLD, 12 ) );", Font.BOLD, 12 ) );

FontMetricsFontMetricsFontMetricsFontMetrics metricsmetricsmetricsmetrics = g.= g.= g.= g.getFontMetricsgetFontMetricsgetFontMetricsgetFontMetrics();();();();

g.g.g.g.drawStringdrawStringdrawStringdrawString( "( "( "( "CurrentCurrentCurrentCurrent font: " + g.font: " + g.font: " + g.font: " + g.getFontgetFontgetFontgetFont(), 10, 40 );(), 10, 40 );(), 10, 40 );(), 10, 40 );

g.g.g.g.drawStringdrawStringdrawStringdrawString( "( "( "( "AscentAscentAscentAscent: " + : " + : " + : " + metricsmetricsmetricsmetrics....getAscentgetAscentgetAscentgetAscent(), 10, 55 );(), 10, 55 );(), 10, 55 );(), 10, 55 );

g.g.g.g.drawStringdrawStringdrawStringdrawString( "( "( "( "DescentDescentDescentDescent: " + : " + : " + : " + metricsmetricsmetricsmetrics....getDescentgetDescentgetDescentgetDescent(), 10, 70 );(), 10, 70 );(), 10, 70 );(), 10, 70 );

g.g.g.g.drawStringdrawStringdrawStringdrawString( "( "( "( "HeightHeightHeightHeight: " + : " + : " + : " + metricsmetricsmetricsmetrics....getHeightgetHeightgetHeightgetHeight(), 10, 85 );(), 10, 85 );(), 10, 85 );(), 10, 85 );

g.g.g.g.drawStringdrawStringdrawStringdrawString( "( "( "( "LeadingLeadingLeadingLeading: " + : " + : " + : " + metricsmetricsmetricsmetrics....getLeadinggetLeadinggetLeadinggetLeading(), 10, 100 );(), 10, 100 );(), 10, 100 );(), 10, 100 );

Font Font Font Font fontfontfontfont = = = = newnewnewnew Font( "Font( "Font( "Font( "SerifSerifSerifSerif", Font.ITALIC, 14 );", Font.ITALIC, 14 );", Font.ITALIC, 14 );", Font.ITALIC, 14 );

metricsmetricsmetricsmetrics = g.= g.= g.= g.getFontMetricsgetFontMetricsgetFontMetricsgetFontMetrics( font );( font );( font );( font );

Osnova

45

g.g.g.g.setFontsetFontsetFontsetFont( font );( font );( font );( font );

g.g.g.g.drawStringdrawStringdrawStringdrawString( "( "( "( "CurrentCurrentCurrentCurrent font: " + font, 10, 130 );font: " + font, 10, 130 );font: " + font, 10, 130 );font: " + font, 10, 130 );

g.g.g.g.drawStringdrawStringdrawStringdrawString( "( "( "( "AscentAscentAscentAscent: " + : " + : " + : " + metricsmetricsmetricsmetrics....getAscentgetAscentgetAscentgetAscent(), 10, 145 );(), 10, 145 );(), 10, 145 );(), 10, 145 );

g.g.g.g.drawStringdrawStringdrawStringdrawString( "( "( "( "DescentDescentDescentDescent: " + : " + : " + : " + metricsmetricsmetricsmetrics....getDescentgetDescentgetDescentgetDescent(), 10, 160 );(), 10, 160 );(), 10, 160 );(), 10, 160 );

g.g.g.g.drawStringdrawStringdrawStringdrawString( "( "( "( "HeightHeightHeightHeight: " + : " + : " + : " + metricsmetricsmetricsmetrics....getHeightgetHeightgetHeightgetHeight(), 10, 175 );(), 10, 175 );(), 10, 175 );(), 10, 175 );

g.g.g.g.drawStringdrawStringdrawStringdrawString( "( "( "( "LeadingLeadingLeadingLeading: " + : " + : " + : " + metricsmetricsmetricsmetrics....getLeadinggetLeadinggetLeadinggetLeading(), 10, 190 );(), 10, 190 );(), 10, 190 );(), 10, 190 );

} // } // } // } // endendendend methodmethodmethodmethod paintComponentpaintComponentpaintComponentpaintComponent

} } } }

Osnova

46

import import import import javaxjavaxjavaxjavax.swing..swing..swing..swing.JFrameJFrameJFrameJFrame;;;;

public public public public classclassclassclass MetricsMetricsMetricsMetrics

{{{{

// // // // executeexecuteexecuteexecute applicationapplicationapplicationapplication

public static public static public static public static voidvoidvoidvoid mainmainmainmain( ( ( ( StringStringStringString argsargsargsargs[] )[] )[] )[] )

{{{{

// // // // createcreatecreatecreate frameframeframeframe forforforfor MetricsJPanelMetricsJPanelMetricsJPanelMetricsJPanel

JFrameJFrameJFrameJFrame frameframeframeframe = = = = newnewnewnew JFrameJFrameJFrameJFrame( "( "( "( "DemonstratingDemonstratingDemonstratingDemonstrating FontMetricsFontMetricsFontMetricsFontMetrics" );" );" );" );

frameframeframeframe....setDefaultCloseOperationsetDefaultCloseOperationsetDefaultCloseOperationsetDefaultCloseOperation( ( ( ( JFrameJFrameJFrameJFrame.EXIT_ON_CLOSE );.EXIT_ON_CLOSE );.EXIT_ON_CLOSE );.EXIT_ON_CLOSE );

MetricsJPanelMetricsJPanelMetricsJPanelMetricsJPanel metricsJPanelmetricsJPanelmetricsJPanelmetricsJPanel = = = = newnewnewnew MetricsJPanelMetricsJPanelMetricsJPanelMetricsJPanel(); (); (); ();

frameframeframeframe....addaddaddadd( ( ( ( metricsJPanelmetricsJPanelmetricsJPanelmetricsJPanel ); // ); // ); // ); // addaddaddadd metricsJPanelmetricsJPanelmetricsJPanelmetricsJPanel to to to to frameframeframeframe

frameframeframeframe....setSizesetSizesetSizesetSize( 510, 250 ); // set ( 510, 250 ); // set ( 510, 250 ); // set ( 510, 250 ); // set frameframeframeframe sizesizesizesize

frameframeframeframe....setVisiblesetVisiblesetVisiblesetVisible( ( ( ( truetruetruetrue ); // display ); // display ); // display ); // display frameframeframeframe

} // } // } // } // endendendend mainmainmainmain

} // } // } // } // endendendend classclassclassclass MetricsMetricsMetricsMetrics

47

7. Kresleníčar, obdelníků a oválů

• TřídaGraphics– Poskytuje metody pro kresleníčar, obdelníků a

oválů• Všechny metody kreslení vyžadují parametrywidth a height

48

Metody třídy Graphics pro kreslení čar, obdélníků a oválů

Method Description public void drawLine( int x1, int y1, int x2, int y2 )

Draws a line between the point (x1, y1) and the point (x2, y2).

public void drawRect( int x, int y, int width, int height )

Draws a rectangle of the specified width and height. The top-left corner of the rectangle has the coordinates (x, y).

public void fillRect( int x, int y, int width, int height )

Draws a solid rectangle with the specified width and height. The top-left corner of the rectangle has the coordinate (x, y).

public void clearRect( int x, int y, int width, int height )

Draws a solid rectangle with the specified width and height in the current background color. The top-left corner of the rectangle has the coordinate (x, y).

public void drawRoundRect( int x, int y, int width, int height, int arcWidth, int arcHeight )

Draws a rectangle with rounded corners in the current color with the specified width and height. The arcWidth and arcHeight determine the rounding of the corners (see Fig. 12.15).

public void fillRoundRect( int x, int y, int width, int height, int arcWidth, int arcHeight )

Draws a solid rectangle with rounded corners in the current color with the specified width and height. The arcWidth and arcHeight determine the rounding of the corners (see Fig. 12.15).

49

Metody třídy Graphics pro kreslení čar, obdélníků a oválů

Method Description public void draw3DRect( int x, int y, int width, int height, boolean b ) Draws a three-dimensional rectangle in the current color with the specified

width and height. The top-left corner of the rectangle has the coordinates (x, y). The rectangle appears raised when b is true and lowered when b is false.

public void fill3DRect( int x, int y, int width, int height, boolean b )

Draws a filled three-dimensional rectangle in the current color with the specified width and height. The top-left corner of the rectangle has the coordinates (x, y). The rectangle appears raised when b is true and lowered when b is false.

public void drawOval( int x, int y, int width, int height )

Draws an oval in the current color with the specified width and height. The bounding rectangle’s top-left corner is at the coordinates (x, y). The oval touches all four sides of the bounding rectangle at the center of each side (see Fig. 12.16).

public void fillOval( int x, int y, int width, int height )

Draws a filled oval in the current color with the specified width and height. The bounding rectangle’s top-left corner is at the coordinates (x, y). The oval touches all four sides of the bounding rectangle at the center of each side (see Fig. 12.16).

Osnova

50

packagepackagepackagepackage graf_19;graf_19;graf_19;graf_19;

import import import import javajavajavajava....awtawtawtawt....ColorColorColorColor;;;;

import import import import javajavajavajava....awtawtawtawt....GraphicsGraphicsGraphicsGraphics;;;;

import import import import javaxjavaxjavaxjavax.swing..swing..swing..swing.JPanelJPanelJPanelJPanel;;;;

public public public public classclassclassclass LinesRectsOvalsJPanelLinesRectsOvalsJPanelLinesRectsOvalsJPanelLinesRectsOvalsJPanel extendsextendsextendsextends JPanelJPanelJPanelJPanel

{{{{

// display // display // display // display variousvariousvariousvarious lineslineslineslines, , , , rectanglesrectanglesrectanglesrectangles andandandand ovalsovalsovalsovals

public public public public voidvoidvoidvoid paintComponentpaintComponentpaintComponentpaintComponent( ( ( ( GraphicsGraphicsGraphicsGraphics g )g )g )g )

{{{{

super.super.super.super.paintComponentpaintComponentpaintComponentpaintComponent( g ); // ( g ); // ( g ); // ( g ); // callcallcallcall superclasssuperclasssuperclasssuperclass's 's 's 's paintpaintpaintpaint methodmethodmethodmethod

thisthisthisthis....setBackgroundsetBackgroundsetBackgroundsetBackground( ( ( ( ColorColorColorColor.WHITE );.WHITE );.WHITE );.WHITE );

g.g.g.g.setColorsetColorsetColorsetColor( ( ( ( ColorColorColorColor.RED );.RED );.RED );.RED );

g.g.g.g.drawLinedrawLinedrawLinedrawLine( 5, 30, 380, 30 );( 5, 30, 380, 30 );( 5, 30, 380, 30 );( 5, 30, 380, 30 );

g.g.g.g.setColorsetColorsetColorsetColor( ( ( ( ColorColorColorColor.BLUE );.BLUE );.BLUE );.BLUE );

g.g.g.g.drawRectdrawRectdrawRectdrawRect( 5, 40, 90, 55 );( 5, 40, 90, 55 );( 5, 40, 90, 55 );( 5, 40, 90, 55 );

g.g.g.g.fillRectfillRectfillRectfillRect( 100, 40, 90, 55 );( 100, 40, 90, 55 );( 100, 40, 90, 55 );( 100, 40, 90, 55 );

g.g.g.g.setColorsetColorsetColorsetColor( ( ( ( ColorColorColorColor.BLACK );.BLACK );.BLACK );.BLACK );

g.g.g.g.fillRoundRectfillRoundRectfillRoundRectfillRoundRect( 195, 40, 90, 55, 50, 50 );( 195, 40, 90, 55, 50, 50 );( 195, 40, 90, 55, 50, 50 );( 195, 40, 90, 55, 50, 50 );

g.g.g.g.drawRoundRectdrawRoundRectdrawRoundRectdrawRoundRect( 290, 40, 90, 55, 20, 20 );( 290, 40, 90, 55, 20, 20 );( 290, 40, 90, 55, 20, 20 );( 290, 40, 90, 55, 20, 20 );

Osnova

51

g.g.g.g.setColorsetColorsetColorsetColor( ( ( ( ColorColorColorColor.YELLOW ); .YELLOW ); .YELLOW ); .YELLOW );

g.draw3DRect( 5, 100, 90, 55, g.draw3DRect( 5, 100, 90, 55, g.draw3DRect( 5, 100, 90, 55, g.draw3DRect( 5, 100, 90, 55, truetruetruetrue ););););

g.fill3DRect( 100, 100, 90, 55, g.fill3DRect( 100, 100, 90, 55, g.fill3DRect( 100, 100, 90, 55, g.fill3DRect( 100, 100, 90, 55, falsefalsefalsefalse ););););

g.g.g.g.setColorsetColorsetColorsetColor( ( ( ( ColorColorColorColor.MAGENTA );.MAGENTA );.MAGENTA );.MAGENTA );

g.g.g.g.drawOvaldrawOvaldrawOvaldrawOval( 195, 100, 90, 55 );( 195, 100, 90, 55 );( 195, 100, 90, 55 );( 195, 100, 90, 55 );

g.g.g.g.fillOvalfillOvalfillOvalfillOval( 290, 100, 90, 55 );( 290, 100, 90, 55 );( 290, 100, 90, 55 );( 290, 100, 90, 55 );

} // } // } // } // endendendend methodmethodmethodmethod paintComponentpaintComponentpaintComponentpaintComponent

} } } }

Osnova

52

import import import import javajavajavajava....awtawtawtawt....ColorColorColorColor;;;;

import import import import javaxjavaxjavaxjavax.swing..swing..swing..swing.JFrameJFrameJFrameJFrame;;;;

public public public public classclassclassclass LinesRectsOvalsLinesRectsOvalsLinesRectsOvalsLinesRectsOvals

{{{{

// // // // executeexecuteexecuteexecute applicationapplicationapplicationapplication

public static public static public static public static voidvoidvoidvoid mainmainmainmain( ( ( ( StringStringStringString argsargsargsargs[] )[] )[] )[] )

{{{{

// // // // createcreatecreatecreate frameframeframeframe forforforfor LinesRectsOvalsJPanelLinesRectsOvalsJPanelLinesRectsOvalsJPanelLinesRectsOvalsJPanel

JFrameJFrameJFrameJFrame frameframeframeframe = = = =

newnewnewnew JFrameJFrameJFrameJFrame( "( "( "( "DrawingDrawingDrawingDrawing lineslineslineslines, , , , rectanglesrectanglesrectanglesrectangles andandandand ovalsovalsovalsovals" );" );" );" );

frameframeframeframe....setDefaultCloseOperationsetDefaultCloseOperationsetDefaultCloseOperationsetDefaultCloseOperation( ( ( ( JFrameJFrameJFrameJFrame.EXIT_ON_CLOSE );.EXIT_ON_CLOSE );.EXIT_ON_CLOSE );.EXIT_ON_CLOSE );

LinesRectsOvalsJPanelLinesRectsOvalsJPanelLinesRectsOvalsJPanelLinesRectsOvalsJPanel linesRectsOvalsJPanellinesRectsOvalsJPanellinesRectsOvalsJPanellinesRectsOvalsJPanel = = = =

newnewnewnew LinesRectsOvalsJPanelLinesRectsOvalsJPanelLinesRectsOvalsJPanelLinesRectsOvalsJPanel(); (); (); ();

linesRectsOvalsJPanellinesRectsOvalsJPanellinesRectsOvalsJPanellinesRectsOvalsJPanel....setBackgroundsetBackgroundsetBackgroundsetBackground( ( ( ( ColorColorColorColor.WHITE ); .WHITE ); .WHITE ); .WHITE );

frameframeframeframe....addaddaddadd( ( ( ( linesRectsOvalsJPanellinesRectsOvalsJPanellinesRectsOvalsJPanellinesRectsOvalsJPanel ); // ); // ); // ); // addaddaddadd panel to panel to panel to panel to frameframeframeframe

frameframeframeframe....setSizesetSizesetSizesetSize( 400, 210 ); // set ( 400, 210 ); // set ( 400, 210 ); // set ( 400, 210 ); // set frameframeframeframe sizesizesizesize

frameframeframeframe....setVisiblesetVisiblesetVisiblesetVisible( ( ( ( truetruetruetrue ); // display ); // display ); // display ); // display frameframeframeframe

} // } // } // } // endendendend mainmainmainmain

} // } // } // } // endendendend classclassclassclass LinesRectsOvalsLinesRectsOvalsLinesRectsOvalsLinesRectsOvals

53

Šířka a výška oblouku pro zaoblené obdélníky

(x, y)

arc height

a rc width

w idth

height

54

Oval ohraničený obdélníkem

(x, y)

height

w id th

55

8. Kreslení oblouků - výsečí

• Arc - oblouk– část tvoří ovál

– měří se ve stupních

– Sweepspočet stupňů v obloukovém úhlu (arc angle)

– Sweep začíná u počátečního úhlu• Counterclockwise sweep je měřen v kladných stupních

• Clockwise sweep je měřen v záporných stupních

56

Kladné a záporné úhly oblouku

90°

0°180°

270°

90°

0°180°

270°

Kladné úhly Záporné úhly

57

Metody třídy Graphics pro kresleníoblouků

Method Description public void drawArc( int x, int y, int width, int height, int startAngle, int arcAngle )

Draws an arc relative to the bounding rectangle’s top-left coordinates (x, y) with the specified width and height. The arc segment is drawn starting at startAngle and sweeps arcAngle degrees.

public void fillArc( int x, int y, int width, int height, int startAngle, int arcAngle )

Draws a solid arc (i.e., a sector) relative to the bounding rectangle’s top-left coordinates (x, y) with the specified width and height. The arc segment is drawn starting at startAngle and sweeps arcAngle degrees.

Osnova

58

import import import import javajavajavajava....awtawtawtawt....ColorColorColorColor;;;;

import import import import javajavajavajava....awtawtawtawt....GraphicsGraphicsGraphicsGraphics;;;;

import import import import javaxjavaxjavaxjavax.swing..swing..swing..swing.JPanelJPanelJPanelJPanel;;;;

public public public public classclassclassclass ArcsJPanelArcsJPanelArcsJPanelArcsJPanel extendsextendsextendsextends JPanelJPanelJPanelJPanel

{{{{

// // // // drawdrawdrawdraw rectanglesrectanglesrectanglesrectangles andandandand arcsarcsarcsarcs

public public public public voidvoidvoidvoid paintComponentpaintComponentpaintComponentpaintComponent( ( ( ( GraphicsGraphicsGraphicsGraphics g )g )g )g )

{{{{

super.super.super.super.paintComponentpaintComponentpaintComponentpaintComponent( g ); // ( g ); // ( g ); // ( g ); // callcallcallcall superclasssuperclasssuperclasssuperclass's 's 's 's paintComponentpaintComponentpaintComponentpaintComponent

// start // start // start // start atatatat 0 0 0 0 andandandand sweepsweepsweepsweep 360 360 360 360 degreesdegreesdegreesdegrees

g.g.g.g.setColorsetColorsetColorsetColor( ( ( ( ColorColorColorColor.RED );.RED );.RED );.RED );

g.g.g.g.drawRectdrawRectdrawRectdrawRect( 15, 35, 80, 80 );( 15, 35, 80, 80 );( 15, 35, 80, 80 );( 15, 35, 80, 80 );

g.g.g.g.setColorsetColorsetColorsetColor( ( ( ( ColorColorColorColor.BLACK );.BLACK );.BLACK );.BLACK );

g.g.g.g.drawArcdrawArcdrawArcdrawArc( 15, 35, 80, 80, 0, 360 );( 15, 35, 80, 80, 0, 360 );( 15, 35, 80, 80, 0, 360 );( 15, 35, 80, 80, 0, 360 );

// start // start // start // start atatatat 0 0 0 0 andandandand sweepsweepsweepsweep 110 110 110 110 degreesdegreesdegreesdegrees

g.g.g.g.setColorsetColorsetColorsetColor( ( ( ( ColorColorColorColor.RED );.RED );.RED );.RED );

g.g.g.g.drawRectdrawRectdrawRectdrawRect( 100, 35, 80, 80 );( 100, 35, 80, 80 );( 100, 35, 80, 80 );( 100, 35, 80, 80 );

g.g.g.g.setColorsetColorsetColorsetColor( ( ( ( ColorColorColorColor.BLACK );.BLACK );.BLACK );.BLACK );

g.g.g.g.drawArcdrawArcdrawArcdrawArc( 100, 35, 80, 80, 0, 110 );( 100, 35, 80, 80, 0, 110 );( 100, 35, 80, 80, 0, 110 );( 100, 35, 80, 80, 0, 110 );

Osnova

59

// start // start // start // start atatatat 0 0 0 0 andandandand sweepsweepsweepsweep ----270 270 270 270 degreesdegreesdegreesdegrees

g.g.g.g.setColorsetColorsetColorsetColor( ( ( ( ColorColorColorColor.RED );.RED );.RED );.RED );

g.g.g.g.drawRectdrawRectdrawRectdrawRect( 185, 35, 80, 80 );( 185, 35, 80, 80 );( 185, 35, 80, 80 );( 185, 35, 80, 80 );

g.g.g.g.setColorsetColorsetColorsetColor( ( ( ( ColorColorColorColor.BLACK );.BLACK );.BLACK );.BLACK );

g.g.g.g.drawArcdrawArcdrawArcdrawArc( 185, 35, 80, 80, 0, ( 185, 35, 80, 80, 0, ( 185, 35, 80, 80, 0, ( 185, 35, 80, 80, 0, ----270 );270 );270 );270 );

// start // start // start // start atatatat 0 0 0 0 andandandand sweepsweepsweepsweep 360 360 360 360 degreesdegreesdegreesdegrees

g.g.g.g.fillArcfillArcfillArcfillArc( 15, 120, 80, 40, 0, 360 );( 15, 120, 80, 40, 0, 360 );( 15, 120, 80, 40, 0, 360 );( 15, 120, 80, 40, 0, 360 );

// start // start // start // start atatatat 270 270 270 270 andandandand sweepsweepsweepsweep ----90 90 90 90 degreesdegreesdegreesdegrees

g.g.g.g.fillArcfillArcfillArcfillArc( 100, 120, 80, 40, 270, ( 100, 120, 80, 40, 270, ( 100, 120, 80, 40, 270, ( 100, 120, 80, 40, 270, ----90 );90 );90 );90 );

// start // start // start // start atatatat 0 0 0 0 andandandand sweepsweepsweepsweep ----270 270 270 270 degreesdegreesdegreesdegrees

g.g.g.g.fillArcfillArcfillArcfillArc( 185, 120, 80, 40, 0, ( 185, 120, 80, 40, 0, ( 185, 120, 80, 40, 0, ( 185, 120, 80, 40, 0, ----270 );270 );270 );270 );

} // } // } // } // endendendend methodmethodmethodmethod paintComponentpaintComponentpaintComponentpaintComponent

} // } // } // } // endendendend classclassclassclass ArcsJPanelArcsJPanelArcsJPanelArcsJPanel

Osnova

60

import import import import javaxjavaxjavaxjavax.swing..swing..swing..swing.JFrameJFrameJFrameJFrame;;;;

public public public public classclassclassclass DrawArcsDrawArcsDrawArcsDrawArcs

{{{{

// // // // executeexecuteexecuteexecute applicationapplicationapplicationapplication

public static public static public static public static voidvoidvoidvoid mainmainmainmain( ( ( ( StringStringStringString argsargsargsargs[] )[] )[] )[] )

{{{{

// // // // createcreatecreatecreate frameframeframeframe forforforfor ArcsJPanelArcsJPanelArcsJPanelArcsJPanel

JFrameJFrameJFrameJFrame frameframeframeframe = = = = newnewnewnew JFrameJFrameJFrameJFrame( "( "( "( "DrawingDrawingDrawingDrawing ArcsArcsArcsArcs" );" );" );" );

frameframeframeframe....setDefaultCloseOperationsetDefaultCloseOperationsetDefaultCloseOperationsetDefaultCloseOperation( ( ( ( JFrameJFrameJFrameJFrame.EXIT_ON_CLOSE );.EXIT_ON_CLOSE );.EXIT_ON_CLOSE );.EXIT_ON_CLOSE );

ArcsJPanelArcsJPanelArcsJPanelArcsJPanel arcsJPanelarcsJPanelarcsJPanelarcsJPanel = = = = newnewnewnew ArcsJPanelArcsJPanelArcsJPanelArcsJPanel(); // (); // (); // (); // createcreatecreatecreate ArcsJPanelArcsJPanelArcsJPanelArcsJPanel

frameframeframeframe....addaddaddadd( ( ( ( arcsJPanelarcsJPanelarcsJPanelarcsJPanel ); // ); // ); // ); // addaddaddadd arcsJPanelarcsJPanelarcsJPanelarcsJPanel to to to to frameframeframeframe

frameframeframeframe....setSizesetSizesetSizesetSize( 300, 210 ); // set ( 300, 210 ); // set ( 300, 210 ); // set ( 300, 210 ); // set frameframeframeframe sizesizesizesize

frameframeframeframe....setVisiblesetVisiblesetVisiblesetVisible( ( ( ( truetruetruetrue ); // display ); // display ); // display ); // display frameframeframeframe

} // } // } // } // endendendend mainmainmainmain

} // } // } // } // endendendend classclassclassclass DrawArcsDrawArcsDrawArcsDrawArcs

61

9. Kreslení polygonů a lomených čarPolygons and Polylines

• TřídaPolygon– Polygons

• Vícestranné tvary (multisided shapes)

– Polylines• Řada spojených bodů

62

Metody třídy Graphics pro kreslenípolygonů a statické metody třídy Polygon

Metody Popis Metody třídy Graphics pro kreslení polygonů

public void drawPolygon( int xPoints[], int yPoints[], int points )

Nakreslí polygon. x-souřadnice každého bodu jsou specifikovány v poli xPoints, obdobně y-souřadnice. Poslední argument specifikuje počet bodů.. Metoda kreslí uzavřený polygon. Pokud se poslední a první bod liší, pak oba body spojí čára.

public void drawPolyline( int xPoints[], int yPoints[], int points )

Draws a sequence of connected lines. The x-coordinate of each point is specified in the xPoints array and the y-coordinate of each point is specified in the yPoints array. The last argument specifies the number of points. If the last point is different from the first point, the polyline is not closed.

public void drawPolygon( Polygon p )

Draws the specified polygon.

public void fillPolygon( int xPoints[], int yPoints[], int points )

Draws a solid polygon. The x-coordinate of each point is specified in the xPoints array and the y-coordinate of each point is specified in the yPoints array. The last argument specifies the number of points. This method draws a closed polygon. If the last point is different from the first point, the polygon is closed by a line that connects the last point to the first point.

public void fillPolygon( Polygon p )

Draws the specified solid polygon. The polygon is closed.

63

Metody třídy Graphics pro kreslenípolygonů a statické metody třídy Polygon

Method Description Polygon constructors and methods public Polygon()

Constructs a new polygon object. The polygon does not contain any points.

public Polygon( int xValues[], int yValues[], int numberOfPoints )

Constructs a new polygon object. The polygon has numberOfPoints sides, with each point consisting of an x-coordinate from xValues and a y-coordinate from yValues.

public void addPoint( int x, int y )

Adds pairs of x- and y-coordinates to the Polygon.

Osnova

64

import import import import javajavajavajava....awtawtawtawt....GraphicsGraphicsGraphicsGraphics;;;;

import import import import javajavajavajava....awtawtawtawt.Polygon;.Polygon;.Polygon;.Polygon;

import import import import javaxjavaxjavaxjavax.swing..swing..swing..swing.JPanelJPanelJPanelJPanel;;;;

public public public public classclassclassclass PolygonsJPanelPolygonsJPanelPolygonsJPanelPolygonsJPanel extendsextendsextendsextends JPanelJPanelJPanelJPanel

{{{{

// // // // drawdrawdrawdraw polygonspolygonspolygonspolygons andandandand polylinespolylinespolylinespolylines

public public public public voidvoidvoidvoid paintComponentpaintComponentpaintComponentpaintComponent( ( ( ( GraphicsGraphicsGraphicsGraphics g )g )g )g )

{{{{

super.super.super.super.paintComponentpaintComponentpaintComponentpaintComponent( g ); // ( g ); // ( g ); // ( g ); // callcallcallcall superclasssuperclasssuperclasssuperclass's 's 's 's paintComponentpaintComponentpaintComponentpaintComponent

// // // // drawdrawdrawdraw polygon polygon polygon polygon withwithwithwith Polygon Polygon Polygon Polygon objectobjectobjectobject

intintintint xValuesxValuesxValuesxValues[] = { 20, 40, 50, 30, 20, 15 };[] = { 20, 40, 50, 30, 20, 15 };[] = { 20, 40, 50, 30, 20, 15 };[] = { 20, 40, 50, 30, 20, 15 };

intintintint yValuesyValuesyValuesyValues[] = { 50, 50, 60, 80, 80, 60 };[] = { 50, 50, 60, 80, 80, 60 };[] = { 50, 50, 60, 80, 80, 60 };[] = { 50, 50, 60, 80, 80, 60 };

Polygon polygon1 = Polygon polygon1 = Polygon polygon1 = Polygon polygon1 = newnewnewnew Polygon( Polygon( Polygon( Polygon( xValuesxValuesxValuesxValues, , , , yValuesyValuesyValuesyValues, 6 );, 6 );, 6 );, 6 );

g.g.g.g.drawPolygondrawPolygondrawPolygondrawPolygon( polygon1 );( polygon1 );( polygon1 );( polygon1 );

// // // // drawdrawdrawdraw polylinespolylinespolylinespolylines withwithwithwith twotwotwotwo arraysarraysarraysarrays

intintintint xValues2[] = { 70, 90, 100, 80, 70, 65, 60 };xValues2[] = { 70, 90, 100, 80, 70, 65, 60 };xValues2[] = { 70, 90, 100, 80, 70, 65, 60 };xValues2[] = { 70, 90, 100, 80, 70, 65, 60 };

intintintint yValues2[] = { 100, 100, 110, 110, 130, 110, 90 };yValues2[] = { 100, 100, 110, 110, 130, 110, 90 };yValues2[] = { 100, 100, 110, 110, 130, 110, 90 };yValues2[] = { 100, 100, 110, 110, 130, 110, 90 };

g.g.g.g.drawPolylinedrawPolylinedrawPolylinedrawPolyline( xValues2, yValues2, 7 );( xValues2, yValues2, 7 );( xValues2, yValues2, 7 );( xValues2, yValues2, 7 );

// // // // fillfillfillfill polygon polygon polygon polygon withwithwithwith twotwotwotwo arraysarraysarraysarrays

intintintint xValues3[] = { 120, 140, 150, 190 };xValues3[] = { 120, 140, 150, 190 };xValues3[] = { 120, 140, 150, 190 };xValues3[] = { 120, 140, 150, 190 };

intintintint yValues3[] = { 40, 70, 80, 60 };yValues3[] = { 40, 70, 80, 60 };yValues3[] = { 40, 70, 80, 60 };yValues3[] = { 40, 70, 80, 60 };

g.g.g.g.fillPolygonfillPolygonfillPolygonfillPolygon( xValues3, yValues3, 4 );( xValues3, yValues3, 4 );( xValues3, yValues3, 4 );( xValues3, yValues3, 4 );

Osnova

65

// // // // drawdrawdrawdraw filledfilledfilledfilled polygon polygon polygon polygon withwithwithwith Polygon Polygon Polygon Polygon objectobjectobjectobject

Polygon polygon2 = Polygon polygon2 = Polygon polygon2 = Polygon polygon2 = newnewnewnew Polygon();Polygon();Polygon();Polygon();

polygon2.polygon2.polygon2.polygon2.addPointaddPointaddPointaddPoint( 165, 135 );( 165, 135 );( 165, 135 );( 165, 135 );

polygon2.polygon2.polygon2.polygon2.addPointaddPointaddPointaddPoint( 175, 150 );( 175, 150 );( 175, 150 );( 175, 150 );

polygon2.polygon2.polygon2.polygon2.addPointaddPointaddPointaddPoint( 270, 200 );( 270, 200 );( 270, 200 );( 270, 200 );

polygon2.polygon2.polygon2.polygon2.addPointaddPointaddPointaddPoint( 200, 220 );( 200, 220 );( 200, 220 );( 200, 220 );

polygon2.polygon2.polygon2.polygon2.addPointaddPointaddPointaddPoint( 130, 180 );( 130, 180 );( 130, 180 );( 130, 180 );

g.g.g.g.fillPolygonfillPolygonfillPolygonfillPolygon( polygon2 );( polygon2 );( polygon2 );( polygon2 );

} // } // } // } // endendendend methodmethodmethodmethod paintComponentpaintComponentpaintComponentpaintComponent

} // } // } // } // endendendend classclassclassclass PolygonsJPanelPolygonsJPanelPolygonsJPanelPolygonsJPanel

Osnova

66

import import import import javaxjavaxjavaxjavax.swing..swing..swing..swing.JFrameJFrameJFrameJFrame;;;;

public public public public classclassclassclass DrawPolygonsDrawPolygonsDrawPolygonsDrawPolygons

{{{{

// // // // executeexecuteexecuteexecute applicationapplicationapplicationapplication

public static public static public static public static voidvoidvoidvoid mainmainmainmain( ( ( ( StringStringStringString argsargsargsargs[] )[] )[] )[] )

{{{{

// // // // createcreatecreatecreate frameframeframeframe forforforfor PolygonsJPanelPolygonsJPanelPolygonsJPanelPolygonsJPanel

JFrameJFrameJFrameJFrame frameframeframeframe = = = = newnewnewnew JFrameJFrameJFrameJFrame( "( "( "( "DrawingDrawingDrawingDrawing PolygonsPolygonsPolygonsPolygons" );" );" );" );

frameframeframeframe....setDefaultCloseOperationsetDefaultCloseOperationsetDefaultCloseOperationsetDefaultCloseOperation( ( ( ( JFrameJFrameJFrameJFrame.EXIT_ON_CLOSE );.EXIT_ON_CLOSE );.EXIT_ON_CLOSE );.EXIT_ON_CLOSE );

PolygonsJPanelPolygonsJPanelPolygonsJPanelPolygonsJPanel polygonsJPanelpolygonsJPanelpolygonsJPanelpolygonsJPanel = = = = newnewnewnew PolygonsJPanelPolygonsJPanelPolygonsJPanelPolygonsJPanel(); (); (); ();

frameframeframeframe....addaddaddadd( ( ( ( polygonsJPanelpolygonsJPanelpolygonsJPanelpolygonsJPanel ); // ); // ); // ); // addaddaddadd polygonsJPanelpolygonsJPanelpolygonsJPanelpolygonsJPanel to to to to frameframeframeframe

frameframeframeframe....setSizesetSizesetSizesetSize( 280, 270 ); // set ( 280, 270 ); // set ( 280, 270 ); // set ( 280, 270 ); // set frameframeframeframe sizesizesizesize

frameframeframeframe....setVisiblesetVisiblesetVisiblesetVisible( ( ( ( truetruetruetrue ); // display ); // display ); // display ); // display frameframeframeframe

} // } // } // } // endendendend mainmainmainmain

} } } }

Osnova

67

Kresleníkomplexních tvarů

import import import import javajavajavajava....awtawtawtawt....ColorColorColorColor;;;;

import import import import javajavajavajava....awtawtawtawt....GraphicsGraphicsGraphicsGraphics;;;;

import import import import javajavajavajava....awtawtawtawt....BasicStrokeBasicStrokeBasicStrokeBasicStroke;;;;

import import import import javajavajavajava....awtawtawtawt....GradientPaintGradientPaintGradientPaintGradientPaint;;;;

import import import import javajavajavajava....awtawtawtawt....TexturePaintTexturePaintTexturePaintTexturePaint;;;;

import import import import javajavajavajava....awtawtawtawt....RectangleRectangleRectangleRectangle;;;;

import import import import javajavajavajava....awtawtawtawt.Graphics2D;.Graphics2D;.Graphics2D;.Graphics2D;

import import import import javajavajavajava....awtawtawtawt....geomgeomgeomgeom.Ellipse2D;.Ellipse2D;.Ellipse2D;.Ellipse2D;

import import import import javajavajavajava....awtawtawtawt....geomgeomgeomgeom.Rectangle2D;.Rectangle2D;.Rectangle2D;.Rectangle2D;

import import import import javajavajavajava....awtawtawtawt....geomgeomgeomgeom.RoundRectangle2D;.RoundRectangle2D;.RoundRectangle2D;.RoundRectangle2D;

import import import import javajavajavajava....awtawtawtawt....geomgeomgeomgeom.Arc2D;.Arc2D;.Arc2D;.Arc2D;

import import import import javajavajavajava....awtawtawtawt....geomgeomgeomgeom.Line2D;.Line2D;.Line2D;.Line2D;

import import import import javajavajavajava....awtawtawtawt....imageimageimageimage....BufferedImageBufferedImageBufferedImageBufferedImage;;;;

import import import import javaxjavaxjavaxjavax.swing..swing..swing..swing.JPanelJPanelJPanelJPanel;;;;

public public public public classclassclassclass ShapesJPanelShapesJPanelShapesJPanelShapesJPanel extendsextendsextendsextends JPanelJPanelJPanelJPanel

{{{{

// // // // drawdrawdrawdraw shapesshapesshapesshapes withwithwithwith Java 2D APIJava 2D APIJava 2D APIJava 2D API

public public public public voidvoidvoidvoid paintComponentpaintComponentpaintComponentpaintComponent( ( ( ( GraphicsGraphicsGraphicsGraphics g )g )g )g )

{{{{

super.super.super.super.paintComponentpaintComponentpaintComponentpaintComponent( g ); // ( g ); // ( g ); // ( g ); // callcallcallcall superclasssuperclasssuperclasssuperclass's 's 's 's paintComponentpaintComponentpaintComponentpaintComponent

Graphics2D g2d = ( Graphics2D ) g; // Graphics2D g2d = ( Graphics2D ) g; // Graphics2D g2d = ( Graphics2D ) g; // Graphics2D g2d = ( Graphics2D ) g; // castcastcastcast g to Graphics2Dg to Graphics2Dg to Graphics2Dg to Graphics2D

// // // // drawdrawdrawdraw 2D 2D 2D 2D ellipseellipseellipseellipse filledfilledfilledfilled withwithwithwith a a a a blueblueblueblue----yellowyellowyellowyellow gradientgradientgradientgradient

g2d.g2d.g2d.g2d.setPaintsetPaintsetPaintsetPaint( ( ( ( newnewnewnew GradientPaintGradientPaintGradientPaintGradientPaint( 5, 30, ( 5, 30, ( 5, 30, ( 5, 30, ColorColorColorColor.BLUE, 35, 100, .BLUE, 35, 100, .BLUE, 35, 100, .BLUE, 35, 100,

ColorColorColorColor.YELLOW, .YELLOW, .YELLOW, .YELLOW, truetruetruetrue ) ); ) ); ) ); ) );

g2d.g2d.g2d.g2d.fillfillfillfill( ( ( ( newnewnewnew Ellipse2D.Double( 5, 30, 65, 100 ) );Ellipse2D.Double( 5, 30, 65, 100 ) );Ellipse2D.Double( 5, 30, 65, 100 ) );Ellipse2D.Double( 5, 30, 65, 100 ) );

Osnova

68

// // // // drawdrawdrawdraw 2D 2D 2D 2D rectanglerectanglerectanglerectangle in in in in redredredred

g2d.g2d.g2d.g2d.setPaintsetPaintsetPaintsetPaint( ( ( ( ColorColorColorColor.RED ); .RED ); .RED ); .RED );

g2d.g2d.g2d.g2d.setStrokesetStrokesetStrokesetStroke( ( ( ( newnewnewnew BasicStrokeBasicStrokeBasicStrokeBasicStroke( 10.0f ) ); ( 10.0f ) ); ( 10.0f ) ); ( 10.0f ) );

g2d.g2d.g2d.g2d.drawdrawdrawdraw( ( ( ( newnewnewnew Rectangle2D.Double( 80, 30, 65, 100 ) );Rectangle2D.Double( 80, 30, 65, 100 ) );Rectangle2D.Double( 80, 30, 65, 100 ) );Rectangle2D.Double( 80, 30, 65, 100 ) );

// // // // drawdrawdrawdraw 2D 2D 2D 2D roundedroundedroundedrounded rectanglerectanglerectanglerectangle withwithwithwith a a a a bufferedbufferedbufferedbuffered backgroundbackgroundbackgroundbackground

BufferedImageBufferedImageBufferedImageBufferedImage buffImagebuffImagebuffImagebuffImage = = = = newnewnewnew BufferedImageBufferedImageBufferedImageBufferedImage( 10, 10, ( 10, 10, ( 10, 10, ( 10, 10,

BufferedImageBufferedImageBufferedImageBufferedImage.TYPE_INT_RGB );.TYPE_INT_RGB );.TYPE_INT_RGB );.TYPE_INT_RGB );

// // // // obtainobtainobtainobtain Graphics2D Graphics2D Graphics2D Graphics2D fromfromfromfrom bufferImagebufferImagebufferImagebufferImage andandandand drawdrawdrawdraw on on on on itititit

Graphics2D Graphics2D Graphics2D Graphics2D gggggggg = = = = buffImagebuffImagebuffImagebuffImage....createGraphicscreateGraphicscreateGraphicscreateGraphics(); (); (); ();

gggggggg....setColorsetColorsetColorsetColor( ( ( ( ColorColorColorColor.YELLOW ); // .YELLOW ); // .YELLOW ); // .YELLOW ); // drawdrawdrawdraw in in in in yellowyellowyellowyellow

gggggggg....fillRectfillRectfillRectfillRect( 0, 0, 10, 10 ); // ( 0, 0, 10, 10 ); // ( 0, 0, 10, 10 ); // ( 0, 0, 10, 10 ); // drawdrawdrawdraw a a a a filledfilledfilledfilled rectanglerectanglerectanglerectangle

gggggggg....setColorsetColorsetColorsetColor( ( ( ( ColorColorColorColor.BLACK ); // .BLACK ); // .BLACK ); // .BLACK ); // drawdrawdrawdraw in in in in blackblackblackblack

gggggggg....drawRectdrawRectdrawRectdrawRect( 1, 1, 6, 6 ); // ( 1, 1, 6, 6 ); // ( 1, 1, 6, 6 ); // ( 1, 1, 6, 6 ); // drawdrawdrawdraw a a a a rectanglerectanglerectanglerectangle

gggggggg....setColorsetColorsetColorsetColor( ( ( ( ColorColorColorColor.BLUE ); // .BLUE ); // .BLUE ); // .BLUE ); // drawdrawdrawdraw in in in in blueblueblueblue

gggggggg....fillRectfillRectfillRectfillRect( 1, 1, 3, 3 ); // ( 1, 1, 3, 3 ); // ( 1, 1, 3, 3 ); // ( 1, 1, 3, 3 ); // drawdrawdrawdraw a a a a filledfilledfilledfilled rectanglerectanglerectanglerectangle

gggggggg....setColorsetColorsetColorsetColor( ( ( ( ColorColorColorColor.RED ); // .RED ); // .RED ); // .RED ); // drawdrawdrawdraw in in in in redredredred

gggggggg....fillRectfillRectfillRectfillRect( 4, 4, 3, 3 ); // ( 4, 4, 3, 3 ); // ( 4, 4, 3, 3 ); // ( 4, 4, 3, 3 ); // drawdrawdrawdraw a a a a filledfilledfilledfilled rectanglerectanglerectanglerectangle

// // // // paintpaintpaintpaint buffImagebuffImagebuffImagebuffImage ontoontoontoonto thethethethe JFrameJFrameJFrameJFrame

g2d.g2d.g2d.g2d.setPaintsetPaintsetPaintsetPaint( ( ( ( newnewnewnew TexturePaintTexturePaintTexturePaintTexturePaint( ( ( ( buffImagebuffImagebuffImagebuffImage, , , ,

newnewnewnew RectangleRectangleRectangleRectangle( 10, 10 ) ) );( 10, 10 ) ) );( 10, 10 ) ) );( 10, 10 ) ) );

g2d.g2d.g2d.g2d.fillfillfillfill((((

newnewnewnew RoundRectangle2D.Double( 155, 30, 75, 100, 50, 50 ) );RoundRectangle2D.Double( 155, 30, 75, 100, 50, 50 ) );RoundRectangle2D.Double( 155, 30, 75, 100, 50, 50 ) );RoundRectangle2D.Double( 155, 30, 75, 100, 50, 50 ) );

Osnova

69

// // // // drawdrawdrawdraw 2D 2D 2D 2D piepiepiepie----shapedshapedshapedshaped arcarcarcarc in in in in whitewhitewhitewhite

g2d.g2d.g2d.g2d.setPaintsetPaintsetPaintsetPaint( ( ( ( ColorColorColorColor.WHITE );.WHITE );.WHITE );.WHITE );

g2d.g2d.g2d.g2d.setStrokesetStrokesetStrokesetStroke( ( ( ( newnewnewnew BasicStrokeBasicStrokeBasicStrokeBasicStroke( 6.0f ) ); ( 6.0f ) ); ( 6.0f ) ); ( 6.0f ) );

g2d.g2d.g2d.g2d.drawdrawdrawdraw((((

newnewnewnew Arc2D.Double( 240, 30, 75, 100, 0, 270, Arc2D.PIE ) );Arc2D.Double( 240, 30, 75, 100, 0, 270, Arc2D.PIE ) );Arc2D.Double( 240, 30, 75, 100, 0, 270, Arc2D.PIE ) );Arc2D.Double( 240, 30, 75, 100, 0, 270, Arc2D.PIE ) );

// // // // drawdrawdrawdraw 2D 2D 2D 2D lineslineslineslines in in in in greengreengreengreen andandandand yellowyellowyellowyellow

g2d.g2d.g2d.g2d.setPaintsetPaintsetPaintsetPaint( ( ( ( ColorColorColorColor.GREEN );.GREEN );.GREEN );.GREEN );

g2d.g2d.g2d.g2d.drawdrawdrawdraw( ( ( ( newnewnewnew Line2D.Double( 395, 30, 320, 150 ) );Line2D.Double( 395, 30, 320, 150 ) );Line2D.Double( 395, 30, 320, 150 ) );Line2D.Double( 395, 30, 320, 150 ) );

// // // // drawdrawdrawdraw 2D line 2D line 2D line 2D line usingusingusingusing strokestrokestrokestroke

floatfloatfloatfloat dashesdashesdashesdashes[] = { 10 }; // [] = { 10 }; // [] = { 10 }; // [] = { 10 }; // specifyspecifyspecifyspecify dashdashdashdash patternpatternpatternpattern

g2d.g2d.g2d.g2d.setPaintsetPaintsetPaintsetPaint( ( ( ( ColorColorColorColor.YELLOW ); .YELLOW ); .YELLOW ); .YELLOW );

g2d.g2d.g2d.g2d.setStrokesetStrokesetStrokesetStroke( ( ( ( newnewnewnew BasicStrokeBasicStrokeBasicStrokeBasicStroke( 4, ( 4, ( 4, ( 4, BasicStrokeBasicStrokeBasicStrokeBasicStroke.CAP_ROUND,.CAP_ROUND,.CAP_ROUND,.CAP_ROUND,

BasicStrokeBasicStrokeBasicStrokeBasicStroke.JOIN_ROUND, 10, .JOIN_ROUND, 10, .JOIN_ROUND, 10, .JOIN_ROUND, 10, dashesdashesdashesdashes, 0 ) ); , 0 ) ); , 0 ) ); , 0 ) );

g2d.g2d.g2d.g2d.drawdrawdrawdraw( ( ( ( newnewnewnew Line2D.Double( 320, 30, 395, 150 ) );Line2D.Double( 320, 30, 395, 150 ) );Line2D.Double( 320, 30, 395, 150 ) );Line2D.Double( 320, 30, 395, 150 ) );

} // } // } // } // endendendend methodmethodmethodmethod paintComponentpaintComponentpaintComponentpaintComponent

} // } // } // } // endendendend classclassclassclass ShapesJPanelShapesJPanelShapesJPanelShapesJPanel

Osnova

70

import import import import javaxjavaxjavaxjavax.swing..swing..swing..swing.JFrameJFrameJFrameJFrame;;;;

public public public public classclassclassclass ShapesShapesShapesShapes

{{{{

// // // // executeexecuteexecuteexecute applicationapplicationapplicationapplication

public static public static public static public static voidvoidvoidvoid mainmainmainmain( ( ( ( StringStringStringString argsargsargsargs[] )[] )[] )[] )

{{{{

// // // // createcreatecreatecreate frameframeframeframe forforforfor ShapesJPanelShapesJPanelShapesJPanelShapesJPanel

JFrameJFrameJFrameJFrame frameframeframeframe = = = = newnewnewnew JFrameJFrameJFrameJFrame( "( "( "( "DrawingDrawingDrawingDrawing 2D 2D 2D 2D shapesshapesshapesshapes" );" );" );" );

frameframeframeframe....setDefaultCloseOperationsetDefaultCloseOperationsetDefaultCloseOperationsetDefaultCloseOperation( ( ( ( JFrameJFrameJFrameJFrame.EXIT_ON_CLOSE );.EXIT_ON_CLOSE );.EXIT_ON_CLOSE );.EXIT_ON_CLOSE );

// // // // createcreatecreatecreate ShapesJPanelShapesJPanelShapesJPanelShapesJPanel

ShapesJPanelShapesJPanelShapesJPanelShapesJPanel shapesJPanelshapesJPanelshapesJPanelshapesJPanel = = = = newnewnewnew ShapesJPanelShapesJPanelShapesJPanelShapesJPanel();();();();

frameframeframeframe....addaddaddadd( ( ( ( shapesJPanelshapesJPanelshapesJPanelshapesJPanel ); // ); // ); // ); // addaddaddadd shapesJPanelshapesJPanelshapesJPanelshapesJPanel to to to to frameframeframeframe

frameframeframeframe....setSizesetSizesetSizesetSize( 425, 200 ); // set ( 425, 200 ); // set ( 425, 200 ); // set ( 425, 200 ); // set frameframeframeframe sizesizesizesize

frameframeframeframe....setVisiblesetVisiblesetVisiblesetVisible( ( ( ( truetruetruetrue ); // display ); // display ); // display ); // display frameframeframeframe

} // } // } // } // endendendend mainmainmainmain

} // } // } // } // endendendend classclassclassclass ShapesShapesShapesShapes

71

10. Třída JTable

• Celá aplikace používá třídu javax.swing.JTable –která zobrazí data v dvourozměrné tabulce

• JTable využívá architekturu MVC (model viewcontroller) a uživatel může využít DefaultTableModel pokud nechce dělat úpravy

• Aplikace vytváří DefaultTableModel s 11 sloupci

Osnova

72

import import import import javajavajavajava....utilutilutilutil.*;.*;.*;.*;

import import import import javajavajavajava....awtawtawtawt.*;.*;.*;.*;

import import import import javajavajavajava....awtawtawtawt....eventeventeventevent.*;.*;.*;.*;

import import import import javaxjavaxjavaxjavax.swing.*;.swing.*;.swing.*;.swing.*;

import import import import javaxjavaxjavaxjavax.swing.table.*;.swing.table.*;.swing.table.*;.swing.table.*;

public public public public classclassclassclass EmpGUIEmpGUIEmpGUIEmpGUI extendsextendsextendsextends JFrameJFrameJFrameJFrame {{{{

//*** instance //*** instance //*** instance //*** instance fieldsfieldsfieldsfields

private private private private ContainerContainerContainerContainer contcontcontcont;;;;

private private private private JTableJTableJTableJTable table;table;table;table;

private private private private DefaultTableModelDefaultTableModelDefaultTableModelDefaultTableModel dm;dm;dm;dm;

private private private private EmpRWEmpRWEmpRWEmpRW empRWempRWempRWempRW;;;;

private private private private StringStringStringString infileNameinfileNameinfileNameinfileName;;;;

private private private private StringStringStringString outfileNameoutfileNameoutfileNameoutfileName;;;;

//*** //*** //*** //*** classclassclassclass fieldsfieldsfieldsfields

private static private static private static private static finalfinalfinalfinal StringStringStringString readStringreadStringreadStringreadString = " = " = " = " ReadReadReadRead FileFileFileFile ";";";";

private static private static private static private static finalfinalfinalfinal StringStringStringString writeStringwriteStringwriteStringwriteString = " = " = " = " WriteWriteWriteWrite FileFileFileFile ";";";";

private static private static private static private static finalfinalfinalfinal StringStringStringString exitStringexitStringexitStringexitString = " Exit ";= " Exit ";= " Exit ";= " Exit ";

//** //** //** //** ConstructConstructConstructConstruct thethethethe GUI, GUI, GUI, GUI, includingincludingincludingincluding controlscontrolscontrolscontrols andandandand a a a a JTableJTableJTableJTable,,,,

// // // // andandandand display display display display thethethethe GUI GUI GUI GUI automaticallyautomaticallyautomaticallyautomatically....

// Syntax: // Syntax: // Syntax: // Syntax: newnewnewnew EmpGUIEmpGUIEmpGUIEmpGUI()()()()

public public public public EmpGUIEmpGUIEmpGUIEmpGUI() {() {() {() {

super( "super( "super( "super( "EmployeeEmployeeEmployeeEmployee Edit Edit Edit Edit ApplicationApplicationApplicationApplication" ); " ); " ); " );

setSizesetSizesetSizesetSize( 900, 350 ); ( 900, 350 ); ( 900, 350 ); ( 900, 350 );

contcontcontcont = = = = getContentPanegetContentPanegetContentPanegetContentPane(); (); (); ();

initControlsinitControlsinitControlsinitControls();();();();

initTableinitTableinitTableinitTable();();();();

setVisiblesetVisiblesetVisiblesetVisible((((truetruetruetrue););););

}}}}

Osnova

73

//** //** //** //** AddAddAddAdd buttonsbuttonsbuttonsbuttons to to to to readreadreadread, , , , writewritewritewrite, , , , andandandand exit.exit.exit.exit.

// // // // AddAddAddAdd actionactionactionaction listenerslistenerslistenerslisteners per per per per buttonbuttonbuttonbutton....

private private private private voidvoidvoidvoid initControlsinitControlsinitControlsinitControls() {() {() {() {

JButtonJButtonJButtonJButton b;b;b;b;

JPanelJPanelJPanelJPanel controlscontrolscontrolscontrols = = = = newnewnewnew JPanelJPanelJPanelJPanel(); (); (); ();

controlscontrolscontrolscontrols....setLayoutsetLayoutsetLayoutsetLayout( ( ( ( newnewnewnew FlowLayoutFlowLayoutFlowLayoutFlowLayout() ); () ); () ); () );

b = b = b = b = addButtonaddButtonaddButtonaddButton( ( ( ( controlscontrolscontrolscontrols, , , , readStringreadStringreadStringreadString ););););

b.b.b.b.addActionListeneraddActionListeneraddActionListeneraddActionListener( ( ( ( newnewnewnew ActionListenerActionListenerActionListenerActionListener() {() {() {() {

public public public public voidvoidvoidvoid actionPerformedactionPerformedactionPerformedactionPerformed( ( ( ( ActionEventActionEventActionEventActionEvent e ) { e ) { e ) { e ) { readreadreadread(); } (); } (); } (); }

} ); } ); } ); } );

b = b = b = b = addButtonaddButtonaddButtonaddButton( ( ( ( controlscontrolscontrolscontrols, , , , writeStringwriteStringwriteStringwriteString ); ); ); );

b.b.b.b.addActionListeneraddActionListeneraddActionListeneraddActionListener( ( ( ( newnewnewnew ActionListenerActionListenerActionListenerActionListener() {() {() {() {

public public public public voidvoidvoidvoid actionPerformedactionPerformedactionPerformedactionPerformed( ( ( ( ActionEventActionEventActionEventActionEvent e ) { e ) { e ) { e ) { writewritewritewrite(); } (); } (); } (); }

} ); } ); } ); } );

b = b = b = b = addButtonaddButtonaddButtonaddButton( ( ( ( controlscontrolscontrolscontrols, , , , exitStringexitStringexitStringexitString ); ); ); );

b.b.b.b.addActionListeneraddActionListeneraddActionListeneraddActionListener( ( ( ( newnewnewnew ActionListenerActionListenerActionListenerActionListener() {() {() {() {

public public public public voidvoidvoidvoid actionPerformedactionPerformedactionPerformedactionPerformed( ( ( ( ActionEventActionEventActionEventActionEvent e ) { e ) { e ) { e ) {

SystemSystemSystemSystem.exit( 0 ); } .exit( 0 ); } .exit( 0 ); } .exit( 0 ); }

} ); } ); } ); } );

contcontcontcont....addaddaddadd( ( ( ( controlscontrolscontrolscontrols, , , , BorderLayoutBorderLayoutBorderLayoutBorderLayout.NORTH ); .NORTH ); .NORTH ); .NORTH );

}}}}

Osnova

74

//** //** //** //** CreateCreateCreateCreate anananan emptyemptyemptyempty JTableJTableJTableJTable to hold to hold to hold to hold thethethethe employeeemployeeemployeeemployee recordsrecordsrecordsrecords

private private private private voidvoidvoidvoid initTableinitTableinitTableinitTable() {() {() {() {

StringStringStringString[ ] [ ] [ ] [ ] colscolscolscols = { "CODE", "ID", "LNAME", "FNAME", "DEPT", = { "CODE", "ID", "LNAME", "FNAME", "DEPT", = { "CODE", "ID", "LNAME", "FNAME", "DEPT", = { "CODE", "ID", "LNAME", "FNAME", "DEPT",

"TITLE", "RPTS", "DISC", "OPTS", "HR", "OT" };"TITLE", "RPTS", "DISC", "OPTS", "HR", "OT" };"TITLE", "RPTS", "DISC", "OPTS", "HR", "OT" };"TITLE", "RPTS", "DISC", "OPTS", "HR", "OT" };

dm = dm = dm = dm = newnewnewnew DefaultTableModelDefaultTableModelDefaultTableModelDefaultTableModel( ( ( ( colscolscolscols, 0 ); , 0 ); , 0 ); , 0 );

table = table = table = table = newnewnewnew JTableJTableJTableJTable( dm );( dm );( dm );( dm );

table.table.table.table.getTableHeadergetTableHeadergetTableHeadergetTableHeader().().().().setFontsetFontsetFontsetFont( ( ( ( newnewnewnew Font( "Dialog", Font( "Dialog", Font( "Dialog", Font( "Dialog",

Font.BOLD, 12 )Font.BOLD, 12 )Font.BOLD, 12 )Font.BOLD, 12 ) ); ); ); );

contcontcontcont....addaddaddadd( ( ( ( newnewnewnew JScrollPaneJScrollPaneJScrollPaneJScrollPane( table ), ( table ), ( table ), ( table ), BorderLayoutBorderLayoutBorderLayoutBorderLayout.CENTER ); .CENTER ); .CENTER ); .CENTER );

}}}}

//** //** //** //** AddAddAddAdd thethethethe namednamednamednamed buttonbuttonbuttonbutton to a panelto a panelto a panelto a panel

private private private private JButtonJButtonJButtonJButton addButtonaddButtonaddButtonaddButton( ( ( ( JPanelJPanelJPanelJPanel p, p, p, p, StringStringStringString namenamenamename ) {) {) {) {

JButtonJButtonJButtonJButton b = b = b = b = newnewnewnew JButtonJButtonJButtonJButton( ( ( ( namenamenamename ););););

b.b.b.b.setFontsetFontsetFontsetFont( ( ( ( newnewnewnew Font( "Dialog", Font.BOLD, 14 ) );Font( "Dialog", Font.BOLD, 14 ) );Font( "Dialog", Font.BOLD, 14 ) );Font( "Dialog", Font.BOLD, 14 ) );

p.p.p.p.addaddaddadd( b ); ( b ); ( b ); ( b );

returnreturnreturnreturn b; b; b; b;

}}}}

//** Use //** Use //** Use //** Use anananan EmpRWEmpRWEmpRWEmpRW objectobjectobjectobject to to to to readreadreadread recordsrecordsrecordsrecords fromfromfromfrom a a a a

// // // // specifiedspecifiedspecifiedspecified inputinputinputinput filefilefilefile. . . . AddAddAddAdd thethethethe recordsrecordsrecordsrecords to to to to thethethethe JTableJTableJTableJTable....

private private private private voidvoidvoidvoid readreadreadread() {() {() {() {

clearRowsclearRowsclearRowsclearRows(); (); (); ();

JFileChooserJFileChooserJFileChooserJFileChooser fcfcfcfc = = = = newnewnewnew JFileChooserJFileChooserJFileChooserJFileChooser();();();();

intintintint choicechoicechoicechoice = = = = fcfcfcfc....showOpenDialogshowOpenDialogshowOpenDialogshowOpenDialog( ( ( ( newnewnewnew JFrameJFrameJFrameJFrame() );() );() );() );

ifififif ( ( ( ( choicechoicechoicechoice == == == == JFileChooserJFileChooserJFileChooserJFileChooser.APPROVE_OPTION ) .APPROVE_OPTION ) .APPROVE_OPTION ) .APPROVE_OPTION )

infileNameinfileNameinfileNameinfileName = = = = fcfcfcfc....getSelectedFilegetSelectedFilegetSelectedFilegetSelectedFile().().().().getNamegetNamegetNamegetName();();();();

elseelseelseelse

Osnova

75

returnreturnreturnreturn; //*** ; //*** ; //*** ; //*** useruseruseruser hit CANCEL hit CANCEL hit CANCEL hit CANCEL buttonbuttonbuttonbutton

StringStringStringString outfileNameoutfileNameoutfileNameoutfileName = "= "= "= "OutputForOutputForOutputForOutputFor_" + _" + _" + _" + infileNameinfileNameinfileNameinfileName;;;;

empRWempRWempRWempRW = = = = newnewnewnew EmpRWEmpRWEmpRWEmpRW( ( ( ( infileNameinfileNameinfileNameinfileName, , , , outfileNameoutfileNameoutfileNameoutfileName ););););

empRWempRWempRWempRW....readreadreadread();();();();

EnumerationEnumerationEnumerationEnumeration e = e = e = e = empRWempRWempRWempRW....getEmpsgetEmpsgetEmpsgetEmps().().().().elementselementselementselements();();();();

whilewhilewhilewhile ( e.( e.( e.( e.hasMoreElementshasMoreElementshasMoreElementshasMoreElements() ) {() ) {() ) {() ) {

EmpEmpEmpEmp t = (t = (t = (t = (EmpEmpEmpEmp) e.) e.) e.) e.nextElementnextElementnextElementnextElement();();();();

dm.dm.dm.dm.addRowaddRowaddRowaddRow( t.( t.( t.( t.getFieldValuesgetFieldValuesgetFieldValuesgetFieldValues() ); //*** () ); //*** () ); //*** () ); //*** polymorphicpolymorphicpolymorphicpolymorphic

}}}}

}}}}

//** Use //** Use //** Use //** Use anananan EmpRWEmpRWEmpRWEmpRW objectobjectobjectobject to to to to writewritewritewrite recordsrecordsrecordsrecords fromfromfromfrom thethethethe JTableJTableJTableJTable

// to a // to a // to a // to a specifiedspecifiedspecifiedspecified filefilefilefile....

private private private private voidvoidvoidvoid writewritewritewrite() {() {() {() {

EnumerationEnumerationEnumerationEnumeration e = dm.e = dm.e = dm.e = dm.getDataVectorgetDataVectorgetDataVectorgetDataVector().().().().elementselementselementselements();();();();

VectorVectorVectorVector recordsrecordsrecordsrecords = = = = newnewnewnew VectorVectorVectorVector();();();();

whilewhilewhilewhile ( e.( e.( e.( e.hasMoreElementshasMoreElementshasMoreElementshasMoreElements() ) {() ) {() ) {() ) {

VectorVectorVectorVector fieldsfieldsfieldsfields = (= (= (= (VectorVectorVectorVector) e.) e.) e.) e.nextElementnextElementnextElementnextElement();();();();

StringStringStringString t = "";t = "";t = "";t = "";

EnumerationEnumerationEnumerationEnumeration e2 = e2 = e2 = e2 = fieldsfieldsfieldsfields....elementselementselementselements();();();();

whilewhilewhilewhile ( e2.( e2.( e2.( e2.hasMoreElementshasMoreElementshasMoreElementshasMoreElements() ) {() ) {() ) {() ) {

StringStringStringString s = (s = (s = (s = (StringStringStringString) e2.) e2.) e2.) e2.nextElementnextElementnextElementnextElement();();();();

ifififif ( !s.( !s.( !s.( !s.equalsequalsequalsequals( ( ( ( EmpEmpEmpEmp....NotApplicableNotApplicableNotApplicableNotApplicable ) )) )) )) )

t += s + " ";t += s + " ";t += s + " ";t += s + " ";

}}}}

recordsrecordsrecordsrecords....addElementaddElementaddElementaddElement( t );( t );( t );( t );

}}}}

empRWempRWempRWempRW....writeRecordswriteRecordswriteRecordswriteRecords( ( ( ( recordsrecordsrecordsrecords ););););

}}}}

Osnova

76

//** //** //** //** ClearClearClearClear thethethethe JTableJTableJTableJTable's 's 's 's rowsrowsrowsrows beforebeforebeforebefore a a a a readreadreadread....

private private private private voidvoidvoidvoid clearRowsclearRowsclearRowsclearRows() {() {() {() {

intintintint n = dm.n = dm.n = dm.n = dm.getRowCountgetRowCountgetRowCountgetRowCount();();();();

forforforfor ( ( ( ( intintintint i = dm.i = dm.i = dm.i = dm.getRowCountgetRowCountgetRowCountgetRowCount() () () () ---- 1; i >= 0; i1; i >= 0; i1; i >= 0; i1; i >= 0; i-------- ))))

dm.dm.dm.dm.removeRowremoveRowremoveRowremoveRow( i );( i );( i );( i );

}}}}

}}}}