⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sketchframe.java

📁 非常好的java事例以及带源码事例的java2教程
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
// Frame for the Sketcher application
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.awt.print.*;

public class SketchFrame extends JFrame
                         implements Constants, ActionListener, Observer
{
  // Constructor
  public SketchFrame(String title, Sketcher theApp)
  {
    this.theApp = theApp;
    setJMenuBar(menuBar);                         // Add the menu bar to the window

    JMenu fileMenu = new JMenu("File");           // Create File menu
    JMenu elementMenu = new JMenu("Elements");    // Create Elements menu
    JMenu optionsMenu = new JMenu("Options");     // Create options menu
    JMenu helpMenu = new JMenu("Help");           // Create Help menu

    fileMenu.setMnemonic('F');                    // Create shortcut
    elementMenu.setMnemonic('E');                 // Create shortcut
    optionsMenu.setMnemonic('O');                 // Create shortcut
    helpMenu.setMnemonic('H');                    // Create shortcut 

    // Construct the file pull down menu
    addMenuItem(fileMenu, 
                newAction = new FileAction("New", "Create new sketch"),
                KeyStroke.getKeyStroke('N',Event.CTRL_MASK ));
    addMenuItem(fileMenu, 
                openAction = new FileAction("Open", "Open existing sketch"), 
                KeyStroke.getKeyStroke('O',Event.CTRL_MASK ));
    addMenuItem(fileMenu, 
                closeAction = new FileAction("Exit", "Exit Sketcher"), null);
    fileMenu.addSeparator();                                       // Add separator
    addMenuItem(fileMenu, 
                saveAction = new FileAction("Save", "Save sketch"),
                KeyStroke.getKeyStroke('S',Event.CTRL_MASK ));
    addMenuItem(fileMenu, 
                saveAsAction = new FileAction("Save As...","Save as new file"),
                null);
    fileMenu.addSeparator();                                       // Add separator
    addMenuItem(fileMenu, 
                printAction = new FileAction("Print", "Print sketch"),
                KeyStroke.getKeyStroke('P',Event.CTRL_MASK ));
    fileMenu.addSeparator();                                     // Add separator
    addMenuItem(fileMenu, closeAction = new FileAction("Exit", "Exit Sketcher"),
                                    KeyStroke.getKeyStroke('X',Event.CTRL_MASK ));
     
    // Construct the Element pull down menu
    addMenuItem(elementMenu, 
                lineAction = new TypeAction("Line", LINE, "Draw lines"));
    addMenuItem(elementMenu, 
                rectangleAction = new TypeAction("Rectangle", RECTANGLE, 
                                                 "Draw rectangles"));
    addMenuItem(elementMenu, 
                circleAction = new TypeAction("Circle", CIRCLE, "Draw circles"));
    addMenuItem(elementMenu, 
                curveAction = new TypeAction("Curve", CURVE, "Draw curves"));
    addMenuItem(elementMenu, textAction = new TypeAction("Text", TEXT,
                                                         "Draw text"), null);

    elementMenu.addSeparator();

    JMenu colorMenu = new JMenu("Color");         // Color sub-menu
    elementMenu.add(colorMenu);                   // Add the sub-menu
    addMenuItem(colorMenu, 
                redAction = new ColorAction("Red", Color.red, "Draw in red"));
    addMenuItem(colorMenu, 
                yellowAction = new ColorAction("Yellow", Color.yellow,
                                                               "Draw in yellow"));
    addMenuItem(colorMenu, 
                greenAction = new ColorAction("Green", Color.green, 
                                                                "Draw in green"));
    addMenuItem(colorMenu, 
                blueAction = new ColorAction("Blue", Color.blue, "Draw in blue"));

    // Add the font choice item to the options menu
    fontItem = new JMenuItem("Choose font...");
    fontItem.addActionListener(this);
    optionsMenu.add(fontItem);

    // Add the About item to the Help menu
    aboutItem = new JMenuItem("About");           // Create the item
    aboutItem.addActionListener(this);            // Listener is the frame
    helpMenu.add(aboutItem);                      // Add item to menu

    menuBar.add(fileMenu);                        // Add the file menu
    menuBar.add(elementMenu);                     // Add the element menu
    menuBar.add(optionsMenu);                     // Add the options menu
    menuBar.add(helpMenu);                        // Add the Help menu

    // Add file buttons
    toolBar.addSeparator();                                 // Space at the start
    addToolBarButton(newAction);
    addToolBarButton(openAction);
    addToolBarButton(saveAction);
    addToolBarButton(printAction);
   
    // Add element type buttons
    toolBar.addSeparator();
    addToolBarButton(lineAction);
    addToolBarButton(rectangleAction);
    addToolBarButton(circleAction);
    addToolBarButton(curveAction);

    // Add element color buttons
    toolBar.addSeparator();
    addToolBarButton(redAction);
    addToolBarButton(yellowAction);
    addToolBarButton(greenAction);
    addToolBarButton(blueAction);
    toolBar.addSeparator();                            // Space at the end

    addToolBarButton(textAction);

    // Create pop-up menu
    popup.add(lineAction);
    popup.add(rectangleAction);
    popup.add(circleAction);
    popup.add(curveAction);
    popup.add(textAction);

    popup.addSeparator();
    popup.add(redAction);
    popup.add(yellowAction);
    popup.add(greenAction);
    popup.add(blueAction);

    toolBar.setBorder(BorderFactory.createCompoundBorder(       // Toolbar border
                      BorderFactory.createLineBorder(Color.darkGray),
                      BorderFactory.createEmptyBorder(2,2,4,2)));   

    toolBar.setFloatable(false);                       // Inhibit toolbar floating
    getContentPane().add(toolBar, BorderLayout.NORTH); // Add the toolbar

    getContentPane().add(statusBar, BorderLayout.SOUTH);         // Add the statusbar
    fontDlg = new FontDialog(this);

    customColorItem = popup.add("Custom Color...");    // Add the item
    customColorItem.addActionListener(this);           // and add its listener

    frameTitle = title + ": ";        
    setTitle(frameTitle + filename);

    if(!DEFAULT_DIRECTORY.exists())
      if(!DEFAULT_DIRECTORY.mkdirs())
        JOptionPane.showMessageDialog(this,
                                      "Error creating default directory",
                                      "Directory Creation Error",
                                      JOptionPane.ERROR_MESSAGE);
    files = new JFileChooser(DEFAULT_DIRECTORY);
  }

  // Method called by SketchModel object when it changes
  public void update(Observable o, Object obj)
  {
    sketchChanged = true;
  }

  private JButton addToolBarButton(Action action)
  {
    JButton button = toolBar.add(action);                     // Add toolbar button
    button.setToolTipText((String)action.getValue(action.SHORT_DESCRIPTION));
    button.setBorder(BorderFactory.createRaisedBevelBorder()); // Add button border
    button.setText(null);                                     // No button text
    return button;
  }

  private JMenuItem addMenuItem(JMenu menu, Action action)
  {
    JMenuItem item = menu.add(action);                  // Add the menu item
    item.setIcon(null);                                 // Remove the icon
    return item;                                        // Return the menu item
  }

  private JMenuItem addMenuItem(JMenu menu, Action action, KeyStroke keystroke)
  {
    JMenuItem item = addMenuItem(menu, action);         // Add the menu item
    item.setAccelerator(keystroke);                     // Set the accelerator
    return item;                                        // Return the menu item
  }

  // Display a custom file save dialog
  private File showDialog (String dialogTitle,
                          String approveButtonText,
                          String approveButtonTooltip,
                          char approveButtonMnemonic,
                          File file)                       // Current file - if any
  {
    files.setDialogTitle(dialogTitle);
    files.setApproveButtonText(approveButtonText);
    files.setApproveButtonToolTipText(approveButtonTooltip);
    files.setApproveButtonMnemonic(approveButtonMnemonic);
    files.setFileSelectionMode(files.FILES_ONLY);
    files.rescanCurrentDirectory();
    files.setSelectedFile(file);

    ExtensionFilter sketchFilter = new ExtensionFilter(".ske", 
                                        "Sketch files (*.ske)");
    files.addChoosableFileFilter(sketchFilter);             // Add the filter
    files.setFileFilter(sketchFilter);                      // and select it

    int result = files.showDialog(SketchFrame.this, null);  // Show the dialog
    return (result == files.APPROVE_OPTION) ? files.getSelectedFile() : null;
  }

  // Save the sketch if it is necessary
  private void saveOperation()
  {
    if(!sketchChanged)
      return;
    if(modelFile != null)
      saveSketch(modelFile);
    else
    {
      File file = showDialog("Save Sketch",
                             "Save",
                             "Save the sketch",
                             's',
                             new File(files.getCurrentDirectory(), filename));
      if(file == null)
        return;
      else
        if(file.exists())                      // Check for existence
          if(JOptionPane.NO_OPTION ==          // Overwrite warning
              JOptionPane.showConfirmDialog(SketchFrame.this,
                                      file.getName() + " exists. Overwrite?",
                                      "Confirm Save As",
                                      JOptionPane.YES_NO_OPTION,
                                      JOptionPane.WARNING_MESSAGE))
            return;                            // No selected file
      saveSketch(file);
    }
  }

  // Write a sketch to outFile
  private void saveSketch(File outFile)
  {
    try
    {
      ObjectOutputStream out =  new ObjectOutputStream(
                                new BufferedOutputStream(
                                new FileOutputStream(outFile)));
      out.writeObject(theApp.getModel());        // Write the sketch to the stream
      out.flush();                               // Flush the stream
      out.close();                               // And close it
    }
    catch(IOException e)
    {
      JOptionPane.showMessageDialog(SketchFrame.this,
                                          "Error writing a sketch file.",
                                              "File Output Error",
                                              JOptionPane.ERROR_MESSAGE);
      return;                                      // Serious error - return
    }
    if(outFile != modelFile)                      // If we are saving to a new file
    {                                              // we must update the window
      modelFile = outFile;                         // Save file reference
      filename = modelFile.getName();              // Update the file name
      setTitle(frameTitle + modelFile.getPath());  // Change the window title
    }
    sketchChanged = false;                         // Set as unchanged
  }

  public Color getElementColor()
  { 
    return elementColor; 
  }

  public int getElementType()

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -