Grafika 2D 1
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 2
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 3
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, bottom oblasti jsou obsazeny s JPanel center 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 4
Příklad uživatelského formuláře 5
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 6
import javax.swing.*; import java.awt awt.*; import java.awt awt.event event.*; class MaceGUI extends JFrame implements ActionListener { private Container pane; private JPanel buttons, misc, stlist; private JList list; private JRadioButton married; private JTextField email, name; private JTextArea reasons; //tridni atributy private final static String submit = " Submit "; private final static String clear = " Clear "; private final static String exit = " Exit "; private final static String promptn = "First and last name "; private final static String prompte = "E-mail address "; private final static String promptr = " My charisma needs enhancement because"; private final static String[ ] states = { "Illinois " Illinois", "Indiana" Indiana", "Iowa" Iowa", "Kansas", "Minnesota", "Michigan", "Missouri " Missouri", "Nebraska" Nebraska", "Ohio", "Wisconsin" Wisconsin" ; 7
public MaceGUI() { super( "Midwest " Association for Charisma Enhancement" ); pane = getcontentpane(); buttons = new JPanel( new FlowLayout() ); misc = new JPanel( new FlowLayout() ); stlist = new JPanel(); married = new JRadioButton( "Married" Married", false ); email = new JTextField( prompte ); name = new JTextField( promptn ); reasons = new JTextArea( promptr ); list = new JList( states ); //** Midwest state names init(); setvisible( true ); setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); public void actionperformed( ActionEvent e ) { String cmd = e.getactioncommand getactioncommand(); if ( cmd.equals equals( submit ) ) submitform(); else if ( cmd.equals equals( clear ) ) clearform(); else if ( cmd.equals equals( exit ) ) System.exit( 0 ); 8
private void submitform() { String t = (list.getselectedvalue getselectedvalue() == null)? "none" none" : list.getselectedvalue getselectedvalue(). ().tostring tostring(); post( name.gettext gettext(), email.gettext gettext(), t, (married married.isselected isselected())? "married" married" : "not maried", reasons.gettext gettext() ); private void clearform() { reasons.settext settext( promptr ); name.settext settext( promptn ); email.settext settext( prompte ); married.setselected setselected( false ); list.getselectionmodel getselectionmodel(). ().clearselection clearselection(); //*** For now, a stub function that prints to the standard error. private void post( String n, String e, String s, String m, String r ) { System.err err.println println( n + " " + e + " " + s + "\n"" + m + "\n"" + r ); private void init() { JLabel j; Font f = null; pane.setlayout setlayout( new BorderLayout() ); buttons.setbackground setbackground( Color.gray ); email.setfont setfont( f = new Font( "Dialog", Font.BOLD, 12 ) ); name.setfont setfont( f ); reasons.setfont setfont( f ); 9
reasons.setlinewrap setlinewrap( true ); misc.add add( name ); misc.add add( email ); misc.add add( married ); list.setfont setfont( f ); list.setbackground setbackground( Color.cyan ); list.getselectionmodel getselectionmodel(). ().setselectionmode setselectionmode( ListSelectionModel.SINGLE_SELECTION ); stlist.setlayout setlayout( new BoxLayout( stlist, BoxLayout.Y_AXIS ) ); stlist.add add( j = new JLabel( "Home" state " ) ); j.setfont setfont( f ); j.setforeground setforeground( Color.black ); stlist.add add( list ); addbutton( submit ); addbutton( clear ); addbutton( exit ); pane.add add( buttons, BorderLayout.NORTH ); pane.add add( reasons, BorderLayout.CENTER ); pane.add add( stlist, BorderLayout.WEST ); pane.add add( misc, BorderLayout.SOUTH ); pack(); private void addbutton( String name ) { JButton b = new JButton( name ); b.setfont setfont( new Font( "Dialog", Font.BOLD, 14 ) ); b.addactionlistener addactionlistener( this ); buttons.add add( b ); 10
class MaceGUITester { public static void main( String[ ] args ) { new MaceGUI(); 11
2. Úvod Třídy a rozhraní 2D grafiky Object Color Component Font FontMetrics Graphics Polygon Classes and interfaces from the Java2D API that appear in package java.awt Graphics2D BasicStroke GradientPaint TexturePaint Classes from the Java2D API that appear in package java.awt.geom GeneralPath Line2D RectangularShape Arc2D Ellipse2D Rectangle2D RoundRectangle2D interface java.awt.paint interface java.awt.shape interface java.awt.stroke 12
Ú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 13
Systém souřadnic měří se v pixlech (0, 0) +x X a xis (x, y ) +y Y a xis 14
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 15
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() 16
import javax.swing.*; import java.awt awt.*; import java.awt awt.event event.*; class OneButton extends JFrame { private Container c; private JButton b; private String msg1, msg2, displayedmsg; private Color fillcolor = Color.white white; private boolean toggle; private Font f; private int count; public OneButton() { super( "Repaint Example" ); c = getcontentpane(); displayedmsg = msg1 = "Hello" Hello, world!"; msg2 = "What " What, me worry?"; b = new JButton( " Toggle " ); b.addactionlistener addactionlistener( new ActionListener() { public void actionperformed( ActionEvent e ) { displayedmsg = (toggle( toggle)? msg1 : msg2; fillcolor = (toggle( toggle)? Color.white : Color.cyan cyan; toggle =!toggle! toggle; repaint(); // vyvola update, coz vyvola paint if(++ (++count > 4){ c.add add(new JLabel(" ("Wow Wow!")); c.validate validate(); count = 0; ); 17
c.setlayout setlayout( new FlowLayout() ); c.add add( b ); setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); c.setfont setfont( f = new Font( "Dialog", Font.BOLD, 14 ) ); setsize( 300, 200 ); setvisible( true ); public void paint( Graphics g ) { super.paint paint( g ); // vymaze pane g.draw3drect( 50, 70, 150, 70, true ); g.setcolor setcolor( fillcolor ); g.fill3drect( 50, 70, 150, 70, true ); g.setcolor setcolor( Color.black ); g.setfont setfont( f ); g.drawstring drawstring( displayedmsg, 70, 100 ); 18
class OneButtonTester { public static void main( String[ ] args ) { new OneButton(); 19
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í 20
Třída Color 4. Práce s barvami Definuje metody a konstanty pro práci s barvami Barvy jsou tvořeny komponentami red, green a blue RGB hodnoty 21
Grafické konstanty a jejich RGB hodnoty Color 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 22
Metody Popis Konstanty Color a metody Metody třídy Color public Color( int r, int g, int b ) public Color( float r, float g, float b ) public int getred() public int getgreen() public int getblue() Vytvoří barvu (Color) založenou na komponentách red, green a blue vyjádřené jako celé číslo v rozsahu od 0 do 255. Vytvoří barvu založenou na komponentách red, green a blue vyjádřené jako floating-point hodnoty od 0.0 do 1.0. Vrací hodnotu mezi 0 a 255 reprezentující obsah červené. Vrací hodnotu mezi 0 a 255 reprezentující obsah zelené. Vrací hodnotu mezi 0 a 255 reprezentující obsah modré. Methody Graphics pro práci s Colors public Color getcolor() public void setcolor( Color c ) Vrací objekt třídy Color reprezentující aktuální barvu pro grafický kontext. Nastavuje aktuální barvu pro kresleni s grafickým kontextem. 23
// Demonstrating Colors. package graf_06; import java.awt awt.graphics Graphics; import java.awt awt.color Color; import javax.swing..swing.jpanel JPanel; public class ColorJPanel extends JPanel { // draw rectangles and Strings in different colors public void paintcomponent( Graphics g ) { super.paintcomponent paintcomponent( g ); // call superclass's paintcomponent this.setbackground setbackground( Color.WHITE ); // set new drawing color using integers g.setcolor setcolor( new Color( 255, 0, 0 ) ); g.fillrect fillrect( 15, 25, 100, 20 ); g.drawstring drawstring( "Current" RGB: " + g.getcolor getcolor(), 130, 40 ); // set new drawing color using floats g.setcolor setcolor( new Color( 0.50f, 0.75f, 0.0f ) ); g.fillrect fillrect( 15, 50, 100, 20 ); g.drawstring drawstring( "Current" RGB: " + g.getcolor getcolor(), 130, 65 ); // set new drawing color using static Color objects g.setcolor setcolor( Color.BLUE ); g.fillrect fillrect( 15, 75, 100, 20 ); g.drawstring drawstring( "Current" RGB: " + g.getcolor getcolor(), 130, 90 ); 24
// display individual RGB values Color color = Color.MAGENTA; g.setcolor setcolor( color ); g.fillrect fillrect( 15, 100, 100, 20 ); g.drawstring drawstring( "RGB values: " + color.getred getred() + ", " + color.getgreen getgreen() + ", " + color.getblue getblue(), 130, 115 ); // end method paintcomponent // end class ColorJPanel 25
// Demonstrating Colors. package graf_06; import javax.swing..swing.jframe JFrame; public class ShowColors { // execute application public static void main( String args[] ) { // create frame for ColorJPanel JFrame frame = new JFrame( "Using" colors" ); frame.setdefaultcloseoperation setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); ColorJPanel colorjpanel = new ColorJPanel(); // create ColorJPanel frame.add add( colorjpanel ); // add colorjpanel to frame frame.setsize setsize( 400, 180 ); // set frame size frame.setvisible setvisible( true ); // display frame // end main // end class ShowColors 26
import javax.swing.*; import java.awt awt.event event.*; import java.awt awt.*; class ColorMenuEx extends JFrame implements ActionListener { private JMenuBar menubar; private JMenu colormenu; private JMenu controlmenu; private static final Color orig = Color.white white; private static final String[ ] colornames = { "Blue " Blue", "Cyan" Cyan", "Gray" Gray", "Orange" Orange", "Pink" ; private static final Color[ ] colors = { Color.blue blue, Color.cyan cyan, Color.gray gray, Color.orange orange, Color.pink ; private static final String[ ] controls = { "Restore" Restore", "Exit" ; public ColorMenuEx() { menubar = new JMenuBar(); colormenu = new JMenu( "Colors" Colors" ); controlmenu = new JMenu( "Control" Control" ); init(); setsize( 300, 150 ); getcontentpane(). ().setbackground setbackground( orig ); setvisible( true ); Jednoduchý příklad využívající barev 27
public void actionperformed( ActionEvent e ) { String s = e.getactioncommand getactioncommand(); if ( s.equals equals( "Exit" ) ) System.exit( 0 ); else if ( s.equals equals( "Restore" Restore" ) ) getcontentpane(). ().setbackground setbackground( orig ); else setcolor( s ); private void init() { initmenu( colormenu, colornames ); initmenu( controlmenu, controls ); menubar.add add( colormenu ); menubar.add add( controlmenu ); setjmenubar( menubar ); private void initmenu( JMenu menu, String[ ] items ) { for ( int i = 0; i < items.length length; i++ ) { JMenuItem item = new JMenuItem( items[ i ] ); item.addactionlistener addactionlistener( this ); menu.add add( item ); private void setcolor( String c ) { for ( int i = 0; i < colornames.length length; i++ ) if ( c.equals equals( colornames[ i ] ) ) { getcontentpane(). ().setbackground setbackground( colors[ i ] ); break; 28
class ColorMenuExTester { public static void main( String[ ] args ) { new ColorMenuEx(); 29
// Choosing colors with JColorChooser. package graf_08; import java.awt awt.borderlayout BorderLayout; import java.awt awt.color Color; import java.awt awt.event event.actionevent ActionEvent; import java.awt awt.event event.actionlistener ActionListener; import javax.swing..swing.jbutton JButton; import javax.swing..swing.jframe JFrame; import javax.swing..swing.jcolorchooser JColorChooser; import javax.swing..swing.jpanel JPanel; Příklad umožňující výběr barev public class ShowColors2JFrame extends JFrame { private JButton changecolorjbutton; private Color color = Color.LIGHT_GRAY; private JPanel colorjpanel; // set up GUI public ShowColors2JFrame() { super( "Using " JColorChooser" ); // create JPanel for display color colorjpanel = new JPanel(); colorjpanel.setbackground setbackground( color ); // set up changecolorjbutton and register its event handler changecolorjbutton = new JButton( "Change" Color" ); changecolorjbutton.addactionlistener addactionlistener( 30
new ActionListener() // anonymni vnitrni trida { // display JColorChooser when user clicks button public void actionperformed( ActionEvent event ) { color = JColorChooser.showDialog showdialog( ShowColors2JFrame.this this, "Choose" a color", color ); // set default color, if no color is returned if ( color == null ) color = Color.LIGHT_GRAY; // change content pane's background color colorjpanel.setbackground setbackground( color ); // end method actionperformed // end anonymous inner class ); // end call to addactionlistener add( colorjpanel, BorderLayout.CENTER ); // add colorjpanel add( changecolorjbutton, BorderLayout.SOUTH ); // add button setsize( 400, 130 ); // set frame size setvisible( true ); // display frame // end ShowColor2JFrame constructor // end class ShowColors2JFrame 31
// Choosing colors with JColorChooser. package graf_08; import javax.swing..swing.jframe JFrame; public class ShowColors2 { // execute application public static void main( String args[] ) { ShowColors2JFrame application = new ShowColors2JFrame(); application.setdefaultcloseoperation setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); // end main // end class ShowColors2 32
33
Výsledky aplikace 34
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) 35
Metody a konstanty třídy Font Metody nebo konstanty Popis Konstanty Font, konstruktory a metody pro kreslení polygonů public final static int PLAIN public final static int BOLD public final static int ITALIC Konstanta reprezentující a plain font style. Konstanta reprezentující a bold font style. 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() public int getsize() public String getname() public String getfamily() public boolean isplain() public boolean isbold() public boolean isitalic() Vrací celočíselnou hodnotu indikující aktuální styl fontu. Vrací celočíselnou hodnotu indikující aktuální velikost fontu. Vrací aktuální jméno fontu jako řetězec. Vrací font s family name jako řetězec. Testuje font na plain font styl. Testuje font na a bold font styl. Testuje font na an italic font styl. 36
Metody a konstanty třídy Font Metody nebo konstanty Popis Methods Graphics pro práci s fonty public Font getfont() public void setfont( Font f ) Vrací objekt třídy Font reprezentující aktuální font. Nastaví aktuální font na font, styl a velikost specifikované v proměnné f. 37
// Display strings in different fonts and colors. package graf_12; import java.awt awt.font; import java.awt awt.color Color; import java.awt awt.graphics Graphics; import javax.swing..swing.jpanel JPanel; Demonstrace využití třídy Font public class FontJPanel extends JPanel { // display Strings in different fonts and colors public void paintcomponent( Graphics g ) { super.paintcomponent paintcomponent( g ); // call superclass's paintconponent // set font to Serif (Times Times), bold, 12pt and draw a string g.setfont setfont( new Font( "Serif" Serif", Font.BOLD, 12 ) ); g.drawstring drawstring( "Serif" 12 point bold.", 20, 50 ); // set font to Monospaced (Courier Courier), italic, 24pt and draw a string g.setfont setfont( new Font( "Monospaced" Monospaced", Font.ITALIC, 24 ) ); g.drawstring drawstring( "Monospaced" 24 point italic.", 20, 70 ); // set font to SansSerif (Helvetica Helvetica), plain, 14pt and draw a string g.setfont setfont( new Font( "SansSerif" SansSerif", Font.PLAIN, 14 ) ); g.drawstring drawstring( "SansSerif" 14 point plain.", 20, 90 ); 38
// set font to Serif (Times Times), bold/italic italic, 18pt and draw a string g.setcolor setcolor( Color.RED ); g.setfont setfont( new Font( "Serif" Serif", Font.BOLD + Font.ITALIC, 18 ) ); g.drawstring drawstring( g.getfont getfont(). ().getname getname() + " " + g.getfont getfont(). ().getsize getsize() + " point bold italic.", 20, 110 ); // end method paintcomponent // end class FontJPanel 39
// Using fonts. package graf_12; import javax.swing..swing.jframe JFrame; public class Fonts { // execute application public static void main( String args[] ) { // create frame for FontJPanel JFrame frame = new JFrame( "Using" fonts" ); frame.setdefaultcloseoperation setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); FontJPanel fontjpanel = new FontJPanel(); // create FontJPanel frame.add add( fontjpanel ); // add fontjpanel to frame frame.setsize setsize( 420, 170 ); // set frame size frame.setvisible setvisible( true ); // display frame // end main // end class Fonts 40
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) 41
Metriky fontů he ight Xy1İ asc le ading e nt ba seline desc ent 42
Metody tříd FontMetrics a Graphics zí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. 43
// FontMetrics and Graphics methods useful for obtaining font metrics. package graf_16; import java.awt awt.font; import java.awt awt.fontmetrics FontMetrics; import java.awt awt.graphics Graphics; import javax.swing..swing.jpanel JPanel; public class MetricsJPanel extends JPanel { // display font metrics public void paintcomponent( Graphics g ) { super.paintcomponent paintcomponent( g ); // call superclass's paintcomponent g.setfont setfont( new Font( "SansSerif" SansSerif", Font.BOLD, 12 ) ); FontMetrics metrics = g.getfontmetrics getfontmetrics(); g.drawstring drawstring( "Current" font: " + g.getfont getfont(), 10, 40 ); g.drawstring drawstring( "Ascent" Ascent: " + metrics.getascent getascent(), 10, 55 ); g.drawstring drawstring( "Descent" Descent: " + metrics.getdescent getdescent(), 10, 70 ); g.drawstring drawstring( "Height" Height: " + metrics.getheight getheight(), 10, 85 ); g.drawstring drawstring( "Leading" Leading: " + metrics.getleading getleading(), 10, 100 ); Font font = new Font( "Serif" Serif", Font.ITALIC, 14 ); metrics = g.getfontmetrics getfontmetrics( font ); 44
g.setfont setfont( font ); g.drawstring drawstring( "Current" font: " + font, 10, 130 ); g.drawstring drawstring( "Ascent" Ascent: " + metrics.getascent getascent(), 10, 145 ); g.drawstring drawstring( "Descent" Descent: " + metrics.getdescent getdescent(), 10, 160 ); g.drawstring drawstring( "Height" Height: " + metrics.getheight getheight(), 10, 175 ); g.drawstring drawstring( "Leading" Leading: " + metrics.getleading getleading(), 10, 190 ); // end method paintcomponent 45
import javax.swing..swing.jframe JFrame; public class Metrics { // execute application public static void main( String args[] ) { // create frame for MetricsJPanel JFrame frame = new JFrame( "Demonstrating" FontMetrics" ); frame.setdefaultcloseoperation setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); MetricsJPanel metricsjpanel = new MetricsJPanel(); frame.add add( metricsjpanel ); // add metricsjpanel to frame frame.setsize setsize( 510, 250 ); // set frame size frame.setvisible setvisible( true ); // display frame // end main // end class Metrics 46
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 47
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). 48
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). 49
package graf_19; import java.awt awt.color Color; import java.awt awt.graphics Graphics; import javax.swing..swing.jpanel JPanel; public class LinesRectsOvalsJPanel extends JPanel { // display various lines, rectangles and ovals public void paintcomponent( Graphics g ) { super.paintcomponent paintcomponent( g ); // call superclass's paint method this.setbackground setbackground( Color.WHITE ); g.setcolor setcolor( Color.RED ); g.drawline drawline( 5, 30, 380, 30 ); g.setcolor setcolor( Color.BLUE ); g.drawrect drawrect( 5, 40, 90, 55 ); g.fillrect fillrect( 100, 40, 90, 55 ); g.setcolor setcolor( Color.BLACK ); g.fillroundrect fillroundrect( 195, 40, 90, 55, 50, 50 ); g.drawroundrect drawroundrect( 290, 40, 90, 55, 20, 20 ); 50
g.setcolor setcolor( Color.YELLOW ); g.draw3drect( 5, 100, 90, 55, true ); g.fill3drect( 100, 100, 90, 55, false ); g.setcolor setcolor( Color.MAGENTA ); g.drawoval drawoval( 195, 100, 90, 55 ); g.filloval filloval( 290, 100, 90, 55 ); // end method paintcomponent 51
import java.awt awt.color Color; import javax.swing..swing.jframe JFrame; public class LinesRectsOvals { // execute application public static void main( String args[] ) { // create frame for LinesRectsOvalsJPanel JFrame frame = new JFrame( "Drawing" lines, rectangles and ovals" ); frame.setdefaultcloseoperation setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); LinesRectsOvalsJPanel linesrectsovalsjpanel = new LinesRectsOvalsJPanel(); linesrectsovalsjpanel.setbackground setbackground( Color.WHITE ); frame.add add( linesrectsovalsjpanel ); // add panel to frame frame.setsize setsize( 400, 210 ); // set frame size frame.setvisible setvisible( true ); // display frame // end main // end class LinesRectsOvals 52
Šířka a výška oblouku pro zaoblené obdélníky (x, y) arc height a rc width height w idth 53
Oval ohraničený obdélníkem (x, y ) height w id th 54
Arc - oblouk část tvoří ovál 8. Kreslení oblouků - výsečí měří se ve stupních Sweeps poč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 55
Kladné a záporné úhly oblouku Kladné úhly 90 Záporné úhly 90 180 0 180 0 270 270 56
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. 57
import java.awt awt.color Color; import java.awt awt.graphics Graphics; import javax.swing..swing.jpanel JPanel; public class ArcsJPanel extends JPanel { // draw rectangles and arcs public void paintcomponent( Graphics g ) { super.paintcomponent paintcomponent( g ); // call superclass's paintcomponent // start at 0 and sweep 360 degrees g.setcolor setcolor( Color.RED ); g.drawrect drawrect( 15, 35, 80, 80 ); g.setcolor setcolor( Color.BLACK ); g.drawarc drawarc( 15, 35, 80, 80, 0, 360 ); // start at 0 and sweep 110 degrees g.setcolor setcolor( Color.RED ); g.drawrect drawrect( 100, 35, 80, 80 ); g.setcolor setcolor( Color.BLACK ); g.drawarc drawarc( 100, 35, 80, 80, 0, 110 ); 58
// start at 0 and sweep -270 degrees g.setcolor setcolor( Color.RED ); g.drawrect drawrect( 185, 35, 80, 80 ); g.setcolor setcolor( Color.BLACK ); g.drawarc drawarc( 185, 35, 80, 80, 0, -270 ); // start at 0 and sweep 360 degrees g.fillarc fillarc( 15, 120, 80, 40, 0, 360 ); // start at 270 and sweep -90 degrees g.fillarc fillarc( 100, 120, 80, 40, 270, -90 ); // start at 0 and sweep -270 degrees g.fillarc fillarc( 185, 120, 80, 40, 0, -270 ); // end method paintcomponent // end class ArcsJPanel 59
import javax.swing..swing.jframe JFrame; public class DrawArcs { // execute application public static void main( String args[] ) { // create frame for ArcsJPanel JFrame frame = new JFrame( "Drawing" Arcs" ); frame.setdefaultcloseoperation setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); ArcsJPanel arcsjpanel = new ArcsJPanel(); // create ArcsJPanel frame.add add( arcsjpanel ); // add arcsjpanel to frame frame.setsize setsize( 300, 210 ); // set frame size frame.setvisible setvisible( true ); // display frame // end main // end class DrawArcs 60
9. Kreslení polygonů a lomených čar Polygons and Polylines TřídaPolygon Polygons Vícestranné tvary (multisided shapes) Polylines Řada spojených bodů 61
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. 62
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. 63
import java.awt awt.graphics Graphics; import java.awt awt.polygon; import javax.swing..swing.jpanel JPanel; public class PolygonsJPanel extends JPanel { // draw polygons and polylines public void paintcomponent( Graphics g ) { super.paintcomponent paintcomponent( g ); // call superclass's paintcomponent // draw polygon with Polygon object int xvalues[] = { 20, 40, 50, 30, 20, 15 ; int yvalues[] = { 50, 50, 60, 80, 80, 60 ; Polygon polygon1 = new Polygon( xvalues, yvalues, 6 ); g.drawpolygon drawpolygon( polygon1 ); // draw polylines with two arrays int xvalues2[] = { 70, 90, 100, 80, 70, 65, 60 ; int yvalues2[] = { 100, 100, 110, 110, 130, 110, 90 ; g.drawpolyline drawpolyline( xvalues2, yvalues2, 7 ); // fill polygon with two arrays int xvalues3[] = { 120, 140, 150, 190 ; int yvalues3[] = { 40, 70, 80, 60 ; g.fillpolygon fillpolygon( xvalues3, yvalues3, 4 ); 64
// draw filled polygon with Polygon object Polygon polygon2 = new Polygon(); polygon2.addpoint addpoint( 165, 135 ); polygon2.addpoint addpoint( 175, 150 ); polygon2.addpoint addpoint( 270, 200 ); polygon2.addpoint addpoint( 200, 220 ); polygon2.addpoint addpoint( 130, 180 ); g.fillpolygon fillpolygon( polygon2 ); // end method paintcomponent // end class PolygonsJPanel 65
import javax.swing..swing.jframe JFrame; public class DrawPolygons { // execute application public static void main( String args[] ) { // create frame for PolygonsJPanel JFrame frame = new JFrame( "Drawing" Polygons" ); frame.setdefaultcloseoperation setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); PolygonsJPanel polygonsjpanel = new PolygonsJPanel(); frame.add add( polygonsjpanel ); // add polygonsjpanel to frame frame.setsize setsize( 280, 270 ); // set frame size frame.setvisible setvisible( true ); // display frame // end main 66
import java.awt awt.color Color; import java.awt awt.graphics Graphics; import java.awt awt.basicstroke BasicStroke; import java.awt awt.gradientpaint GradientPaint; import java.awt awt.texturepaint TexturePaint; import java.awt awt.rectangle Rectangle; import java.awt awt.graphics2d; import java.awt awt.geom geom.ellipse2d; import java.awt awt.geom geom.rectangle2d; import java.awt awt.geom geom.roundrectangle2d; import java.awt awt.geom geom.arc2d; import java.awt awt.geom geom.line2d; import java.awt awt.image image.bufferedimage BufferedImage; import javax.swing..swing.jpanel JPanel; Kreslení komplexních tvarů public class ShapesJPanel extends JPanel { // draw shapes with Java 2D API public void paintcomponent( Graphics g ) { super.paintcomponent paintcomponent( g ); // call superclass's paintcomponent Graphics2D g2d = ( Graphics2D ) g; // cast g to Graphics2D // draw 2D ellipse filled with a blue-yellow gradient g2d.setpaint setpaint( new GradientPaint( 5, 30, Color.BLUE, 35, 100, Color.YELLOW, true ) ); g2d.fill fill( new Ellipse2D.Double( 5, 30, 65, 100 ) ); 67
// draw 2D rectangle in red g2d.setpaint setpaint( Color.RED ); g2d.setstroke setstroke( new BasicStroke( 10.0f ) ); g2d.draw draw( new Rectangle2D.Double( 80, 30, 65, 100 ) ); // draw 2D rounded rectangle with a buffered background BufferedImage buffimage = new BufferedImage( 10, 10, BufferedImage.TYPE_INT_RGB ); // obtain Graphics2D from bufferimage and draw on it Graphics2D gg = buffimage.creategraphics creategraphics(); gg.setcolor setcolor( Color.YELLOW ); // draw in yellow gg.fillrect fillrect( 0, 0, 10, 10 ); // draw a filled rectangle gg.setcolor setcolor( Color.BLACK ); // draw in black gg.drawrect drawrect( 1, 1, 6, 6 ); // draw a rectangle gg.setcolor setcolor( Color.BLUE ); // draw in blue gg.fillrect fillrect( 1, 1, 3, 3 ); // draw a filled rectangle gg.setcolor setcolor( Color.RED ); // draw in red gg.fillrect fillrect( 4, 4, 3, 3 ); // draw a filled rectangle // paint buffimage onto the JFrame g2d.setpaint setpaint( new TexturePaint( buffimage, new Rectangle( 10, 10 ) ) ); g2d.fill fill( new RoundRectangle2D.Double( 155, 30, 75, 100, 50, 50 ) ); 68
// draw 2D pie-shaped arc in white g2d.setpaint setpaint( Color.WHITE ); g2d.setstroke setstroke( new BasicStroke( 6.0f ) ); g2d.draw draw( new Arc2D.Double( 240, 30, 75, 100, 0, 270, Arc2D.PIE ) ); // draw 2D lines in green and yellow g2d.setpaint setpaint( Color.GREEN ); g2d.draw draw( new Line2D.Double( 395, 30, 320, 150 ) ); // draw 2D line using stroke float dashes[] = { 10 ; // specify dash pattern g2d.setpaint setpaint( Color.YELLOW ); g2d.setstroke setstroke( new BasicStroke( 4, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 10, dashes, 0 ) ); g2d.draw draw( new Line2D.Double( 320, 30, 395, 150 ) ); // end method paintcomponent // end class ShapesJPanel 69
import javax.swing..swing.jframe JFrame; public class Shapes { // execute application public static void main( String args[] ) { // create frame for ShapesJPanel JFrame frame = new JFrame( "Drawing" 2D shapes" ); frame.setdefaultcloseoperation setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE ); // create ShapesJPanel ShapesJPanel shapesjpanel = new ShapesJPanel(); frame.add add( shapesjpanel ); // add shapesjpanel to frame frame.setsize setsize( 425, 200 ); // set frame size frame.setvisible setvisible( true ); // display frame // end main // end class Shapes 70
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 view controller) a uživatel může využít DefaultTableModel pokud nechce dělat úpravy Aplikace vytváří DefaultTableModel s 11 sloupci 71
import java.util util.*; import java.awt awt.*; import java.awt awt.event event.*; import javax.swing.*; import javax.swing.table.*; public class EmpGUI extends JFrame { //*** instance fields private Container cont; private JTable table; private DefaultTableModel dm; private EmpRW emprw; private String infilename; private String outfilename; //*** class fields private static final String readstring = " Read File "; private static final String writestring = " Write File "; private static final String exitstring = " Exit "; //** Construct the GUI, including controls and a JTable, // and display the GUI automatically. // Syntax: new EmpGUI() public EmpGUI() { super( "Employee " Edit Application" ); setsize( 900, 350 ); cont = getcontentpane(); initcontrols(); inittable(); setvisible(true true); 72
//** Add buttons to read, write, and exit. // Add action listeners per button. private void initcontrols() { JButton b; JPanel controls = new JPanel(); controls.setlayout setlayout( new FlowLayout() ); b = addbutton( controls, readstring ); b.addactionlistener addactionlistener( new ActionListener() { public void actionperformed( ActionEvent e ) { read(); ); b = addbutton( controls, writestring ); b.addactionlistener addactionlistener( new ActionListener() { public void actionperformed( ActionEvent e ) { write(); ); b = addbutton( controls, exitstring ); b.addactionlistener addactionlistener( new ActionListener() { public void actionperformed( ActionEvent e ) { System.exit( 0 ); ); cont.add add( controls, BorderLayout.NORTH ); 73
//** Create an empty JTable to hold the employee records private void inittable() { String[ ] cols = { "CODE", "ID", "LNAME", "FNAME", "DEPT", "TITLE", "RPTS", "DISC", "OPTS", "HR", "OT" ; dm = new DefaultTableModel( cols, 0 ); table = new JTable( dm ); table.gettableheader gettableheader(). ().setfont setfont( new Font( "Dialog", Font.BOLD, 12 ) ); cont.add add( new JScrollPane( table ), BorderLayout.CENTER ); //** Add the named button to a panel private JButton addbutton( JPanel p, String name ) { JButton b = new JButton( name ); b.setfont setfont( new Font( "Dialog", Font.BOLD, 14 ) ); p.add add( b ); return b; //** Use an EmpRW object to read records from a // specified input file. Add the records to the JTable. private void read() { clearrows(); JFileChooser fc = new JFileChooser(); int choice = fc.showopendialog showopendialog( new JFrame() ); if ( choice == JFileChooser.APPROVE_OPTION ) infilename = fc.getselectedfile getselectedfile(). ().getname getname(); else 74
return; //*** user hit CANCEL button String outfilename = "OutputFor" OutputFor_" + infilename; emprw = new EmpRW( infilename, outfilename ); emprw.read read(); Enumeration e = emprw.getemps getemps(). ().elements elements(); while ( e.hasmoreelements hasmoreelements() ) { Emp t = (Emp( Emp) e.nextelement nextelement(); dm.addrow addrow( t.getfieldvalues getfieldvalues() ); //*** polymorphic //** Use an EmpRW object to write records from the JTable // to a specified file. private void write() { Enumeration e = dm.getdatavector getdatavector(). ().elements elements(); Vector records = new Vector(); while ( e.hasmoreelements hasmoreelements() ) { Vector fields = (Vector( Vector) e.nextelement nextelement(); String t = ""; Enumeration e2 = fields.elements elements(); while ( e2.hasmoreelements hasmoreelements() ) { String s = (String( String) e2.nextelement nextelement(); if (!s.equals equals( Emp.NotApplicable ) ) t += s + " "; records.addelement addelement( t ); emprw.writerecords writerecords( records ); 75
//** Clear the JTable's rows before a read. private void clearrows() { int n = dm.getrowcount getrowcount(); for ( int i = dm.getrowcount getrowcount() - 1; i >= 0; i--i ) dm.removerow removerow( i ); 76