Java 程式設計 -- 視窗

Java 程式

簡介

運算式

分枝

迴圈

陣列

函數

遞迴

錯誤處理

物件導向

封裝

繼承

多型

技巧

函式庫

字串

數學

正規表達式

容器

檔案

網路

資料庫

視窗

Thread

Listener

錯誤陷阱

相關檔案

相關資源

教學錄影

Eclipse

考題解答

訊息

相關網站

參考文獻

最新修改

簡體版

English

範例:開一個視窗

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
class Frame1
{
    public static void main( String args[] )
    {
        JFrame frame = new JFrame();
        frame.setSize(600, 480);
        frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
        frame.setVisible( true );
    }
}

範例:開一個視窗 (使用繼承法)

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
class Swing1 extends JFrame
{
    // Main entry point for this example
    public static void main( String args[] )
    {
        // Create an instance of the test application
        Swing1 frame = new Swing1();
        frame.setVisible( true );
    }
 
    Swing1() {
        setSize(600, 480);
        setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
    }
 
}

範例:功能表

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
class Menu1 extends JFrame
{
    // Main entry point for this example
    public static void main( String args[] )
    {
        // Create an instance of the test application
        Menu1 frame = new Menu1();
        frame.setVisible( true );
    }
 
    Menu1() {
        // set the property of frame
        setSize(600, 480);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
 
        // set the menubar
        JMenuBar bar = new JMenuBar();
        setJMenuBar(bar);
 
        // set a menu.
        JMenu menuFile = new JMenu("檔案");
        bar.add(menuFile);
 
        // add sub menus.
        menuFile.add(new JMenuItem("檔案開啟"));
        menuFile.add(new JMenuItem("檔案關閉"));
    }
}

範例:浮現式功能表

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
class Popup1 extends JFrame
{
    public static void main( String args[] )
    {
        Popup1 frame = new Popup1();
        frame.setVisible( true );
    }
 
    Popup1() {
        setSize(600, 480);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
 
        Popup popup = new Popup();
        popup.add(new JMenuItem("剪下"));
        popup.addSeparator();
        popup.add(new JMenuItem("貼上"));
        addMouseListener(popup);
    }
}
 
class Popup extends JPopupMenu implements MouseListener {
    public void mouseClicked(MouseEvent evt) {}
    public void mouseEntered(MouseEvent evt) {}
    public void mouseExited(MouseEvent evt) {}
    public void mousePressed(MouseEvent evt) {
        if (evt.isPopupTrigger())
            show(evt.getComponent(), evt.getX(), evt.getY());
    }
    public void mouseReleased(MouseEvent evt) {
        if (evt.isPopupTrigger())
            show(evt.getComponent(), evt.getX(), evt.getY());
    }
}

顯示表格

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
class SimpleTableExample extends JFrame
 {
    private    JPanel        topPanel;
    private    JTable        table;
    private    JScrollPane scrollPane;
 
    public SimpleTableExample()
    {
        setTitle( "Simple Table Application" );
        setSize( 300, 200 );
        setBackground( Color.gray );
 
        topPanel = new JPanel();
        topPanel.setLayout( new BorderLayout() );
        getContentPane().add( topPanel );
 
        String columnNames[] = { "Column 1", "Column 2", "Column 3" };
 
        String dataValues[][] =
        {
            { "12", "234", "67" },
            { "-123", "43", "853" },
            { "93", "89.2", "109" },
            { "279", "9033", "3092" }
        };
 
        table = new JTable( dataValues, columnNames );
 
        scrollPane = new JScrollPane( table );
        topPanel.add( scrollPane, BorderLayout.CENTER );
    }
 
    public static void main( String args[] )
    {
        SimpleTableExample mainFrame    = new SimpleTableExample();
        mainFrame.setVisible( true );
    }
}

範例:表格按下的處理

import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.JScrollPane;
import javax.swing.JPanel;
import javax.swing.JFrame;
import java.awt.*;
import java.awt.event.*;
 
public class SimpleTableSelectionDemo extends JFrame {
    private boolean DEBUG = false;
    private boolean ALLOW_COLUMN_SELECTION = false;
    private boolean ALLOW_ROW_SELECTION = true;
 
