Java Swing

WebView

import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.html.*;
// The Simple Web Browser.
public class MiniBrowser extends JFrame implements HyperlinkListener {
  // These are the buttons for iterating through the page list.
  private JButton backButton, forwardButton;
  // Page location text field.
  private JTextField locationTextField;
  // Editor pane for displaying pages.
  private JEditorPane displayEditorPane;
  // Browser's list of pages that have been visited.
  private ArrayList pageList = new ArrayList();
  // Constructor for Mini Web Browser.
  public MiniBrowser() {
    // Set application title.
    super("Mini Browser");
    // Set window size.
    setSize(640, 480);
    // Handle closing events.
    addWindowListener(
      new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
          actionExit();
        }
      }
    );
    // Set up file menu.
    JMenuBar menuBar = new JMenuBar();
    JMenu fileMenu = new JMenu("File");
    fileMenu.setMnemonic(KeyEvent.VK_F);
    JMenuItem fileExitMenuItem = new JMenuItem("Exit", KeyEvent.VK_X);
    fileExitMenuItem.addActionListener(
      new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          actionExit();
        }
      }
    );
    fileMenu.add(fileExitMenuItem);
    menuBar.add(fileMenu);
    setJMenuBar(menuBar);
    // Set up button panel.
    JPanel buttonPanel = new JPanel();
    backButton = new JButton("< Back");
    backButton.addActionListener(
      new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          actionBack();
        }
      }
    );
    backButton.setEnabled(false);
    buttonPanel.add(backButton);
    forwardButton = new JButton("Forward >");
    forwardButton.addActionListener(
      new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          actionForward();
        }
      }
    );
    forwardButton.setEnabled(false);
    buttonPanel.add(forwardButton);
    locationTextField = new JTextField(35);
    locationTextField.addKeyListener(
      new KeyAdapter() {
        public void keyReleased(KeyEvent e) {
          if (e.getKeyCode() == KeyEvent.VK_ENTER) {
            actionGo();
          }
        }
      }
    );
    buttonPanel.add(locationTextField);
    JButton goButton = new JButton("GO");
    goButton.addActionListener(
      new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          actionGo();
        }
      }
    );
    buttonPanel.add(goButton);
    // Set up page display.
    displayEditorPane = new JEditorPane();
    displayEditorPane.setContentType("text/html");
    displayEditorPane.setEditable(false);
    displayEditorPane.addHyperlinkListener(this);
    getContentPane().setLayout(new BorderLayout());
    getContentPane().add(buttonPanel, BorderLayout.NORTH);
    getContentPane()
      .add(new JScrollPane(displayEditorPane), BorderLayout.CENTER);
  }
  // Exit this program.
  private void actionExit() {
    System.exit(0);
  }
  // Go back to the page viewed before the current page.
  private void actionBack() {
    URL currentUrl = displayEditorPane.getPage();
    int pageIndex = pageList.indexOf(currentUrl.toString());
    try {
      showPage(new URL((String) pageList.get(pageIndex - 1)), false);
    } catch (Exception e) {}
  }
  // Go forward to the page viewed after the current page.
  private void actionForward() {
    URL currentUrl = displayEditorPane.getPage();
    int pageIndex = pageList.indexOf(currentUrl.toString());
    try {
      showPage(new URL((String) pageList.get(pageIndex + 1)), false);
    } catch (Exception e) {}
  }
  // Load and show the page specified in the location text field.
  private void actionGo() {
    URL verifiedUrl = verifyUrl(locationTextField.getText());
    if (verifiedUrl != null) {
      showPage(verifiedUrl, true);
    } else {
      showError("Invalid URL");
    }
  }
  // Show dialog box with error message.
  private void showError(String errorMessage) {
    JOptionPane.showMessageDialog(
      this,
      errorMessage,
      "Error",
      JOptionPane.ERROR_MESSAGE
    );
  }
  // Verify URL format.
  private URL verifyUrl(String url) {
    // Only allow HTTP URLs.
    if (!url.toLowerCase().startsWith("http://")) return null;
    // Verify format of URL.
    URL verifiedUrl = null;
    try {
      verifiedUrl = new URL(url);
    } catch (Exception e) {
      return null;
    }
    return verifiedUrl;
  }
  /* Show the specified page and add it to
     the page list if specified. */
  private void showPage(URL pageUrl, boolean addToList) {
    // Show hour glass cursor while crawling is under way.
    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    try {
      // Get URL of page currently being displayed.
      URL currentUrl = displayEditorPane.getPage();
      // Load and display specified page.
      displayEditorPane.setPage(pageUrl);
      // Get URL of new page being displayed.
      URL newUrl = displayEditorPane.getPage();
      // Add page to list if specified.
      if (addToList) {
        int listSize = pageList.size();
        if (listSize > 0) {
          int pageIndex = pageList.indexOf(currentUrl.toString());
          if (pageIndex < listSize - 1) {
            for (int i = listSize - 1; i > pageIndex; i--) {
              pageList.remove(i);
            }
          }
        }
        pageList.add(newUrl.toString());
      }
      // Update location text field with URL of current page.
      locationTextField.setText(newUrl.toString());
      // Update buttons based on the page being displayed.
      updateButtons();
    } catch (Exception e) {
      // Show error messsage.
      showError("Unable to load page");
    } finally {
      // Return to default cursor.
      setCursor(Cursor.getDefaultCursor());
    }
  }
  /* Update back and forward buttons based on
     the page being displayed. */
  private void updateButtons() {
    if (pageList.size() < 2) {
      backButton.setEnabled(false);
      forwardButton.setEnabled(false);
    } else {
      URL currentUrl = displayEditorPane.getPage();
      int pageIndex = pageList.indexOf(currentUrl.toString());
      backButton.setEnabled(pageIndex > 0);
      forwardButton.setEnabled(pageIndex < (pageList.size() - 1));
    }
  }
  // Handle hyperlink's being clicked.
  public void hyperlinkUpdate(HyperlinkEvent event) {
    HyperlinkEvent.EventType eventType = event.getEventType();
    if (eventType == HyperlinkEvent.EventType.ACTIVATED) {
      if (event instanceof HTMLFrameHyperlinkEvent) {
        HTMLFrameHyperlinkEvent linkEvent = (HTMLFrameHyperlinkEvent) event;
        HTMLDocument document = (HTMLDocument) displayEditorPane.getDocument();
        document.processHTMLFrameHyperlinkEvent(linkEvent);
      } else {
        showPage(event.getURL(), true);
      }
    }
  }
  // Run the Mini Browser.
  public static void main(String[] args) {
    MiniBrowser browser = new MiniBrowser();
    browser.show();
  }
}Copy to clipboardErrorCopied

