1.按鈕(Jbutton)
Swing中的按鈕是Jbutton,它是javax.swing.AbstracButton類的子類,swing中的按鈕可以顯示圖像,並且可以將按鈕設置為窗口的默認圖標,而且還可以將多個圖像指定給一個按鈕。
在JButton中有如下幾個比較常用的構造方法。
- JButton(Icon icon): 按鈕上顯示圖標。
- JButton(String text): 按鈕上顯示字符。
- JButton(String text,Icon icon): 按鈕上既顯示圖標又先施字符。
JButton類的方法:
- setText(String text): 設置按鈕的標簽文本。
- setIcon(Icon defaultIcon): 設置按鈕在默認狀態下顯示的圖片。
- setRolloverIcon(Icon rolloverIcon): 設置當光標移動到按鈕上方時顯示的圖片。
- setPressedIcon(Icon pressedIcon): 設置當按鈕被按下時顯示的圖片。
- setContentAreaFilled(boolean b): 設置按鈕的背景為同名,當設為fase時表示不繪制,默認為繪制。
- setBorderPainted(boolean b): 設置為不繪制按鈕的邊框,當設為false時表示不繪制,默認為繪制。
按鈕組件是GUI中最常用的一種組件。按鈕組件可以捕捉到用戶的單擊事件,同時利用按鈕事件處理機制響應用戶的請求。JButton類是Swing提供的按鈕組件,在單擊JButton類對象創建的按鈕時,會產生一個ActionEvent事件。
代碼實例:
1 package jFrameDemo; 2 3 import java.applet.*; 4 import java.awt.*; 5 import java.awt.event.*; 6 7 @SuppressWarnings("all") 8 public class ButtonDemo extends Applet implements ActionListener { 9 String msg = ""; 10 Button yes,no,undecided; 11 12 public void init() { 13 yes = new Button("Yes"); 14 no = new Button("No"); 15 undecided = new Button("Undecided"); 16 17 add(yes); 18 add(no); 19 add(undecided); 20 21 yes.addActionListener(this); 22 no.addActionListener(this); 23 undecided.addActionListener(this); 24 } 25 26 public void actionPerformed(ActionEvent ee) { 27 String str = ee.getActionCommand(); 28 if (str.equals("Yes")) { 29 msg = "您選擇了Yes!"; 30 }else if (str.equals("No")) { 31 msg = "您選擇了No!"; 32 }else { 33 msg = "您選擇了Undecided!"; 34 } 35 repaint(); 36 } 37 38 public void paint(Graphics g){ 39 g.drawString(msg, 6, 100); 40 } 41 }
運行效果如下:
2.單選按鈕(JRadioButton)
JRadioButton組件實現的是一個單選按鈕。JRadioButton類可以單獨使用,也可以與ButtonGroup類聯合使用,當單獨使用時,該單選按鈕可以被選定和取消選定;當與ButtonGroup類聯合使用,需要使用add()方法將JRadioButton添加到ButtonGroup中,並組成一個單選按鈕組。此時用戶只能選定按鈕組中的一個單選按鈕。
JRadioButton組件的常用方法:
- setText(String text):設置單選按鈕的標簽文本。
- setSelected(boolean b):設置單選按鈕的狀態,默認情況下未被選中,當設為true時表示單選按鈕被選中。
- add(AbatractButton b):添加按鈕到按鈕組中。
- remove(AbatractButton b):從按鈕組中移除按鈕。
- getButtonCount():返回按鈕組中包含按鈕的個數,返回值為int型。
- getElements():返回一個Enumeration類型的對象,通過該對象可以遍歷按鈕組中包含的所有按鈕對象。
- isSelected():返回單選按鈕的狀態,當設為true時為選中。
- setSelected(boolean b):設定單選按鈕的狀態。
【例】實例功能是選擇用戶所喜歡的城市。
1 package com.sy.swing; 2 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class JRadioButtonTest extends JFrame { 8 9 /** 10 * Launch the application. 11 */ 12 public static void main(String[] args) { 13 EventQueue.invokeLater(new Runnable() { 14 public void run() { 15 try { 16 JRadioButtonTest frame = new JRadioButtonTest(); 17 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 18 frame.setBounds(100, 100, 450, 300); 19 frame.setTitle("單選框示例"); 20 frame.setVisible(true); 21 } catch (Exception e) { 22 e.printStackTrace(); 23 } 24 } 25 }); 26 } 27 28 /** 29 * Create the frame. 30 */ 31 public JRadioButtonTest() { 32 Container contentPane = getContentPane(); //創建一個內容面板容器 33 contentPane.setLayout(new FlowLayout()); //設置該窗口的布局 34 JPanel p1 = new JPanel(); //創建一個面板對象p1 35 p1.setLayout(new GridLayout(1, 3)); //設置布局管理器的格式 36 p1.setBorder(BorderFactory.createTitledBorder("選擇你喜歡的城市")); 37 //定義3個JRadioButton單選按鈕 38 JRadioButton r1 = new JRadioButton("北京"); 39 JRadioButton r2 = new JRadioButton("上海"); 40 JRadioButton r3 = new JRadioButton("青島"); 41 p1.add(r1); 42 p1.add(r2); 43 p1.add(r3); 44 r1.setSelected(true); //設置"北京"單選按鈕的狀態為被選中 45 contentPane.add(p1); // 面板對象p1加到窗口內容面板容器中 46 pack(); 47 addWindowListener(new WindowAdapter() { 48 public void windowClosing(WindowEvent e){ 49 System.exit(0); 50 } 51 }); 52 } 53 }
代碼運行結果如下
程序運行結果如圖所示。程序首先創建JFrame窗口對象,內容版面(contentPane),並設置窗口的布局格式為流布局FlowLayout();之后定義3個JRadioButton對象,並設置各自的現實文本同事添加到面板對象p1中;然后為窗口設置事件監聽。
3.復選框(JCheckBox)
使用復選框可以完成多項選擇。Swing中的復選框與awt中的復選框相比,優點是Swing復選框中可以添加圖片。復選框可以為每一次的單擊操作添加一個事件。
復選框的構造方法如下。
- JCheckBox(Icon icon):創建一個有圖標,但未被選中的復選框。
- JCheckBox(Icon icon,boolean selected):創建一個有圖標復選框,並且制定是否被選中。
- JCheckBox(String text):創建一個有文本,但未被選中的復選框。
- JCheckBox(String text,boolean selected):創建一個有文本復選框,並且制定是否被選中。
- JCheckBox(String text,Icon icon):創建一個指定文本和圖標,但未被選中的復選框。
- JCheckBox(String text,Icon icon,boolean selected):創建一個指定文本和圖標,並且制定是否被選中的復選框。
常用方法:
- public boolean isSelected():返回復選框狀態,true時為選中。
- public void setSelected(boolean b):設定復選框狀態。
代碼實例:
1 package jFrameDemo; 2 3 import java.applet.*; 4 import java.awt.*; 5 import java.awt.event.*; 6 7 @SuppressWarnings("all") 8 public class CheckboxDemo extends Applet implements ItemListener { 9 String msg = ""; 10 Checkbox windows,android,solaris,mac; 11 12 public void init() { 13 windows = new Checkbox("Windows",null,true); 14 android = new Checkbox("Android"); 15 solaris = new Checkbox("Solaris"); 16 mac = new Checkbox("Mac"); 17 18 add(windows); 19 add(android); 20 add(solaris); 21 add(mac); 22 23 windows.addItemListener(this); 24 android.addItemListener(this); 25 solaris.addItemListener(this); 26 mac.addItemListener(this); 27 } 28 29 public void itemStateChanged(ItemEvent ie){ 30 repaint(); 31 } 32 33 public void paint(Graphics g){ 34 msg = "Current state:"; 35 g.drawString(msg, 6, 80); 36 msg = "Windows: " + windows.getState(); 37 g.drawString(msg, 6, 100); 38 msg = "Android: " + android.getState(); 39 g.drawString(msg, 6, 120); 40 msg = "Solaris: " + solaris.getState(); 41 g.drawString(msg, 6, 140); 42 msg = "Mac OS: " + mac.getState(); 43 g.drawString(msg, 6, 160); 44 } 45 }
代碼運行展示如下:
4.組合框(JComboBox)
JComboBox組件用來創建組合框對象。通常,根據組合框是否可編輯的狀態,可以將組合框分成兩種常見的外觀。可編輯狀態外觀可視為文本框和下拉列表的組合,不可編輯狀態的外觀可視為按鈕和下拉列表的組合。在按鈕或文本框的右邊有一個帶三角符號的下拉按鈕,用戶可以單擊該下拉按鈕,便可出現一個內容列表,這也是組合框的得名。組合框通常用於從列表的”多個項目中選擇一個”的操作。
JComboBox的構造方法有如下幾種:
- JComboBox():創建一個默認模型的組合框。
- JComboBox(ComboBoxModel aModel):創建一個指定模型的組合框。
JComboBox(Object[] items):創建一個具有數組定義列表內容的組合框。
實例代碼如下
1 package JFrameTest; 2 3 import java.awt.BorderLayout; 4 5 @SuppressWarnings("all") 6 public class ComboBoxFrame extends JFrame { 7 8 private JComboBox faceCombo; 9 private JLabel label; 10 private static final int DEFAULT_SIZE = 24; 11 12 /** 13 * Launch the application. 14 */ 15 public static void main(String[] args) { 16 EventQueue.invokeLater(new Runnable() { 17 public void run() { 18 try { 19 ComboBoxFrame frame = new ComboBoxFrame(); 20 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 21 frame.setBounds(100, 100, 450, 300); 22 frame.setVisible(true); 23 } catch (Exception e) { 24 e.printStackTrace(); 25 } 26 } 27 }); 28 } 29 30 /** 31 * Create the frame. 32 */ 33 public ComboBoxFrame() { 34 label = new JLabel("The quick brown fox jumps over the lazy dog."); 35 label.setFont(new Font("Serif",Font.PLAIN,DEFAULT_SIZE)); 36 add(label,BorderLayout.CENTER); 37 38 faceCombo = new JComboBox(); 39 faceCombo.addItem("Serif"); 40 faceCombo.addItem("SnsSerif"); 41 faceCombo.addItem("Monospaced"); 42 faceCombo.addItem("Dialog"); 43 faceCombo.addItem("DialogInput"); 44 45 faceCombo.addActionListener(new ActionListener() { 46 47 @Override 48 public void actionPerformed(ActionEvent e) { 49 // TODO Auto-generated method stub 50 label.setFont(new Font((String) faceCombo.getItemAt(faceCombo.getSelectedIndex()),Font.PLAIN,DEFAULT_SIZE)); 51 } 52 }); 53 54 JPanel comboJPanel = new JPanel(); 55 comboJPanel.add(faceCombo); 56 add(comboJPanel,BorderLayout.SOUTH); 57 pack(); 58 } 59 60 }
代碼運行結果如圖
5.列表(JList)
JList組件用於定義列表,允許用戶選擇一個或多個項目。與JTextArea類似,JList本身不支持滾動功能,如果要顯示超出顯示范圍的項目,可以將JList對象放置到滾動窗格JScrollPane對象中,變可以為列表對象實現滾動操作。
JList的構造方法如下:
- JList():創建一個空模型的列表。
- JList(ListModel dataModel):創建一愕指定模型的列表。
- JList(Object[] listdatas):創建一個具有數組指定項目內容的列表。
常用方法如下:
- int getFirstVisibleIndex():獲取第一個可見單元的索引。
- void setFirstVisibleIndex(int):設置第一個可見單元的索引。
- int getLastVisibleIndex():獲取最后一個可見單元的索引。
- void setLastVisibleIndex(int):設置最后一個可見單元的索引。
- int getSelectedIndex():獲取第一個已選的索引。
- void setSelectedIndex(int):設置第一個已選的索引。
- Object getSelectedValue():獲取第一個已選的對象。
- void setSelectedValue(Object):設置第一個已選的對象。
- Object[] getSelectedValues():獲取已選的所有對象。
- Color getSelectionBackground():獲取選中項目的背景色。
- void setSelectionBackground():設置選中項目的背景色。
- Color getSelectionForeground():獲取選中項目的前景色。
- void setSelectionForeground():設置選中項目的前景色。
6.文本框(JTextField和JPasswordField)
JTextField組件用於創建文本框。文本框是用來接收用戶的單行文本信息輸入的區域。通常文本框用於接收用戶信息或其他文本信息的輸入。當用戶輸入文本信息后,如果為JTextField對象添加了事件處理,按回車鍵后就會觸發一定的操作。
JPasswordField是JTextField的子類,是一種特殊的文本框,也是用來接收單行文本信息輸入的區域,但是會用回顯字符串代替輸入的文本信息。因此,JPasswordField組件也稱為密碼文本框。JPasswordField默認的是回顯字符是”*”,用戶可以自行設置回顯字符。
JTextField的常見構造方法有如下幾種:
- JTextField():創建一個空文本框。
- JTextField(String text):創建一個具有出事文本信息text的文本框。
- JTextField(String text,int columns):創建一個具有出事文本信息text以及制定列數的文本框。
JTextField的常用方法:
- void setText(String):設置顯示內容。
- String getText():獲取顯示內容。
JPasswordField的構造方法有如下幾種:
- JPasswordField():創建一個空的密碼文本框。
- JPasswordField(String text):創建一個指定初始文本信息的密碼文本框。
- JPasswordField(String text,int columns):創建一個指定文本和列數的密碼文本框。
- JPasswordField(int columns):創建一個指定列數的密碼文本框。
JPasswordField是JTextField的子類,因此JPasswordField也具有與JTextField類似的名稱和功能的方法,此外,它還具有與JTextField類似的名稱和功能的方法,此外,它還具有自己的獨特方法:
- boolean echoCharIsSet():獲取設置回顯字符的狀態。
- void setEchoChar(char):設置回顯字符。
- void getEchoChar():獲取回顯字符。
- char[] getPassword():獲取組件的文本。
代碼實例如下
1 package dataExchange; 2 3 import java.awt.BorderLayout; 4 import java.awt.EventQueue; 5 import java.awt.event.ActionEvent; 6 import java.awt.event.ActionListener; 7 8 import javax.swing.JFrame; 9 import javax.swing.JMenu; 10 import javax.swing.JMenuBar; 11 import javax.swing.JMenuItem; 12 import javax.swing.JScrollPane; 13 import javax.swing.JTextArea; 14 15 @SuppressWarnings("all") 16 public class DataExchangeFrame extends JFrame { 17 18 public static final int TEXT_ROWS = 20; 19 public static final int TEXT_COLUMNS = 40; 20 private PasswordChooser dialog = null; 21 private JTextArea textArea; 22 23 /** 24 * Launch the application. 25 */ 26 public static void main(String[] args) { 27 EventQueue.invokeLater(new Runnable() { 28 public void run() { 29 try { 30 DataExchangeFrame frame = new DataExchangeFrame(); 31 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 32 frame.setBounds(100, 100, 450, 300); 33 frame.setVisible(true); 34 } catch (Exception e) { 35 e.printStackTrace(); 36 } 37 } 38 }); 39 } 40 41 /** 42 * Create the frame. 43 */ 44 public DataExchangeFrame() { 45 JMenuBar mbar = new JMenuBar(); 46 setJMenuBar(mbar); 47 JMenu fileMenu = new JMenu("File"); 48 mbar.add(fileMenu); 49 50 JMenuItem connectItem = new JMenuItem("Connect"); 51 connectItem.addActionListener(new ConnectAction()); 52 fileMenu.add(connectItem); 53 54 JMenuItem exitItem = new JMenuItem("Exit"); 55 exitItem.addActionListener(new ActionListener() { 56 public void actionPerformed(ActionEvent e) { 57 System.exit(0); 58 } 59 }); 60 61 fileMenu.add(exitItem); 62 63 textArea = new JTextArea(TEXT_ROWS,TEXT_COLUMNS); 64 add(new JScrollPane(textArea),BorderLayout.CENTER); 65 pack(); 66 } 67 68 public class ConnectAction implements ActionListener{ 69 public void actionPerformed(ActionEvent e) { 70 if (dialog == null) { 71 dialog = new PasswordChooser(); 72 } 73 74 dialog.setUser(new User("yourname", null)); 75 76 if (dialog.showDialog(DataExchangeFrame.this, "Connect")) { 77 User user = dialog.getUser(); 78 textArea.append("Username = " + user.getName() + ",password = " + (new String(user.getPassword())) + "\n"); 79 } 80 } 81 } 82 83 }
運行如下
點擊file,選擇connect,效果如下:
上面運行代碼如下:
1 package dataExchange; 2 3 import java.awt.BorderLayout; 4 5 @SuppressWarnings("serial") 6 public class PasswordChooser extends JPanel { 7 8 private JTextField username; 9 private JPasswordField password; 10 private JButton okButton; 11 private boolean ok; 12 private JDialog dialog; 13 14 /** 15 * Create the panel. 16 */ 17 public PasswordChooser() { 18 setLayout(new BorderLayout()); 19 JPanel panel = new JPanel(); 20 panel.setLayout(new GridLayout(2, 2)); 21 panel.add(new JLabel("Username:")); 22 panel.add(username = new JTextField()); 23 panel.add(new JLabel("Password:")); 24 panel.add(password = new JPasswordField()); 25 add(panel,BorderLayout.CENTER); 26 27 okButton = new JButton("Ok"); 28 okButton.addActionListener(new ActionListener() { 29 public void actionPerformed(ActionEvent e) { 30 ok = true; 31 dialog.setVisible(true); 32 } 33 }); 34 35 JButton cancelButton = new JButton("Cancel"); 36 cancelButton.addActionListener(new ActionListener() { 37 public void actionPerformed(ActionEvent e) { 38 dialog.setVisible(false); 39 } 40 }); 41 42 JPanel buttonPanel = new JPanel(); 43 buttonPanel.add(okButton); 44 buttonPanel.add(cancelButton); 45 add(buttonPanel,BorderLayout.SOUTH); 46 } 47 48 public void setUser(User u){ 49 username.setText(u.getName()); 50 } 51 52 public User getUser(){ 53 return new User(username.getText(),password.getPassword()); 54 } 55 56 public boolean showDialog(Component parent,String title){ 57 ok = false; 58 Frame owner = null; 59 if (parent instanceof Frame) { 60 owner = (Frame)parent; 61 }else { 62 owner = (Frame)SwingUtilities.getAncestorOfClass(Frame.class, parent); 63 } 64 65 if (dialog == null || dialog.getOwner() != owner) { 66 dialog = new JDialog(owner,true); 67 dialog.add(this); 68 dialog.getRootPane().setDefaultButton(okButton); 69 dialog.pack(); 70 } 71 72 dialog.setTitle(title); 73 dialog.setVisible(true); 74 return ok; 75 } 76 77 }
7.面板(JPanel)
JPanel組件定義面板實際上是一種容器組件,用來容納各種其他輕量級組件。此外,用戶還可以用這種面板容器繪制圖形。
JPanel的構造方法如下:
- JPanel():創建具有雙緩沖和流布局(FlowLayout)的面板。
- JPanel(LayoutManager layout):創建具有制定布局管理器的面板。
JPanel的 常用方法:
- void add(Component):添加組件。
- void add(Component,int):添加組件至索引指定位置。
- void add(Component,Object):按照指定布局限制添加組件。
- void add(Component,Object,int):按照指定布局管理器限制添加組件到指定位置。
- void remove(Component):移除組件。
- void remove(int):移除指定位置的組件。
- void removeAll():移除所有組件。
- void paintComponent(Graphics):繪制組件。
- void repaint():重新繪制。
- void setPreferredSize(Dimension):設置組件尺寸。
- Dimension getPreferredSize():獲取最佳尺寸。
代碼實例如下:
1 package com.sy.swing; 2 3 import java.awt.BorderLayout; 4 import java.awt.Color; 5 import java.awt.Container; 6 import java.awt.Dimension; 7 import java.awt.FlowLayout; 8 import java.awt.Graphics; 9 10 import javax.swing.JButton; 11 import javax.swing.JFrame; 12 import javax.swing.JPanel; 13 14 public class JPanelExample extends JFrame { 15 JButton[] buttons; 16 JPanel panel1; 17 CustomPanel panel2; 18 19 public JPanelExample(){ 20 super("面板實例"); 21 Container container = getContentPane(); 22 container.setLayout(new BorderLayout()); 23 panel1 = new JPanel(new FlowLayout()); //創建一個流布局管理器的面板 24 buttons = new JButton[4]; 25 for (int i = 0; i < buttons.length; i++) { 26 buttons[i]=new JButton("按鈕"+(i+1)); 27 panel1.add(buttons[i]); //添加按鈕到面板panel1中 28 } 29 panel2 = new CustomPanel(); 30 container.add(panel1,BorderLayout.NORTH); 31 container.add(panel2,BorderLayout.CENTER); 32 pack(); 33 setVisible(true); 34 } 35 36 public static void main(String[] args) { 37 JPanelExample jpe = new JPanelExample(); 38 jpe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 39 } 40 41 class CustomPanel extends JPanel{ //定義內部類CustomPanel 42 @Override 43 protected void paintComponent(Graphics g) { 44 super.paintComponent(g); 45 g.drawString("Welcome to Java Shape World", 20, 20); 46 g.drawRect(20, 40, 130, 130); 47 g.setColor(Color.GREEN); //設置顏色為綠色 48 g.fillRect(20, 40, 130, 130); //繪制矩形 49 g.drawOval(160, 40, 100, 100); //繪制橢圓 50 g.setColor(Color.ORANGE); //設置顏色為橙色 51 g.fillOval(160, 40, 100, 100); //繪制橢圓 52 } 53 @Override 54 public Dimension getPreferredSize() { 55 // TODO Auto-generated method stub 56 return new Dimension(200,200); 57 } 58 } 59 60 }
運行結果如下:
8.表格(JTable)
表格是Swing新增加的組件,主要功能是把數據以二維表格的形式顯示出來。使用表格,一句M-V-C思想,最好先生成一個MyTableModel類型的對象來表示數據,這個類是從AbstractTableModel累中集成來的,其中有幾個方法移動要重寫,例如geColumnCount、getRowCount、getColumnName和getValueAt。因為JTable會從這個對象中自動獲取表格顯示必須的數據,AbstractTableModel類的對象負責表格大小的確定(行、列)、內容的填寫、賦值、表格單元更新的檢測等一切與表哥內容有關的屬性及其操作。JTable類生成的對象以該TableModel為參數,並負責將TableModel對象中的數據以表格的形式顯示出來。

1 package JFrameTest; 2 3 /* 4 * TableRenderDemo.java requires no other files. 5 */ 6 7 import javax.swing.DefaultCellEditor; 8 import javax.swing.JComboBox; 9 import javax.swing.JFrame; 10 import javax.swing.JPanel; 11 import javax.swing.JScrollPane; 12 import javax.swing.JTable; 13 import javax.swing.table.AbstractTableModel; 14 import javax.swing.table.DefaultTableCellRenderer; 15 import javax.swing.table.TableCellRenderer; 16 import javax.swing.table.TableColumn; 17 18 import java.awt.Component; 19 import java.awt.Dimension; 20 import java.awt.GridLayout; 21 22 /** 23 * TableRenderDemo is just like TableDemo, except that it 24 * explicitly initializes column sizes and it uses a combo box 25 * as an editor for the Sport column. 26 */ 27 @SuppressWarnings("all") 28 public class TableRenderDemo extends JPanel { 29 private boolean DEBUG = false; 30 31 public TableRenderDemo() { 32 super(new GridLayout(1,0)); 33 34 JTable table = new JTable(new MyTableModel()); 35 table.setPreferredScrollableViewportSize(new Dimension(500, 70)); 36 table.setFillsViewportHeight(true); 37 38 //Create the scroll pane and add the table to it. 39 JScrollPane scrollPane = new JScrollPane(table); 40 41 //Set up column sizes. 42 initColumnSizes(table); 43 44 //Fiddle with the Sport column's cell editors/renderers. 45 setUpSportColumn(table, table.getColumnModel().getColumn(2)); 46 47 //Add the scroll pane to this panel. 48 add(scrollPane); 49 } 50 51 /* 52 * This method picks good column sizes. 53 * If all column heads are wider than the column's cells' 54 * contents, then you can just use column.sizeWidthToFit(). 55 */ 56 private void initColumnSizes(JTable table) { 57 MyTableModel model = (MyTableModel)table.getModel(); 58 TableColumn column = null; 59 Component comp = null; 60 int headerWidth = 0; 61 int cellWidth = 0; 62 Object[] longValues = model.longValues; 63 TableCellRenderer headerRenderer = 64 table.getTableHeader().getDefaultRenderer(); 65 66 for (int i = 0; i < 5; i++) { 67 column = table.getColumnModel().getColumn(i); 68 69 comp = headerRenderer.getTableCellRendererComponent( 70 null, column.getHeaderValue(), 71 false, false, 0, 0); 72 headerWidth = comp.getPreferredSize().width; 73 74 comp = table.getDefaultRenderer(model.getColumnClass(i)). 75 getTableCellRendererComponent( 76 table, longValues[i], 77 false, false, 0, i); 78 cellWidth = comp.getPreferredSize().width; 79 80 if (DEBUG) { 81 System.out.println("Initializing width of column " 82 + i + ". " 83 + "headerWidth = " + headerWidth 84 + "; cellWidth = " + cellWidth); 85 } 86 87 column.setPreferredWidth(Math.max(headerWidth, cellWidth)); 88 } 89 } 90 91 public void setUpSportColumn(JTable table, 92 TableColumn sportColumn) { 93 //Set up the editor for the sport cells. 94 JComboBox comboBox = new JComboBox(); 95 comboBox.addItem("Snowboarding"); 96 comboBox.addItem("Rowing"); 97 comboBox.addItem("Knitting"); 98 comboBox.addItem("Speed reading"); 99 comboBox.addItem("Pool"); 100 comboBox.addItem("None of the above"); 101 sportColumn.setCellEditor(new DefaultCellEditor(comboBox)); 102 103 //Set up tool tips for the sport cells. 104 DefaultTableCellRenderer renderer = 105 new DefaultTableCellRenderer(); 106 renderer.setToolTipText("Click for combo box"); 107 sportColumn.setCellRenderer(renderer); 108 } 109 110 class MyTableModel extends AbstractTableModel { 111 private String[] columnNames = {"First Name", 112 "Last Name", 113 "Sport", 114 "# of Years", 115 "Vegetarian"}; 116 private Object[][] data = { 117 {"Kathy", "Smith", 118 "Snowboarding", new Integer(5), new Boolean(false)}, 119 {"John", "Doe", 120 "Rowing", new Integer(3), new Boolean(true)}, 121 {"Sue", "Black", 122 "Knitting", new Integer(2), new Boolean(false)}, 123 {"Jane", "White", 124 "Speed reading", new Integer(20), new Boolean(true)}, 125 {"Joe", "Brown", 126 "Pool", new Integer(10), new Boolean(false)} 127 }; 128 129 public final Object[] longValues = {"Jane", "Kathy", 130 "None of the above", 131 new Integer(20), Boolean.TRUE}; 132 133 public int getColumnCount() { 134 return columnNames.length; 135 } 136 137 public int getRowCount() { 138 return data.length; 139 } 140 141 public String getColumnName(int col) { 142 return columnNames[col]; 143 } 144 145 public Object getValueAt(int row, int col) { 146 return data[row][col]; 147 } 148 149 /* 150 * JTable uses this method to determine the default renderer/ 151 * editor for each cell. If we didn't implement this method, 152 * then the last column would contain text ("true"/"false"), 153 * rather than a check box. 154 */ 155 public Class getColumnClass(int c) { 156 return getValueAt(0, c).getClass(); 157 } 158 159 /* 160 * Don't need to implement this method unless your table's 161 * editable. 162 */ 163 public boolean isCellEditable(int row, int col) { 164 //Note that the data/cell address is constant, 165 //no matter where the cell appears onscreen. 166 if (col < 2) { 167 return false; 168 } else { 169 return true; 170 } 171 } 172 173 /* 174 * Don't need to implement this method unless your table's 175 * data can change. 176 */ 177 public void setValueAt(Object value, int row, int col) { 178 if (DEBUG) { 179 System.out.println("Setting value at " + row + "," + col 180 + " to " + value 181 + " (an instance of " 182 + value.getClass() + ")"); 183 } 184 185 data[row][col] = value; 186 fireTableCellUpdated(row, col); 187 188 if (DEBUG) { 189 System.out.println("New value of data:"); 190 printDebugData(); 191 } 192 } 193 194 private void printDebugData() { 195 int numRows = getRowCount(); 196 int numCols = getColumnCount(); 197 198 for (int i=0; i < numRows; i++) { 199 System.out.print(" row " + i + ":"); 200 for (int j=0; j < numCols; j++) { 201 System.out.print(" " + data[i][j]); 202 } 203 System.out.println(); 204 } 205 System.out.println("--------------------------"); 206 } 207 } 208 209 /** 210 * Create the GUI and show it. For thread safety, 211 * this method should be invoked from the 212 * event-dispatching thread. 213 */ 214 private static void createAndShowGUI() { 215 //Create and set up the window. 216 JFrame frame = new JFrame("TableRenderDemo"); 217 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 218 219 //Create and set up the content pane. 220 TableRenderDemo newContentPane = new TableRenderDemo(); 221 newContentPane.setOpaque(true); //content panes must be opaque 222 frame.setContentPane(newContentPane); 223 224 //Display the window. 225 frame.pack(); 226 frame.setVisible(true); 227 } 228 229 public static void main(String[] args) { 230 //Schedule a job for the event-dispatching thread: 231 //creating and showing this application's GUI. 232 javax.swing.SwingUtilities.invokeLater(new Runnable() { 233 public void run() { 234 createAndShowGUI(); 235 } 236 }); 237 } 238 }
代碼運行結果如下:
參考:http://www.cnblogs.com/pzy4447/p/4925125.html
9.框架(JFrame)
框架SwingGUI應用程序的主窗口,窗口包括邊界、標題、關閉按鈕等。
JFrame類是java.awt包中Frame類的子類,其子類創建的對象是窗體,對象(窗體)是重量容器。不能把組件直接添加到Swing窗體中,其含有內容面板容器,應該把組件添加到內容面板中;不能為Swing窗體設置布局,而應當Swing窗體的內容面板設置布局。
Swing窗體通過getContentPane()方法獲得JFrame的內容面板,再對其加入組件;
JFrame frame = new JFrame();
Container ct = frame.getContentPane(); //獲取內容面板容器
Ct.add(childComponent); //降內容面板容器加入組件
框架(JFrame)常用的方法和事件:
- frame.setVisibel(true):顯示框架對象代表的框架窗口。
- frame.setSize(200,100)或frame.pack():設置框架的初始顯示大小。
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE):當用戶單機框架的關閉按鈕則退出程序,或者添加WindowListener監聽器實現關閉按鈕退出程序。
代碼實例:
1 package jFrameDemo; 2 3 import java.awt.EventQueue; 4 5 import javax.swing.JFrame; 6 7 public class SimpleFrameTest { 8 public static void main(String[] args) { 9 /*所有的Swing組件必須由事件分派線程(event dispatch thread)進行配置, 10 *線程將鼠標點擊和按鈕控制轉移到用戶接口組件。下面的代碼片段是事件分派線程中的執行代碼。 11 *現在,只需要將其看成是啟動一個Swing程序的神器代碼。 12 */ 13 EventQueue.invokeLater(new Runnable(){ 14 @Override 15 public void run() { 16 // TODO Auto-generated method stub 17 SimpleFrame frame = new SimpleFrame(); 18 frame.setTitle("JFrame測試"); 19 //定義一個用戶關閉這個框架時的響應動作。 20 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 21 //為了框架顯示,main方法需要需要調用框架的setVisible方法 22 frame.setVisible(true); 23 } 24 }); 25 } 26 } 27 28 @SuppressWarnings("all") 29 class SimpleFrame extends JFrame{ 30 private static final int DEFAULT_WIDTH = 400; 31 private static final int DEFAULT_HEIGHT = 200; 32 33 public SimpleFrame(){ 34 setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT); 35 } 36 }
代碼實例運行結果如下:
文章內容參考:《Java游戲編程原理與實踐教程》