    public SimpleTableSelectionDemo() {
        super("SimpleTableSelectionDemo");
 
        Object[][] data = {
            {"Mary", "Campione", 
             "Snowboarding", new Integer(5), new Boolean(false)},
            {"Alison", "Huml", 
             "Rowing", new Integer(3), new Boolean(true)},
            {"Kathy", "Walrath",
             "Chasing toddlers", new Integer(2), new Boolean(false)},
            {"Mark", "Andrews",
             "Speed reading", new Integer(20), new Boolean(true)},
            {"Angela", "Lih",
             "Teaching high school", new Integer(4), new Boolean(false)}
        };
 
        String[] columnNames = {"First Name", 
                                "Last Name",
                                "Sport",
                                "# of Years",
                                "Vegetarian"};
 
        final JTable table = new JTable(data, columnNames);
        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
 
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        if (ALLOW_ROW_SELECTION) { // true by default
            ListSelectionModel rowSM = table.getSelectionModel();
            rowSM.addListSelectionListener(new ListSelectionListener() {
                public void valueChanged(ListSelectionEvent e) {
                    ListSelectionModel lsm = (ListSelectionModel)e.getSource();
                    if (lsm.isSelectionEmpty()) {
                        System.out.println("No rows are selected.");
                    } else {
                        int selectedRow = lsm.getMinSelectionIndex();
                        System.out.println("Row " + selectedRow
                                           + " is now selected.");
                    }
                }
            });
        } else {
            table.setRowSelectionAllowed(false);
        }
 
        if (ALLOW_COLUMN_SELECTION) { // false by default
            if (ALLOW_ROW_SELECTION) {
                //We allow both row and column selection, which
                //implies that we *really* want to allow individual
                //cell selection.
                table.setCellSelectionEnabled(true);
            } 
            table.setColumnSelectionAllowed(true);
            ListSelectionModel colSM =
                table.getColumnModel().getSelectionModel();
            colSM.addListSelectionListener(new ListSelectionListener() {
                public void valueChanged(ListSelectionEvent e) {
                    ListSelectionModel lsm = (ListSelectionModel)e.getSource();
                    if (lsm.isSelectionEmpty()) {
                        System.out.println("No columns are selected.");
                    } else {
                        int selectedCol = lsm.getMinSelectionIndex();
                        System.out.println("Column " + selectedCol
                                           + " is now selected.");
                    }
                }
            });
        }
 
        if (DEBUG) {
            table.addMouseListener(new MouseAdapter() {
                public void mouseClicked(MouseEvent e) {
                    printDebugData(table);
                }
            });
        }
 
        //Create the scroll pane and add the table to it. 
        JScrollPane scrollPane = new JScrollPane(table);
 
        //Add the scroll pane to this window.
        getContentPane().add(scrollPane, BorderLayout.CENTER);
 
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }
 
    private void printDebugData(JTable table) {
        int numRows = table.getRowCount();
        int numCols = table.getColumnCount();
        javax.swing.table.TableModel model = table.getModel();
 
        System.out.println("Value of data: ");
        for (int i=0; i < numRows; i++) {
            System.out.print("    row " + i + ":");
            for (int j=0; j < numCols; j++) {
                System.out.print("  " + model.getValueAt(i, j));
            }
            System.out.println();
        }
        System.out.println("--------------------------");
    }
 
    public static void main(String[] args) {
        SimpleTableSelectionDemo frame = new SimpleTableSelectionDemo();
        frame.pack();
        frame.setVisible(true);
    }
}

範例:樹狀結構

import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;
 
public class SimpleTree extends JFrame {
  public static void main(String[] args) {
    new SimpleTree();
  }
 
  public SimpleTree() {
    super("Creating a Simple JTree");
    Container content = getContentPane();
    Object[] hierarchy =
      { "javax.swing",
        "javax.swing.border",
        "javax.swing.colorchooser",
        "javax.swing.event",
        "javax.swing.filechooser",
        new Object[] { "javax.swing.plaf",
                       "javax.swing.plaf.basic",
                       "javax.swing.plaf.metal",
                       "javax.swing.plaf.multi" },
        "javax.swing.table",
        new Object[] { "javax.swing.text",
                       new Object[] { "javax.swing.text.html",
                                      "javax.swing.text.html.parser" },
                       "javax.swing.text.rtf" },
        "javax.swing.tree",
        "javax.swing.undo" };
    DefaultMutableTreeNode root = processHierarchy(hierarchy);
    JTree tree = new JTree(root);
    content.add(new JScrollPane(tree), BorderLayout.CENTER);
    setSize(275, 300);
    setVisible(true);
  }
 
  /** Small routine that will make node out of the first entry
   *  in the array, then make nodes out of subsequent entries
   *  and make them child nodes of the first one. The process is
   *  repeated recursively for entries that are arrays.
   */
 
  private DefaultMutableTreeNode processHierarchy(Object[] hierarchy) {
    DefaultMutableTreeNode node =
      new DefaultMutableTreeNode(hierarchy[0]);
    DefaultMutableTreeNode child;
    for(int i=1; i<hierarchy.length; i++) {
      Object nodeSpecifier = hierarchy[i];
      if (nodeSpecifier instanceof Object[])  // Ie node with children
        child = processHierarchy((Object[])nodeSpecifier);
      else
        child = new DefaultMutableTreeNode(nodeSpecifier); // Ie Leaf
      node.add(child);
    }
    return(node);
  }
}

Facebook

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License