Swing 介绍

Swing 是 Java 平台的 UI:它充当处理用户和计算机之间全部交互的软件。它实际上充当用户和计算机内部之间的中间人。Swing 到底是如何做这项工作的呢?它提供了处理前面一节中描述的 UI 各方面内容的机制:

  • 键盘:Swing 提供了捕捉用户输入的方法。
  • 颜色:Swing 提供改变在屏幕上看到的颜色的方法。
  • 打字的地址栏:Swing 提供了文本组件,处理所有普通任务。
  • 音量:Swing 不太擅长。

无论如何,Swing 为您提供了创建自己的 UI 所需要的所有工具

JFrame

JFrame frame = new JFrame();
对于JFrame,在界面初始化完成时,加入以下代码:
//设置标题。
frame.setTitle("Your title");
// JFrame关闭后退出。
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
// JFrame可见。
frame.setVisible(true);
//设置JFrame的长和宽。
frame.setSize(800, 400);
// 设置JFrame是否可以改变大小。
frame.setResizable(false);
// JFrame打开后居中。
private Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
/** 屏幕宽度 */
private int screenWidth = screenSize.width;
/** 屏幕高度 */
private int screenHeight = screenSize.height;
jFrame.setLocation((screenWidth - FRAME_WIDTH) / 2, (screenHeight - FRAME_HEIGHT) / 2);Copy to clipboardErrorCopied

JPanel

JButton 在 FlowLayout、BorderLayout 等一些布局中使用 setSize()设置大小没效果,可以使用 setPreferredSize 方法进行设置,例如:

public static void main(String[] args) {
  JFrame frame = new JFrame();
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.setLayout(new FlowLayout());
  JButton button = new JButton("测试按钮");
  Dimension preferredSize = new Dimension(300,100);//设置尺寸
  button.setPreferredSize(preferredSize );
  frame.add(button);
  frame.setBounds(0,0, 400, 300);
  frame.setVisible(true);
 }Copy to clipboardErrorCopied

Font

Font font = new Font("宋体",Font.PLAIN,12);
        UIManager.put("Button.font", font);
        UIManager.put("CheckBox.font", font);
        UIManager.put("CheckBoxMenuItem.acceleratorFont", font);
        UIManager.put("CheckBoxMenuItem.font", font);
        UIManager.put("ColorChooser.font", font);
        UIManager.put("ComboBox.font", font);
        UIManager.put("DesktopIcon.font", font);
        UIManager.put("EditorPane.font", font);
        UIManager.put("FormattedTextField.font", font);
        UIManager.put("InternalFrame.titleFont", font);
        UIManager.put("Label.font", font);
        UIManager.put("List.font", font);
        UIManager.put("Menu.acceleratorFont", font);
        UIManager.put("Menu.font", font);
        UIManager.put("MenuBar.font", font);
        UIManager.put("MenuItem.acceleratorFont", font);
        UIManager.put("MenuItem.font", font);
        UIManager.put("OptionPane.font", font);
        UIManager.put("Panel.font", font);
        UIManager.put("PasswordField.font", font);
        UIManager.put("PopupMenu.font", font);
        UIManager.put("ProgressBar.font", font);
        UIManager.put("RadioButton.font", font);
        UIManager.put("RadioButtonMenuItem.acceleratorFont", font);
        UIManager.put("RadioButtonMenuItem.font", font);
        UIManager.put("ScrollPane.font", font);
        UIManager.put("Spinner.font", font);
        UIManager.put("TabbedPane.font", font);
        UIManager.put("Table.font", font);
        UIManager.put("TableHeader.font", font);
        UIManager.put("TextArea.font", font);
        UIManager.put("TextField.font", font);
        UIManager.put("TextPane.font", font);
        UIManager.put("TitledBorder.font", font);
        UIManager.put("ToggleButton.font", font);
        UIManager.put("ToolBar.font", font);
        UIManager.put("ToolTip.font", font);
        UIManager.put("Tree.font", font);
        UIManager.put("Viewport.font", font);