Starting from the drawing program, walking into the GUI programming world

xiaoxiao2021-03-06  41

Starting from the drawing program, walking into the GUI programming world

Java, drawing

/ / The following is the Java version of the drawing

package boya; import java.awt *;. import java.awt.event *;. import java.util *;. public class Draw {private DrawModel model; private DrawView view; private static DrawFrame window; private static Draw theApp; public static Void main (string [] args) {THEAPP.INIT ();} public void init () {window = new drawframe ("Drawboard", this); Toolkit Thekit = WINDOW.GETTOOLKIT (); Dimension Wndsize = thekit.getscreensize (); Window.SetBounds (WNDSIZE.WIDTH / 6, WNDSIZE.HEIGHT / 6, / / ​​Location 2 * Wndsize.Width / 3, 2 * wndsize.height / 3); // Size MODEL = New DrawModel (); View = New DrawView (this); Model.addobserver ((Observer); Model.addobserver (Observer); Window.getContentPane (). add (view, borderlayout.center); Window. setVisible (true);} public DrawFrame getWindow () {return window;} public DrawModel getModel () {return model;} public drawView getView () {return view;} class WindowHandler extends WindowAdapter {public void windowClosing (WindowEvent e) {window .Checkforsave (); window.dispose (); // Close window System.exit (0); // Close User}} public void insertmodel (DrawModel Anew) {model = anew; model.addobserver ((Observer) View); Model.Addobserver (observer); view.repaint () }}

Package boya; import java.io. *; import java.awt. *; import java.util. *; import java.awt.event. *;

class DrawFrame extends JFrame implements ID, ActionListener, Observer {private Draw theApp; private JMenuBar menubar = new JMenuBar (); private JToolBar toolBar = new JToolBar (); private StatusBar statusBar = new StatusBar (); private FontDialog fontDlg; private JMenuItem aboutItem, fontItem, customColorItem; private JPopupMenu popup; private FileAction newAction, openAction, closeAction, saveAction, saveAsAction, printAction; private TypeAction lineAction, rectangleAction, circleAction, curveAction, textAction; private ColorAction redAction, yellowAction, greenAction, blueAction; private Color elementColor = DEFAULT_ELEMENT_COLOR; private int elementType = DEFAULT_ELEMENT_TYPE; private font font = DEFAULT_FONT; private String frameTitle, filename = DEFAULT_FILENAME; private File modelFile; private boolean changed = false; private JFileChooser files; class FileAction extends AbstractAction {FileAction (String name, String tooltip) {super ( Name); String Icons = "RES /" Name ". GIF"; if (New File ) .Exists ()) putValue (SMALL_ICON, new ImageIcon (icons));! If (tooltip = null) putValue (SHORT_DESCRIPTION, tooltip);} public void actionPerformed (ActionEvent e) {String name = (String) getValue (NAME) ; if (name.equals (newAction.getValue (NAME))) {checkForSave (); theApp.insertModel (new DrawModel ()); modelFile = null; filename = DEFAULT_FILENAME; setTitle (frameTitle files.getCurrentDirectory () "/ / " FileName); Changed = false;} else if (Name.Equals (openaction.getValue (Name))) {Checkforsave (); file file = showdialog (" Open File "," Open "," Read a File " , 'o', null; if (file! = null) OpenDRAW (file);

} Else if (name.equals (name)) {checkforsave (); system.exit (0);} else.equals (newaction.GetValue (name))) {Saveit ();} Else IF (SaveAsAction.GetValue (Name)) {file file = showdialog ("Save As", "Save", "Save Image", 'S', Modelfile == NULL? New File (Files.getCurrentDirectory (), FileName); if (file! = null) {if (file.exists () &&! file.equals (model)) IF (joptionpane.no_option == joptionpane.showconfirmdialog (DrawFrame.THIS, File. GetName () "Exes, Overwear?", "Confirm Save", JOPANE.YES_NO_OPTION, JOTIONPANE.WARNING_MESSAGE ") Return; SaveDraw (file);} return;} else f (name.equals) )) {}}} class ColorAction extends AbstractAction {private Color color; ColorAction (String name, Color color, String tooltip) {super (name); this.color = color; String icons = "res /" name "gif. "; New file (icons) .Exists ()) PUTVALUE (Small_ICON, New Imageicon (ICONS); if (T ooltip = null) putValue (SHORT_DESCRIPTION, tooltip);!} public void actionPerformed (ActionEvent e) {elementColor = color; statusBar.setColorPane (color);}} class TypeAction extends AbstractAction {private int typeID; TypeAction (String name, int typeID , String tooltip {super (name); this.typeId = typeid; string icons = "res /" name ". GIF"; if (new file (icons) .Exists ()) PUTVALUE (SMALL_ICON, NEW ImageICON (ICons )); If (tooltip! = Null) PUTVALUE (short_description, tooltip);} public void actionperformed (ActionEvent E) {ELEMENTTYPE = TypeId;

statusBar.setTypePane (typeID);}} public DrawFrame (String title, Draw theApp) {setTitle (title); this.theApp = theApp; setDefaultCloseOperation (WindowConstants.DISPOSE_ON_CLOSE); setJMenuBar (menubar); // a menu JMenu fileMenu = NEW JMENU ("File (F)"); JMenu ElementMenu = New Jmenu ("Graphics (E)"); JMenu OptionsMenu = New Jmenu ("Option (O)"); JMenu HelpMenu = New Jmenu ("Help (H) "); FileMenu.SetmNemonic ('f'); ElementMenu.SetmNemonic ('e'); OptionsMenu.SetmNemonic ('o'); HelpMenu.SetmNemonic ('h'); // Secondary Menu AddMenuItem (FileMenu, NewAction = New FileAction ("New", "Create New File"), Keystroke .GetKeystroke ('N', Event.ctrl_Mask); AddMenuItem (FileMenu, OpenAction = New FileAction), Keystroke .GetKeystroke ('O', event.ctrl_mask); AddMenuItem (FileMenu, CloseAction = New FileAction, "Close"), Keystroke .GetKeystroke ('x', event.ctrl_mask); FileMenu.addSeparator (); AddMenuItem (FileMenu, SaveAction = New FileAction, "Save File"), Keystroke .GetKeystroke ('s', Event.ctrl_mask); AddMenuItem (FileMenu, SaveasAction = New FileAction ("Save As ...", "File Save")); fileMenu.addseParator (); addMenuItem (FileMenu, PrintAction = New FileAction, "Print File"), Keystroke .GetKeystroke ('P' , Event.CTRL_MASK)); addMenuItem (elementMenu, lineAction = new TypeAction ( "straight", LINE, "draw a straight line"), KeyStroke .getKeyStroke ( '1', Event.CTRL_MASK)); addMenuItem (elementMenu, rectangleAction = new TypeAction ("Rectangle", Rectangle, "Draw Rectangle"), Keystroke .GetKeystroke ('2', Event.ctrl_mask);

addMenuItem (elementMenu, circleAction = new TypeAction ( "ellipse", CIRCLE, "draw an ellipse"), KeyStroke .getKeyStroke ( '3', Event.CTRL_MASK)); addMenuItem (elementMenu, curveAction = new TypeAction ( "curve", CURVE, "Drawing Curve"), Keystroke .GetKeystroke ('4', Event.ctrl_mask); AddMenuItem (ElementMenu, TextAction = New TypeAction), Keystroke .GetKeystroke ('5', Event .Ctrl_mask); ElementMenu.addseParator (); jMenu colorMenu = new jMenu ("color"); ElementMenu.add (ColorMenu); addMenuItem (ColorMenu, Redaction = New ColorAction) ("Red", Color.red ), Keystroke .getKeystroke ('1', Event.alt_mask); AddMenuItem (Colormenu, YellowAction = New ColorAction), "Draw Yellow"), Keystroke .GetKeystroke ('2', Event.alt_Mask AddMenuitem (Colormenu, GreenAction = New ColorAction, Color.green, "Draw Green"), Keystroke .GetKeystroke ('3', Event.alt_Mask); AddMenuItem (Colormenu, BlueAction = New ColorAction) Blue ", Color.Blue," Draw Blue "), Keystroke .GetKeystroke ('4', Event.alt_Mask); AboutItem = New JmenuItem (" About "); AboutItem. setAccelerator (KeyStroke.getKeyStroke ( 'A', Event.CTRL_MASK)); aboutItem.addActionListener (this); helpMenu.add (aboutItem); fontItem = new JMenuItem ( "font selection"); fontItem.setAccelerator (KeyStroke.getKeyStroke ( ' T ', Event.CTRL_MASK)); fontItem.addActionListener (this); optionsMenu.add (fontItem); customColorItem = new JMenuItem ( "color selection"); customColorItem.setAccelerator (KeyStroke.getKeyStroke (' R ', Event.CTRL_MASK) CustomColorItem.com.AddActionListener (this);

Optionsmenu.add (CustomColorItem); MenuBar.Add (FileMenu); MenuBar.Add (ElementMenu); MenuBar.Add (OptionsMenu); MenuBar.Add (HelpMenu); // Setting Toolbar.Add (newAction); Toolbar. Add (openaction); Toolbar.Add (SaveAction); Toolbar.add (PrintAction); Toolbar.Add (LineAction); Toolbar.Add (RectangleAction); Toolbar.Add (CircleAction); Toolbar.Add ( CurveAction); Toolbar.Add (TextAction); Toolbar.addSeparator (); Toolbar.Add (Redaction); Toolbar.Add (YELOWAction); Toolbar.Add (BlueAction); getContentPane (); add (); getContentPane (). add ( toolBar, BorderLayout.NORTH); toolBar.setFloatable (false);. // floating toolbar ban getContentPane () add (statusBar, BorderLayout.SOUTH); fontDlg = new FontDialog (this); popup = new JPopupMenu ( "General") Popup.Add (LineAction); Popup.add (RectangleAction); Popup.add (CircleAction); popup.add (textAction); popup.addseparator (); popup.add (redaction); popup .add (yelowaction); popup.add (greenaction); popup.add (blueaction); files = new JFileChooser (DEFAULT_DIR); frameTitle = title ":"; (! DEFAULT_DIR.exists ()) (! DEFAULT_DIR.mkdirs ()); setTitle (frameTitle filename) if if JOptionPane.showMessageDialog (this, "failed to establish file ! "," Error ", JOPANE.ERROR_MESSAGE);} Private JMenuItem AddMenuItem (JMenu Menu, Action Action) {// Reserved Add menu element's function makes it not image, does not have express keys jMenuitem item = menu.add ( Action); item.seticon (null); Return Item;} Private JMenuItem AddMenuItem (JMenu Menu, Action Action, Keystroke Keys) {// Reserved Function Add Menu Element Make it does not have an image, high key jMenuItem item = Menu.add (Action); item.seticon (null); item.setAccelerator (keys); Return Item

} Private JButton addToolBarButton (Action action) {// add toolbar buttons overloaded JButton button = toolBar.add (action); button.setText (null); return button;} public Color getElementColor () {return elementColor;} public int getElementType () {return elementType;} public font getFont () {return font;} public void setFont (font font) {this.font = font;} public JPopupMenu getPopup () {return popup;} public void actionPerformed (ActionEvent e) {IF (E.GetSource () == AboutItem) {JOPANE.SHOWMESSAGEDIALOG ((Component) E.GetSource () E.GetSource () E.GETSOURCE (), version Description: Draw Software by Boya Production, "About", JOPANE.INFORMATION_MESSAGE);} else IF E.GetSource () == fontItem) {Rectangle Bounds = getBounds (); fontdlg.setlocation (bounds.x bounds.width / 3, bounds.y bounds.height / 3); fontdlg.setvisible (TRUE); Else if (E.GetSource () == CustomColorItem) {color color = jcolorchooser.showdialog (this, "color selection", elementColor); if (color! = null) {ElementColor = Color; statusbar.setColorPane (color);} }} Public void update (Observable O, Object Obj) {Changed = True;} private File showDialog (String dlgTitle, String ABT, String ABTP, char ABM, File file) {files.setDialogTitle (dlgTitle); files.setApproveButtonText (ABT); files.setApproveButtonToolTipText (ABTP); files.setApproveButtonMnemonic (ABM ); files.rescanCurrentDirectory (); files.setSelectedFile (file); int result = files.showDialog (DrawFrame.this, null); return (result == files.APPROVE_OPTION) files.getSelectedFile ():? null;} private void Saveit () {if (! call) return; if (model! = null) savedraw (model); else {file file = showdialog ("Save Image", "Save", "Save Picture", 'S'

, New File (files.getCurrentDirectory (), filename)); if (file == null) return; else if (file.exists ()) if (JOptionPane.NO_OPTION == JOptionPane.showConfirmDialog (DrawFrame.this, file.getName () ? "already exists, the cover", "confirm saving", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE)) return; saveDraw (file);}} private void saveDraw (File outFile) {try {ObjectOutputStream out = new ObjectOutputStream ( NEW BUFFEREDOUTPUTSTREAM (outfile)); out.writeObject (theapp.getmodel ()); out.flush (); out.close ();} catch (ioException e) {system.out.println (e); JOptionPane.showMessageDialog (DrawFrame.this, "error", "save failed", JOptionPane.ERROR_MESSAGE); return;} if (outFile = modelFile!) {modelFile = outFile; filename = modelFile.getName (); setTitle (frameTitle modelFile .getpath ());} Changd = false;} public void OpenDraw (file infile) {Try {ObjectInputStream IN = New ObjectInputStream (New FileInputStream (New FileInputStream (Infile)) THEAPP.INSERTMODEL ((DrawModel) in. ReadObject ()); In.close (); ModelfIle = Infile; FileName = Modelfile.GetName (); settitle (frametitle modelfile.getPath ());} catch (exception e) { System.out.println (e); JOptionPane.showMessageDialog (DrawFrame.this, "error", "open failure", JOptionPane.ERROR_MESSAGE); return;}} public void checkForSave () {if (changed) if (JOptionPane.YES_OPTION == JOPANE.SHOWCONFIRMDIALOG (DrawFrame.THIS, "file has been modified, saved? "," Confirm Save ", JOPTIONPANE.YES_NO_OPTION, JOPANE.WARNING_MESSAGE)) Saveit ())

package boya; import java.io *;. import java.util *;. class DrawModel extends Observable implements Serializable {protected LinkedList elements = new LinkedList (); public void add (Elements element) {elements.add (element); setChanged ( ); notifyObservers (element.getBounds ());} public boolean remove (Elements element) {boolean removed = elements.remove (element); if (removed) {setChanged (); notifyObservers (element.getBounds ());} return Removed;} public iterator getiterator () {return Elements.listiterator ();}}

Package boya; import java.awt. *; import java.util. *; import java.awt.event. *; import javax.swing. *; import javax.swing.event. * ; class drawView extends JComponent implements Observer, ID {private Draw theApp; public drawView (Draw theApp) {this.theApp = theApp; MouseHandler handler = new MouseHandler (); addMouseListener (handler); addMouseMotionListener (handler);} class MouseHandler extends MouseInputAdapter {private Point start, end; private Elements temp; private Graphics2D g2D; private Elements createElement (Point start, Point end) {switch {case LINE (theApp.getWindow () getElementType ().): return new Elements.Line (start, end, theApp.getWindow () getElementColor ()); case RECTANGLE:. return new Elements.Rectangle (start, end, theApp.getWindow () getElementColor ()); case CIRCLE:. return new Elements.Circle (start, end, THEAPP.GETWINDOW (). getElementColor ()); Case Curve: Return New Elements.curve (Start, End, THEAPP.GETWINDOW (). getElementColor ();} Retur N null;} public void mousepressed (mouseEvent e) {start = E.GETPOINT (); int modifier = E.GETMODIFIERS (); if ((Modifier & E.BUTTON1_MASK)! = 0) {G2D = (Graphics2D) getGraphics (); G2d.setxormode (G2D.SetPaint); getElementColor ();}} public void mousedragged (MouseEvent E) {end = E.GETPOINT (); int modifier = E.GETMODIFIERS () ; ((Modifier & E.BUTTON1_MASK)! = 0 && () .getElementType ()! = Text) {if (temp == null) TEMP = CreateElement (start, end); else {temp.draw (G2D ); Temp.moving (start, end);} temp.draw (g2d);}} public void mousereleased (mouseEvent E) {int modifier = E.GETMODIFIERS ();

IF (E.Ispopuptrigger ()) {start = E.GETPOINT (); THEAPP.GETWINDOW (). getPopup (). SHOW ((Component) E.GETSOURCE (), start.x, start.y); start = NULL Else IF ((Modifier & E.BUTTON1_DOWN_MASK) == 0 && () {if (temp! = Null) {{godel (). Add (temp); temp! NULL;} if (g2d! = null) {g2d.dispose (); g2d = null;} start = end = null;}} public void mouseclicked (mouseEvent e) {int modifier = E.GETMODIFIERS (); if (((); if Modifier & E.BUTTON1_MASK)! = 0 && () {start = j.getpoint (); string text = j.getpane.showinputDialog () E.GETSOUROG () E.Getsource () E.GETSOURCE () E.Getsource () E.Getsource () E.Getsource () "," Text ", JOPANE.PLAIN_MESSAGE); if (text! = NULL) {G2D = (graphics2d) getGraphics (); font font = theapp.getWindow (). GetFont (); Temp = New Elements.text (font, Text, Start, THEAPP.GETWINDOW (). getElementColor (), font.getstringbounds (text, g2d.getfontrenderContext ()). getBounds ()); Temp.draw (G2D); if (Temp) ! = null) THEAPP.GETMODEL (). add (temp); temp = null; g2d.dispose (); g2d = null; start = null;}}}} public void Update (Observable O, Object Rectangle) {ix rectangle == null) repaint (); else repaint ((Rectangle) rectangle);} public void paint (Graphics g) {Graphics2D g2D = (Graphics2D) g; Iterator elements = theApp.getModel () getIterator ();. Elements element WHILE (Elements.hasNext ()) {Element = (Elements) Elements.next (); Element.draw (G2D);}}}

package boya; import java.io *;. import java.awt *;. import java.util *;. import java.awt.geom *;. abstract class Elements implements Serializable {protected Color color; public Elements (Color color) { this.color = color;} public Color getColor () {return color;} public abstract java.awt.Rectangle getBounds (); public abstract void moving (Point start, Point end); public abstract void draw (Graphics2D g2D); public static class Line extends Elements {private Line2D.Double line; public Line (Point start, Point end, Color color) {super (color); line = new Line2D.Double (start, end);} public java.awt.Rectangle getBounds () {Return line.getbounds (); PUBLIC VOID MOVING (Point Start, Point End) {line.x2 = end.x; line.y2 = end.y;} public void draw (graphics2d g2d) {g2d.setpain (color); g2D.draw (line);} private void writeObject (ObjectOutputStream out) throws IOException {out.writeDouble (line.x2); out.writeDouble (line.y2);} private void readObject (java.io.ObjectInputStream in) T hrows IOException, ClassNotFoundException {double x2 = in.readDouble (); double y2 = in.readDouble (); line = new Line2D.Double (0,0, x2, y2);}} public static class Rectangle extends Elements {private Rectangle2D .Double Rectangle; Public Rectangle; Point Start, Point End, Color Color {Super (Color); Rectangle = New Rectangle2d.double (Math.Min (Start.x, End.x), Math.min (Start.y, End.y), math.abs (start.x-end.x), math.abs (start.y-end.y));} public java.awt.Rectangle getBounds () {return rectangle.getBounds (); } Public void moving (points.x = math.min (start.x, end.x); rectangle.y = math.min (start.y, end.y); Rectangle.Width = Math.abs (start.x-end.x); Rectangle.Height =

Math.abs (start.y-end.y);} public void draw (Graphics2D g2D) {g2D.setPaint (color); g2D.draw (rectangle);} private void writeObject (ObjectOutputStream out) throws IOException {out.writeDouble (rectangle.width); out.writeDouble (rectangle.height);} private void readObject (java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {double width = in.readDouble (); double height = in.readDouble (); rectangle = new Rectangle2D.Double (0,0, width, height);}} public static class Circle extends Elements {private Ellipse2D.Double circle; public Circle (Point center, Point circum, Color color) {super (color); double Radius = center.distance (circume); circle = new elipse2d.double (center.x-radius, center.y-radius, 2 * radius, 2 * radius);} public java.awt.Rectangle getBounds () {Return Circle PUBLIC VOID MOVING (POINT CIENT CENTER, POINT CIRCUM) {Double Radius = Center.distance (Circum); circle.x = center.x- (int) RADIUS; circle.y = center.y- (int) ) RADIUS; CIRCL e.width = circle.height = 2 * radius;} public void draw (Graphics2D g2D) {g2D.setPaint (color); g2D.draw (circle);} private void writeObject (ObjectOutputStream out) throws IOException {out.writeDouble ( circle.width);} private void readObject (java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {double width = in.readDouble (); circle = new Ellipse2D.Double (0,0, width, width);}} public static class Curve extends Elements {private GeneralPath curve; public Curve (Point start, Point next, Color color) {super (color); curve = new GeneralPath (); curve.moveTo (start.x, start.y); curve. LINETO (Next.x, Next.y);

} Public java.awt.Rectangle getBounds () {return curve.getbounds (); PUBLIC VOID MOVING (Point Start, Point NEXT) {curve.lineto (next.x, next.y);} public void Draw (Graphics2D G2D) ) {g2D.setPaint (color); g2D.draw (curve);} private void writeObject (ObjectOutputStream out) throws IOException {PathIterator iterator = curve.getPathIterator (new AffineTransform ()); Vector coords = new Vector (); int max = 6; float [] temp = new float [max]; int result = iterator.currentsegment (TEMP); if (! (! (R == iterator.seg_moveto) {System.out.println ("no starting moveto); }}}} tle (! @ ier .is ()) {result = iterator.currentsegment (TEMP); if (! (! (!) {System.out.println ("Invalid Segment) (" Invalid Segment) TYPE "); Return;} Coords.add (New float)); Coords.Add (new float); item.next ();} out.writeObject (CoRDS); Private void readobject (java.io.objectInputstream in) throws oException, classnotfou NDEXCEPTION {Vector Coords = (vector) in.readObject (); curve = new generalpath (); curve.moveto (0); float x, y; for (int i = 0; i

} Public static class Text extends Elements {private Font font; private String text; private Point pos; private java.awt.Rectangle bounds = null; public Text (Font font, String text, Point pos, Color color, java.awt.Rectangle Bounds) {super (color); this.font = font; this.text = text; this.pos = pos; this.bounds = bounds; this.bounds.setlocation (pos.x, pos.y- (int) Bounds .getHeight ());} public java.awt.Rectangle getBounds () {return bounds;} public void moving (Point start, Point end) {} ​​public void draw (Graphics2D g2D) {g2D.setPaint (color); Font oldFont = g2d.getfont (); g2d.setfont (font); g2d.drawstring (text, pos.x, pos.y); g2d.setfont (oldfont);}}}

package boya; import java.awt *;. import java.awt.event *;. import javax.swing *;. import javax.swing.event *;. import javax.swing.border *;. class FontDialog extends JDialog implements ID , ActionListener, ListSelectionListener {private DrawFrame window; private font font; private int style; private int size; private JButton ok, cancel; private JList fontList; private JLabel fontDisplay; private JComboBox chooseSize; public FontDialog (DrawFrame window) {super (window, "Font Selection", TRUE); this.Window = window; font = window.getfont (); style = font.getStyle (); size = font.getsize (); jPanel button = new jPanel (); button.add ( OK = CREATEBUTTON ("confirmation")); ButtonPane.Add ("Cancel = CreateButton); getContentPane (); add (buttonpane, borderlayout.south); jPanel DataPane = new jPanel (); datapane.setborder (BorderFactory) .CreateCompoundBorder (BorderFactory.createLineborder (Color Factory.createemptyBorder (5, 5, 5, 5))); GridbagLayout Gbleout = New GridbagLayout (); DataPane.setLayout (GBLA yout); GridBagConstraints constraints = new GridBagConstraints (); JLabel label = new JLabel ( "the font selection"); constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridwidth = GridBagConstraints.REMAINDER; gbLayout.setConstraints (label, constraints); dataPane. add (label); GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment (); String [] fonts = e.getAvailableFontFamilyNames (); fontList = new JList (fonts); fontList.setValueIsAdjusting (true); fontList.setSelectionMode (ListSelectionModel.SINGLE_SELECTION); fontList .SetSelectedValue (font.getfamily (), true); fontlist.addlistSelectionListener (this); jscrollpane choosefont =

new JScrollPane (fontList); chooseFont.setMinimumSize (new Dimension (300,100)); JPanel display = new JPanel (); fontDisplay = new JLabel ( "Font Sample: x X y Y z Z"); fontDisplay.setPreferredSize (new Dimension (300,100)); display.add (fontDisplay); JSplitPane splitPane = new JSplitPane (JSplitPane.VERTICAL_SPLIT, true, chooseFont, display); gbLayout.setConstraints (splitPane, constraints); dataPane.add (splitPane); JPanel sizePane = new JPanel (); Label = new jlabel ("Select Font Size"); SIZEPANE.ADD (Label); String [] Sizelist = {"8", "10", "12", "14", "16", "18 "" 20 "," 22 "," 24 "}; choosesize = new jcomboBOX (Sizelist); hoose.tostring (size)); choosesize.addactionListener (this); sizepane.add (choosesize); gblayout .setConstraints (sizePane, constraints); dataPane.add (sizePane); JRadioButton bold = new JRadioButton ( "bold", (style & Font.BOLD)> 0); JRadioButton italic = new JRadioButton ( "italic", (style & Font.ITALIC) > 0); bold.additemlistener (New Stylelistener (Font.Bold); Italic.Additemlistener (New Stylelistener FONT.ITALIC); JPANEL STYLEPANE = New jPanel (); stylepane.add (bold); stylepane.add (Italic); gbLayout.SetConstraints (StylePane, Constraints); DataPane.Add (STYLEPANE); getContentPane (). Add ( dataPane, BorderLayout.CENTER); pack (); setVisible (false);} JButton createButton (String label) {JButton button = new JButton (label); button.setPreferredSize (new Dimension (80,20)); button.addActionListener ( This); return button;} public void actionPerformed (ActionEvent E) {Object Source = E.GETSource (); if (source == ok) {Window.SetFont (font); setvisible (false);

} Else if (source == cancel) setvisible (false); else = = cosesize {size = integer.parseint ((String) ChooseSize.getSelectedItem ()); font = font.derivefont ((float) size ; fontDisplay.setFont (font); fontDisplay.repaint (); (! e.getValueIsAdjusting ())}} public void valueChanged (ListSelectionEvent e) {if {font = new font ((String) fontList.getSelectedValue (), style, size); fontDisplay.setFont (font); fontDisplay.repaint ();}} class StyleListener implements ItemListener {private int astyle; public StyleListener (int style) {this.astyle = style;} public void itemStateChanged (ItemEvent e) {if (E.getStateChange () == itemEvent.selected) style | = ASTYLE; Else Style & = ~ ASTYLE; font = font.derivefont (style); fontdisplay.setfont (font); fontdisplay.repaint ();}}} package boya Import java.awt. *; import java.io.file; public interface id {int line = 101; int Rectangle = 102; int curce = 103; int curve = 104; int text = 105; int default_element_type = line; color Default_Element_Color = Color .red; font default_font = new font, font.plain, 20); file default_dir = new file ("c: / my draw"); string default_filename = "untricled.ice";}

package boya; import java.awt *;. import javax.swing *;. import javax.swing.border *;. class StatusBar extends JPanel implements ID {private StatusPane colorPane = new StatusPane ( "red"); private StatusPane typePane = new StatusPane ( "linear"); class StatusPane extends JLabel {private Font paneFont = new Font ( "Arial", Font.PLAIN, 12); public StatusPane (String text) {setForeground (Color.black); setFont (paneFont); setHorizontalAlignment (CENTER); setBorder (BorderFactory.createBevelBorder (BevelBorder.LOWERED)) ;; setPreferredSize (new Dimension (70,18)); setText (text);}} public StatusBar () {setLayout (new FlowLayout (FlowLayout.RIGHT, 10 , 3)); setBorder (BorderFactory.createLineBorder (Color.LIGHT_GRAY)); setColorPane (DEFAULT_ELEMENT_COLOR); setTypePane (DEFAULT_ELEMENT_TYPE); add (colorPane); add (typePane);} public void setColorPane (Color color) {String text; if (Color.EQUALS (Color.red)) Text = "Red"; Else IF (Color.Equals (Color.Yellow)) Text = "Yellow"; Else IF (Color.equals (Color.green)) Text = "Green " Else IF (color.blue)) text = "blue"; else text = "Unefained"; colorpane.setText (text);} public void settypepane (int element) {string text; switch (element) {Case Line: Text = "Straight"; Break; Case Rectangle: Text = "Rectangular"; Break; Case Case: Text = "Round"; Break; Case CURVE: Text = "Curve"; Break; Case Text: Text = "Text"; break; default: text = "error"; break;} typepane.settext (}}) The generated code can be placed in the JAR package so that it can be installed in the environment where JVM is installed. This JAR package is an executable file.

The structure of the package is as follows: - DRAW ---- Boya ---- Meta-INF ---- RES

It is package, configuration file, resources, respectively.

Creating files in Meta-INF Write: Manifest-Version: 1.0mAin-Class: Boya.Draw This package is completed this package to complete Main-Class: Boya.draw

转载请注明原文地址:https://www.9cbs.com/read-52305.html

New Post(0)