Java編程技術(shù)課件:08Swing UI編程(6學(xué)時)_第1頁
Java編程技術(shù)課件:08Swing UI編程(6學(xué)時)_第2頁
Java編程技術(shù)課件:08Swing UI編程(6學(xué)時)_第3頁
Java編程技術(shù)課件:08Swing UI編程(6學(xué)時)_第4頁
Java編程技術(shù)課件:08Swing UI編程(6學(xué)時)_第5頁
已閱讀5頁,還剩64頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)

文檔簡介

8SwingUI編程8.1JFrame框架8.2布局管理器8.3常用組件8.1JFrame框架JFrame是一個頂層容器,主要用來設(shè)計應(yīng)用程序的圖形用戶界面。JFrame支持多線程。JFrame框架引例packagetestSwing;importjava.awt.*;importjavax.swing.*;publicclasshello

extendsJFrame{publichello(){//構(gòu)造函數(shù) this.add(newJButton("確定"),BorderLayout.WEST); this.add(newJButton("取消"),BorderLayout.EAST);}publicstaticvoidmain(String[]args){

helloh=newhello();

h.setTitle("hello"); h.setSize(300,400); h.setVisible(true); h.add(newJButton("OK"),BorderLayout.SOUTH);}}hello.java繼承JFrame實例化hello并設(shè)置相關(guān)屬性也可以自己動態(tài)添加所需控件窗口中的控件布局MatisseForm創(chuàng)建過程N(yùn)ew→Other→MyEclispe→Swing→MatisseForm選擇JFrame。publicclasshelloJFrame

extendsjavax.swing.JFrame{

publichelloJFrame(){initComponents();}

privatevoidinitComponents(){setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);javax.swing.GroupLayoutlayout=newjavax.swing.GroupLayout(getContentPane());getContentPane().setLayout(layout);layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0,400,Short.MAX_VALUE));layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0,300,Short.MAX_VALUE));pack();}publicstaticvoidmain(Stringargs[]){java.awt.EventQueue.invokeLater(newRunnable(){publicvoidrun(){newhelloJFrame().setVisible(true);}});}}構(gòu)造函數(shù)javax.swing.GroupLayoutlayout=newjavax.swing.GroupLayout(getContentPane());

getContentPane().setLayout(layout);layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0,400,Short.MAX_VALUE));layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0,300,Short.MAX_VALUE));pack();布局管理啟動多線程顯示窗口繼承JFramehelloJFrame.java屬性方法功能構(gòu)造函數(shù):JFrame()創(chuàng)建一個沒有標(biāo)題的框架構(gòu)造函數(shù):JFrame(Stringtitle)創(chuàng)建一個有標(biāo)題的框架titlesetTitle()設(shè)置窗口標(biāo)題defaultCloseOperationsetDefaultCloseOperation(intoption)設(shè)置窗口關(guān)閉時執(zhí)行的操作,取值:EXIT_ON_CLOSE(結(jié)束程序)默認(rèn)DISPOSE_ON_CLOSE(回收窗口)HIDE_ON_CLOSE(隱藏窗口)DO_NOTHING_ON_CLOSE(無作為)alwaysOnTopsetAlwaysOnTop(true)設(shè)置窗口顯示是總是最前端backgroundsetBackground(newColor(255,0,0));或者直接setBackground(Color.Red);設(shè)置窗口背景色cursorsetCursor(new

Cursor(Cursor.HAND_CURSOR));設(shè)置光標(biāo)JFrame常用屬性和方法注意:設(shè)置JFrame的背景顏色,仍然會被內(nèi)容面板蓋住,不如設(shè)置內(nèi)容面板的背景顏色:getContentPane().setBackground(Color.RED);屬性方法功能resizablesetResizable(boolean)設(shè)置窗口是否可以調(diào)整大小,默認(rèn)可調(diào)注:

為false時窗口最大化不能用setVisible(boolean)顯示(true)和(false)隱藏窗口(不推薦使用show()/hide()方法)setSize(intwidth,intheight)設(shè)置窗口大小,窗口的默認(rèn)位置(0,0)。setBounds(intx,inty,intwidth,intheight)設(shè)置出現(xiàn)在屏幕上的位置,前兩個參數(shù)(x,y)坐標(biāo),后兩個參數(shù)是寬度和高度pack()按照組件的大小自動適配容器大小getContentPane()獲得窗口的內(nèi)容面板JFrame常用屬性和方法(續(xù))單獨(dú)使用setSize()時,是按照設(shè)置的大小顯示的;此時不能使用pack(),否則自動適配內(nèi)容面板:JFrame一旦創(chuàng)建,在其中就已經(jīng)包含一個內(nèi)容面板,一般往JFrame中添加組件時,都加在內(nèi)容面板中補(bǔ)充:JFrame屏幕居中/全屏代碼importjava.awt.Dimension;importjava.awt.Toolkit;DimensionscreenSize=Toolkit.getDefaultToolkit().getScreenSize();t.setSize(400,400);//t為JFrame對象DimensionframeSize=t.getSize();t.setLocation((screenSize.width-frameSize.width)/2,(screenSize.height-frameSize.height)/2);t.setVisible(true);

全屏顯示:t.setBounds(0,0,screenSize.width,screenSize.height);補(bǔ)充:JFrame無邊框代碼setUndecorated(true);注意:setUndecroated方法必須在setVisible之前被執(zhí)行,一定要確保Frame窗口是新創(chuàng)建并且沒有做過任何顯示,甚至是pack動作也不能做過,否則會得到一個異常。多窗口示例新建一個JFrame(命名為JFrame1.java),設(shè)置相關(guān)屬性,如:title:多窗口測試;resizable:false;窗口大小等再新建一個JFrame(命名為JFrame2.java),設(shè)置相關(guān)屬性,如:title:第二個窗口;resizable:false;調(diào)整一下窗口大小等defaultCloseOperation:DISPOSE_ON_CLOSE(很重要)在第一個JFrame中添加一個JButton,右擊按鈕添,加一個單擊事件(Events→Action→actionPerformed方法)和代碼:JFrame2newJFrame

=newJFrame2();newJFrame.setVisible(true);【Return】也可改為在JFrame1.java中添加一個成員:privateJFrame2newJFrame=newJFrame2();8.2布局管理器容器中可以容納組件,在往容器中添加多個組件時,要考慮這些組件在容器中的布局。由于Java是跨平臺語言,使用絕對坐標(biāo)會導(dǎo)致問題:即在不同平臺、不同分辨率下的顯示效果不一樣。為了實現(xiàn)跨平臺的特性并且獲得動態(tài)的布局效果,Java將容器內(nèi)的所有組件安排給一個“布局管理器”負(fù)責(zé)管理。Java提供的布局管理器類BorderLayoutFlowLayoutGridLayoutCardLayoutBoxLayoutGridBagLayoutGroupLayout(MatisseForm默認(rèn))【Return】BorderLayout布局BorderLayout把容器空間劃分為東、西、南、北、中5個區(qū)域。BorderLayout.EASTBorderLayout.WESTBorderLayout.SOUTHBorderLayout.NORTHBorderLayout.CENTERBorderLayout是頂層容器(JFrame/Jdialog/JApplet)

默認(rèn)的布局管理器。BorderLayout布局用法示例BorderLayout構(gòu)造函數(shù):BorderLayout():創(chuàng)建一個組件之間沒有水平和垂直間距的BorderLayout布局。BorderLayout(inthgap,intvgap):通過參數(shù)hgap和vgap分別設(shè)定組件的水平和垂直間距。JFrame使用setLayout(newBorderLayout())方法來創(chuàng)建布局管理器。當(dāng)需要在使用BorderLayout布局的容器中添加組件時,可用add方法,例如:

add(組件,BorderLayout.EAST);//將組件放在東邊testBorderLayout.javapackagetestSwing;importjava.awt.BorderLayout;importjavax.swing.*;publicclasstestBorderLayout

extendsJFrame{publictestBorderLayout(){

//默認(rèn)為BorderLayout布局this.add(newJButton("東"),BorderLayout.EAST);this.add(newJButton("西"),BorderLayout.WEST);this.add(newJButton("南"),BorderLayout.SOUTH);this.add(newJButton("北"),BorderLayout.NORTH);this.add(newJButton("中"),BorderLayout.CENTER);}publicstaticvoidmain(String[]args){

testBorderLayoutframe=newtestBorderLayout();frame.setTitle("testBorderLayout");//設(shè)置標(biāo)題frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//設(shè)置窗口關(guān)閉操作//frame.setSize(300,400);//設(shè)置窗口的寬和高frame.setBounds(100,100,300,400);//設(shè)置窗口初始位置和寬高frame.setVisible(true);//顯示窗口}}手工寫的class不使用MatisseForm創(chuàng)建往容器中添加組件并配置布局【Return】FlowLayout布局FlowLayout布局管理器把容器看成一個行集,好象平時在一張紙上寫字一樣,一行寫滿就換下一行。默認(rèn)情況下組件按添加的先后順序從左至右擺放,如果一行排滿,則在下一行中繼續(xù)。默認(rèn)情況下,容器中的每一行組件都居中對齊。FlowLayout布局示例FlowLayout構(gòu)造函數(shù):FlowLayout():創(chuàng)建一個默認(rèn)FlowLayout布局。FlowLayout(intalign):align對齊方式:

FlowLayout.LEFT/FlowLayout.CENTER/FlowLayout.RIGHT。FlowLayout(intalign,inthgap,intvgap):align對齊方式,hagap和vgap指定組件水平和垂直間距。testFlowLayout.javapackagetestSwing;importjava.awt.FlowLayout;importjavax.swing.*;publicclasstestFlowLayout

extendsJFrame{publictestFlowLayout(){this.setLayout(newFlowLayout());for(inti=0;i<10;i++){this.add(newJButton("JButton"+i));}}publicstaticvoidmain(String[]args){

testFlowLayoutframe=newtestFlowLayout();frame.setTitle("testFlowLayout");//設(shè)置標(biāo)題frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//設(shè)置窗口關(guān)閉操作frame.setBounds(100,100,300,200);//設(shè)置窗口初始位置和寬高frame.setVisible(true);//顯示窗口

}}手工寫的class不使用MatisseForm創(chuàng)建【Return】8.3常用組件文本組件選擇組件Panel組件對話框菜單組件【Return】8.3.1文本組件JLabelJTextFieldJPasswordFieldJTextArea【Return】JLabel屬性方法功能構(gòu)造函數(shù):JLabel(Stringtext)創(chuàng)建一個labelfont.setFont(newjava.awt.Font("微軟雅黑",0,48));設(shè)置字體foreground.setForeground(newjava.awt.Color(255,0,0));設(shè)置文字顏色horizontalAlignment.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);設(shè)置文字水平對齊text.setText("hello");設(shè)置文字border.setBorder(BorderFactory.createEtchedBorder())設(shè)置邊框toolTipTextsetToolTipText()提示文字特殊Jlabel--顯示圖形屬性方法功能構(gòu)造函數(shù):JLabel(Iconimage)創(chuàng)建一個具有圖形labelicon.setIcon(newjavax.swing.ImageIcon("D:\\login.jpg"));轉(zhuǎn)義符‘\\’表示字符‘\’【Return】√JTextField屬性方法功能構(gòu)造函數(shù):JTextField()創(chuàng)建一個空白文本框構(gòu)造函數(shù):JTextField(Stringtext)初始內(nèi)容為texttext.setText(String)、.getText()設(shè)置和讀取文本√editable.setEditable(boolean)、.isEditable()設(shè)置編輯狀態(tài)、判斷能否編輯.selectAll()文本全選JTextField常用事件actionPerformed:回車事件focusGained/lostFocus:獲得/失去焦點事件keyPressed/keyReleased:按下/釋放鍵盤時事件keyTyped:打字符事件示例jTextField1jTextField2jTextField3jLabel2jLabel4主要代碼“啟用”按鈕actionPerformed事件:jTextField1.setEditable(true);“禁用”按鈕actionPerformed事件:jTextField1.setEditable(false);“獲取輸入值”按鈕actionPerformed事件:JOptionPane.showMessageDialog(this,jTextField1.getText());jTextField1的actionPerformed事件:

jLabel2.setText("你輸入的是:"+jTextField2.getText());jTextField2的focusGained事件:

jTextField4.setText("");或者jTextField4.selectAll();jTextField2的KeyReleased事件:

jLabel4.setText("你輸入的是:"+jTextField3.getText());創(chuàng)建對話框【Return】補(bǔ)充:關(guān)于設(shè)置文本框焦點問題常用代碼:

jTextField1.requestFocusInWindow();或

jTextField1.requestFocus();

jTextField1.grabFocus();代碼書寫的位置:

在JFrame的windowActivated事件中添加上述代碼

為事件要調(diào)用的方法命個名添加DocumentListener監(jiān)聽器基本框架:jTextField對象.getDocument().addDocumentListener(new javax.swing.event.DocumentListener(){publicvoidchangedUpdate(DocumentEvente){ //這是更改操作的處理}publicvoidinsertUpdate(DocumentEvente){ //這是插入操作的處理

}publicvoidremoveUpdate(DocumentEvente){ //這是刪除操作的處理

}});DocumentListener示例jTextField4.getDocument().addDocumentListener(new javax.swing.event.DocumentListener(){publicvoidchangedUpdate(DocumentEvente){ jLabel5.setText("你輸入的是:"

+jTextField4.getText());}publicvoidinsertUpdate(DocumentEvente){ jLabel5.setText("你輸入的是:"

+jTextField4.getText());

}publicvoidremoveUpdate(DocumentEvente){ jLabel5.setText("你輸入的是:"

+jTextField4.getText());

}});JPasswordField與JTextField用法類似屬性方法功能.getPassword()注:不推薦用.getText()獲取輸入的密碼echoChar.setEchoChar(charc)設(shè)置回顯的字符--如*默認(rèn)為:實心圓點(\u25cf)注意:此方法返回類型是字符數(shù)組char[],如果要轉(zhuǎn)換為字符串,可用newString(JPasswordField1.getPassword())示例1:驗證密碼長度為JPasswordField添加focusLost事件并添加代碼:if(jPasswordField1.getPassword().length>6){ JOptionPane.showMessageDialog(null,

"密碼長度應(yīng)不多于6個字符!");}示例2:登錄窗口登錄按鈕ActionPerformed代碼privatevoidjButton1ActionPerformed(java.awt.event.ActionEventevt){Stringusername,psd;username=jTextField1.getText();psd=newString(jPasswordField1.getPassword());if(username.equals("wustzz")&&psd.equals("123456"))

JOptionPane.showMessageDialog(this,"歡迎"+username);else{

JOptionPane.showMessageDialog(this,"用戶名或密碼錯!");}}轉(zhuǎn)化一下字符串比較用equlas()方法創(chuàng)建對話框取消按鈕ActionPerformed代碼privatevoidjButton2ActionPerformed(java.awt.event.ActionEventevt){dispose();//回收一下System.exit(0);//結(jié)束程序}改進(jìn)一下:3次輸入錯誤,關(guān)閉登錄窗體JFrame類中添加一個計數(shù)器:privateinterrCount=0;登錄按鈕代碼:if(username.equals("wustzz")&&psd.equals("123456"))…else{JOptionPane.showMessageDialog(this,"用戶名或密碼錯!");

errCount++;}if(errCount==3){JOptionPane.showMessageDialog(this,"3次輸入錯誤,將關(guān)閉登錄窗體!");dispose();System.exit(0);}【Return】JTextArea屬性方法功能構(gòu)造函數(shù):JTextArea()創(chuàng)建一個空白文本區(qū)構(gòu)造函數(shù):JTextArea(Stringtext)初始內(nèi)容為text構(gòu)造函數(shù):JTextArea(introws,intcolumns)行數(shù)為rows,列數(shù)為columns構(gòu)造函數(shù):JTextArea(Stringtext,introws,intcolumns)columns、rows.setColumns(int);.setRows(int);設(shè)置行數(shù)、列數(shù)lineWrapsetLineWrap(boolean)設(shè)置是否自動換行.setText(Strings)、.getText()、.getSelectedText()設(shè)置或獲取全部、選中文本.getLineCount()獲得文本區(qū)文本行數(shù).copy()、.cut()、.paste().append(Strings)、.insert(Strings,intindex)、.setSelectionStart(intselectionstart).setSelectionEnd(intselectionEnd).select(intselectionstart,intselectionEnd).selectAll()復(fù)制、剪切、粘貼選中項添加/插入新文本設(shè)置起始位置設(shè)置結(jié)束位置選中起始位置到結(jié)束位置的串選擇所有文本示例主要代碼if(jTextArea1.getSelectedText()!=null){

jTextArea1.copy();

jTextArea1.select(-1,-1);//取消選中}else{JOptionPane.showMessageDialog(null,"請選擇文本");}復(fù)制按鈕if(jTextArea1.getSelectedText()!=null){

jTextArea1.cut();}else{JOptionPane.showMessageDialog(null,"請選擇文本");}剪切按鈕jTextArea2.paste();粘貼按鈕【Return】8.3.2選擇組件JButtonJCheckboxJRadioButtonJComboBoxJList【Return】JButton屬性方法功能構(gòu)造函數(shù):JButton(Stringtext)創(chuàng)建一個帶文字的按鈕構(gòu)造函數(shù):JButton(Iconicon)創(chuàng)建一個帶圖形的按鈕構(gòu)造函數(shù):JButton(Stringtext,Iconicon)創(chuàng)建一個帶文字和圖形的按鈕text.setText()設(shè)置按鈕文字icon.setIcon(newjavax.swing.ImageIcon(…))設(shè)置按鈕圖形rolloverIconsetRolloverIcon(newjavax.swing.ImageIcon(…))設(shè)置鼠標(biāo)懸浮圖形(配合icon屬性)actionPerformed事件操作jButton1.addActionListener(newjava.awt.event.ActionListener(){publicvoidactionPerformed(java.awt.event.ActionEventevt){

jButton1ActionPerformed(evt);}});privatevoidjButton1ActionPerformed(java.awt.event.ActionEventevt){//處理代碼}【Return】actionPerformed事件調(diào)用的方法JCheckbox屬性方法功能構(gòu)造函數(shù):JCheckBox(Stringtext)創(chuàng)建一個單選按鈕,初始未選中構(gòu)造函數(shù):JCheckBox(Stringtext,booleanb)參數(shù)b確定是否選中text.setText()設(shè)置文字selected.setSelected(boolean)、.isSelected()設(shè)置是否選中、判斷是否選中重要事件:itemStateChangedjCheckBox1.addItemListener(newjava.awt.event.ItemListener(){publicvoiditemStateChanged(java.awt.event.ItemEventevt){ jCheckBox1ItemStateChanged(evt);}});privatevoidjCheckBox1ItemStateChanged(java.awt.event.ItemEventevt){if(jCheckBox1.isSelected()){//復(fù)選框選中//處理代碼

}else{//沒有選中//處理代碼}

}itemStateChanged事件示例privatevoidjCheckBox1ItemStateChanged(java.awt.event.ItemEventevt){if(jCheckBox1.isSelected()){jLabel1.setFont(newjava.awt.Font("微軟雅黑",Font.BOLD,18));

}else{jLabel1.setFont(newjava.awt.Font("微軟雅黑",Font.PLAIN,18));}}設(shè)置字體的方法練習(xí)參考代碼Strings1="";if(jCheckBox1.isSelected()){s1=jCheckBox1.getText();}else{s1="";}…JOptionPane.showMessageDialog(null,"你的愛好有:"+s1+s2+s3);【Return】JRadioButton屬性方法功能構(gòu)造函數(shù):JRadioButton(Stringtext)創(chuàng)建一個單選按鈕,初始未選中構(gòu)造函數(shù):JRadioButton(Stringtext,booleanb)參數(shù)b確定是否選中text.setText()設(shè)置文字selected.setSelected(boolean)、.isSelected()設(shè)置是否選中、判斷是否選中JRadioButton分組同一組的單選按鈕每一時刻只能選擇一個。使用ButtonGroup類來分組,然后利用add()方法,把若干個單選按鈕歸組。用法示例:將ButtonGroup組件放入設(shè)計窗口中(該組件不可見);privatejavax.swing.ButtonGroupbuttonGroup1;buttonGroup1=newjavax.swing.ButtonGroup();使用add方法:buttonGroup1.add(jRadioButton1);buttonGroup1.add(jRadioButton2);這樣jRadioButton1和jRadioButton2在同一組。代碼自動生成重要事件:itemStateChanged【Return】privatevoidjRadioButton1ItemStateChanged(java.awt.event.ItemEventevt){if(jRadioButton1.isSelected()){JOptionPane.showMessageDialog(null,"你選中了"+jRadioButton1.getText());}}JComboBox屬性方法功能構(gòu)造函數(shù):JComboBox()創(chuàng)建一個空選項的下拉列表構(gòu)造函數(shù):JComboBox(Object[]items)參數(shù)items指定選項內(nèi)容model.setModel(newjavax.swing.DefaultComboBoxModel(newString[]{"北京","上海","武漢"}));或者.setModel(newjavax.swing.DefaultComboBoxModel());設(shè)置選項內(nèi)容設(shè)置為空項JComboBox用法示例設(shè)計時編輯model屬性:生成的代碼:jComboBox1.setModel(newjavax.swing.DefaultComboBoxModel(newString[]{"北京","上海","武漢"}));JComboBox用法示例(續(xù))手工創(chuàng)建:String[]strs={"故宮","泰山","張家界","頤和園","孔府"};JComboBoxjComboBox1=newJComboBox(strs);

JComboBox常用方法方法功能addItem(Objectobj)√添加選項removeItem(Objectobj)刪除下拉劉表中被指定的選項removeItemAt(intindex)刪除下拉劉表中指定索引值的選項removeAllItems()√刪除所有選項getSelectedItem()√獲取被選取的選項getSelectedIndex()√獲取被選取選項的索引值getItemAt(intindex)獲取指定索引位置的選項getItemCount()獲取下拉列表的選項個數(shù)setSelectedIndex(inti)根據(jù)序號值設(shè)置下拉列表中被選取的選項setSelectedItem(Objectobj)設(shè)置下拉列表中被選取的選項isEditable()測試下拉列表是否可編輯測試幾個ItemStateChanged事件示例--級聯(lián)創(chuàng)建JComboBox1:添加一個空白項<empty>以及"北京","上海","武漢"幾項創(chuàng)建JComboBox2:添加一個空白項<empty>:jComboBox2.setModel(newDefaultComboBoxModel(newString[]{""}));JComboBox1添加ItemStateChanged事件:intindex=jComboBox1.getSelectedIndex();switch(index){

case0:

jComboBox2.removeAllItems();

break;case1:

jComboBox2.removeAllItems();jComboBox2.addItem("北京大學(xué)");…break;case2:…}【Return】JList屬性方法功能構(gòu)造函數(shù):JList()創(chuàng)建一個空項列表構(gòu)造函數(shù):JList(Object[]items)參數(shù)items指定選項內(nèi)容selectionMode.setSelectionMode(intselectionMode)設(shè)置單選or多選(默認(rèn)可多選)構(gòu)造函數(shù):String[]strs={"北京","上海","武漢"};JListlist=newJList(strs);model屬性滾動問題JList本身不支持滾動,要滾動必須放到JScrollPane中:JScrollPanemyScrollPane=newJScrollPane();myScrollPane.setViewportView(jList1);也可使用:JScrollPanemyScrollPane=newJScrollPane(jList1);

//不使用myScrollPane.add(jList1);

MatisseForm已自動使用JList常用方法方法功能getSelectedValue()獲取選中項值getSelectedIndex()獲取選中項索引值setSelectedIndex(int

i)設(shè)置選中單項getSelectedValues()獲取多個選中項值,返回值為object[]getSelectedIndices()獲取多個選中項索引值,返回值為int[]setSelectedIndices(int[])設(shè)置多個選中項clearSelection()取消選中所有選中項setListData((Vector<?>listData)用一個Vector來設(shè)置列表中的選項單值多值JList示例--多值操作Strings="";

for(Objecto:jList1.getSelectedValues()){ s+=o.toString();}或者:

int[]idx=jList1.getSelectedIndices();for(inti:idx){ s+=jList1.getModel().getElementAt(i);}JOptionPane.showMessageDialog(this,s);

不是用getItemAt(intindex)JList示例--選中/取消int[]indexs={1,2};

jList1.setSelectedIndices(indexs);//選中多項

jList1.clearSelection();//取消選中

【Return】JList+Vector+setListData方法添加/刪除元素

Vectorvt=newVector();vt.add("北京");vt.add("上海");vt.add("武漢");

jList1.setListData(vt);vt.remove("上海");//或用vt.remove(intindex);有關(guān)Vector用法請參考JDKJList+Vector+setListData方法改進(jìn)Vectorvt=newVector();

ListModellistModel=jList1.getModel();//獲取JList的modelfor(intindex=0;index<listModel.getSize();index++)

vt.add(listModel.getElementAt(index));vt.add("北京");vt.add("上海");jList1.setListData(vt);vt.remove("上海");vt.add("深圳");保留原來的內(nèi)容再添加新的保留原來的內(nèi)容添加新內(nèi)容JList+setModel方法來添加/刪除元素//先用DefaultListModel來初始化JList:DefaultListModeldlm1=newDefaultListModel();dlm1.addElement("北京");dlm1.addElement("上海");dlm1.addElement("武漢");jList1.setModel(dlm1);//接著添加/刪除操作:DefaultListModeldlm2=(DefaultListModel)jList1.getModel();//追加元素dlm2.addElement("廣州");//或用.add(序號值,"廣州");dlm2.removeElement("武漢");jList1.setModel(dlm2);強(qiáng)制轉(zhuǎn)換的前提是jList的model已經(jīng)是DefaultListModel類型8.3.3Panel組件JPanelJTabbedPanel【Return】JPanel在MatisseForm中,JPanel使用GroupLayout布局,不需要手工設(shè)置布局?!淌褂胋order屬性可設(shè)置邊框,但邊框上沒有文字。設(shè)置的邊框上沒有文字在邊框上添加文字自定義邊框方法:

.setBorder(newTitledBorder(Boder類型,"邊框文字"))例如:jPanel1.setBorder(newTitledBorder(

BorderFactory.createEtchedBorder(),"邊框文字"));JPanel示例–手工布局主要代碼Containercp=getContentPane();cp.setLayout(newFlowLayout());//設(shè)置JFrame布局

JButtonjb=newJButton("JButton");BasicArrowButtonup=newBasicArrowButton(BasicArrowButton.NORTH),down=newBasicArrowButton(BasicArrowButton.SOUTH),right=newBasicArrowButton(BasicArrowButton.EAST),left=newBasicArrowButton(BasicArrowButton.WEST);//創(chuàng)建JPanel并設(shè)置布局JPaneljp=newJPanel();jp.setPreferredSize(newDimension(100,100));//設(shè)置JPanel的大小jp.setLayout(newGridLayout(2,2));jp.setBorder(newTitledBorder("方向按鈕"));//為JPanel添加標(biāo)題√//將組件添加到Panel中jp.add(up);jp.add(down);jp.add(left);jp.add(right);

//將Panel添加到JFrame中cp.add(jb);cp.add(jp);【Return】JTabbedPaneJTabbedPane選項卡每個選項卡中又是一個Panel組件創(chuàng)建過程(JTabbedPane+JPanel)創(chuàng)建一個JTabbedPane。代碼:

JTabbedPanejTabbedPane1=newJTabbedPane();將一個JPanel放在TabbedPane上部。代碼:JPaneljPanel1=newJPanel();

jTabbedPane1.addTab("tab1",jPanel1);

JTabbedPaneJPanel虛線狀態(tài)第一個參數(shù)是選項卡標(biāo)題使用addTab方法將Panel添加到TabbedPane中創(chuàng)建過程(JTabbedPane+JPanel)續(xù)如果有多個選項卡,則重復(fù)上一步操作。最后選擇不同的選項卡,將所需組件放置上去即可。【Return】補(bǔ)充:(1)創(chuàng)建帶圖形的選項卡jTabbedPane1.addTab("名稱",newImageIcon("D:\\login.jpg"),jPanel1);(2)將選項卡放在下部:

jTabbedPane1.setTabPlacement(JTabbedPane.BOT

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論