8. 按钮(JButton)使用示例
例14. 按钮使用示例。
package GUI; import java.awt.BorderLayout; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; public class demoJButton implements ActionListener{ JFrame jf; JButton jb; Container con; ImageIcon closeIcon,openIcon; public demoJButton(){ jf = new JFrame("JButton使用示例"); openIcon = new ImageIcon("open.jpg"); closeIcon = new ImageIcon("close.jpg"); jb = new JButton("打开", openIcon); jb.addActionListener(this); con = jf.getContentPane(); con.add(jb, BorderLayout.NORTH); jf.setSize(500, 400); jf.setLocation(300, 200); jf.setVisible(true); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { new demoJButton(); } public void actionPerformed(ActionEvent e) { if(e.getSource()==jb){ if(jb.getText().compareTo("打开")==0){ jb.setText("关闭"); jb.setIcon(closeIcon); }else { jb.setText("打开"); jb.setIcon(openIcon); } } } }
9. 文本框(JTextField)和密码框(JPasswordField)使用示例
例. 文本框和密码框使用示例。
package GUI; import java.awt.Container; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPasswordField; import javax.swing.JTextField; public class demoJText { JLabel jl1,jl2; JFrame jf; Container con; JButton loginBtn,cancelBtn; JTextField userText; JPasswordField jpf; HandleAction handleAction; public class HandleAction implements ActionListener { public void actionPerformed(ActionEvent e) { String msg; if(e.getSource()==loginBtn){ msg = "你的用户名是:"+userText.getText()+"\n你的密码是:"+new String(jpf.getPassword()); JOptionPane.showMessageDialog(jf, msg); }else if(e.getSource()==cancelBtn){ userText.setText(""); jpf.setText(""); } } } public demoJText(){ jl1 = new JLabel("用户名"); jl2 = new JLabel("密 码"); jf = new JFrame("文本框和密码框使用示例"); con = jf.getContentPane(); handleAction = new HandleAction(); loginBtn = new JButton("登录"); loginBtn.addActionListener(handleAction); cancelBtn = new JButton("取消"); cancelBtn.addActionListener(handleAction); userText = new JTextField(); userText.setColumns(20); jpf = new JPasswordField(); jpf.setColumns(20); con.setLayout(new FlowLayout()); con.add(jl1); con.add(userText); con.add(jl2); con.add(jpf); con.add(loginBtn); con.add(cancelBtn); jf.setSize(300, 300); jf.setLocation(300, 200); jf.setVisible(true); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { new demoJText(); } }
如果需要在输入的密码框中显示其他符号,可以使用setEchoChar('*')来实现。
实现回车功能的该进如下:
package GUI; import java.awt.Container; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPasswordField; import javax.swing.JTextField; public class demoJText { JLabel jl1,jl2; JFrame jf; Container con; JButton loginBtn,cancelBtn; JTextField userText; JPasswordField jpf; HandleAction handleAction; public class HandleAction implements ActionListener { public void actionPerformed(ActionEvent e) { String msg; if(e.getSource()==loginBtn){ msg = "你的用户名是:"+userText.getText()+"\n你的密码是:"+new String(jpf.getPassword()); JOptionPane.showMessageDialog(jf, msg); }else if(e.getSource()==cancelBtn){ userText.setText(""); jpf.setText(""); }else if(e.getSource()==userText){ jpf.requestFocus(); }else if(e.getSource()==jpf){ loginBtn.doClick(); } } } public demoJText(){ jl1 = new JLabel("用户名"); jl2 = new JLabel("密 码"); jf = new JFrame("文本框和密码框使用示例"); con = jf.getContentPane(); handleAction = new HandleAction(); loginBtn = new JButton("登录"); loginBtn.addActionListener(handleAction); cancelBtn = new JButton("取消"); cancelBtn.addActionListener(handleAction); userText = new JTextField(); userText.addActionListener(handleAction); userText.setColumns(20); jpf = new JPasswordField(); jpf.addActionListener(handleAction); jpf.setColumns(20); con.setLayout(new FlowLayout()); con.add(jl1); con.add(userText); con.add(jl2); con.add(jpf); con.add(loginBtn); con.add(cancelBtn); jf.setSize(300, 300); jf.setLocation(300, 200); jf.setVisible(true); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { new demoJText(); } }
10. 文本区(JTextArea)使用示例
例. 文本区使用使用示例。
package GUI; import javax.swing.*; public class demoJTextArea { JFrame jf; JScrollPane jsp; JTextArea jta; public demoJTextArea(){ jf = new JFrame("这是一个JTextArea使用示例"); jta = new JTextArea(); jsp = new JScrollPane(jta); jf.getContentPane().add(jsp); jf.setSize(500, 400); jf.setLocation(300, 200); jf.setVisible(true); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { new demoJTextArea(); } }
11. 复选框(JCheckBox)使用示例
例. 复选框使用示例。
package GUI; import java.awt.Container; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class demoJcheckBox implements ActionListener{ JFrame jf; JLabel jl; JCheckBox jb[]; Container con; JButton OKbtn; static final String ProvinceName[]={"北京","上海","天津","辽宁","吉林","四川","湖南","湖北","广东"}; public demoJcheckBox(){ jf = new JFrame("JCheckBox使用示例"); jl = new JLabel("请至少选择一个你去过的省份"); con = jf.getContentPane(); con.setLayout(new FlowLayout()); con.add(jl); jb = new JCheckBox[ProvinceName.length]; for(int i=0;i<jb.length;i++){ jb[i] = new JCheckBox(ProvinceName[i],false); con.add(jb[i]); } OKbtn = new JButton("确定"); OKbtn.addActionListener(this); con.add(OKbtn); jf.setSize(500, 400); jf.setLocation(300, 200); jf.setVisible(true); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent e) { String str= ""; int count = 0; for(int i=0;i<jb.length;i++){ if(jb[i].isSelected()){ count++; str = str + jb[i].getText() + " "; } } if(e.getSource()==OKbtn) JOptionPane.showMessageDialog(jf, "你选择了"+count+"个省份,它们是:\n"+str); } public static void main(String[] args) { new demoJcheckBox(); } }
12. 单选按钮(JRadioButton)使用示例
单选按钮本身无法知道自己和其它按钮的关系,所以要把他们放在一个名为ButtonGroup的组件中统一管理。该组件本身不可见,但对于JRadioButton却是必不可少的。
例. 单选按钮使用示例。
package GUI; import java.awt.Container; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class demoJRadioButton implements ActionListener{ JFrame jf; JLabel jl; JButton Okbtn; JRadioButton jrb1,jrb2; ButtonGroup sexbg; Container con; String str="男"; public demoJRadioButton(){ jf = new JFrame("JRadioButton使用示例"); jl = new JLabel("请选择性别"); Okbtn = new JButton("确定"); Okbtn.addActionListener(this); jrb1 = new JRadioButton("男",true); jrb1.addActionListener(this); jrb2 = new JRadioButton("女",false); jrb2.addActionListener(this); sexbg = new ButtonGroup(); sexbg.add(jrb1); sexbg.add(jrb2); con = jf.getContentPane(); con.setLayout(new FlowLayout()); con.add(jl); con.add(jrb1); con.add(jrb2); con.add(Okbtn); jf.setSize(500, 400); jf.setLocation(300, 200); jf.setVisible(true); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent e) { if(e.getSource() instanceof JRadioButton){ str = e.getActionCommand(); }else{ JOptionPane.showMessageDialog(jf, "你选择了"+str); } } public static void main(String[] args) { new demoJRadioButton(); } }
13. 列表框(JList)使用示例
例. 列表框使用示例。
package GUI; import java.awt.BorderLayout; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class demoJList implements ActionListener{ JFrame jf; JPanel jp; JButton addBtn,delBtn; Container con; JList lList,rList; DefaultListModel lModel,rModel; JScrollPane ljsp,rjsp; JSplitPane jsp; static final String city[] = {"北京","上海","天津","辽宁","吉林","四川","湖南","湖北","广东"}; public demoJList(){ jf = new JFrame("JList使用示例"); jp = new JPanel(); addBtn = new JButton("选中>>"); addBtn.addActionListener(this); delBtn = new JButton("撤销<<"); delBtn.addActionListener(this); con = jf.getContentPane(); lModel = new DefaultListModel(); for(int i=0;i<city.length;i++) lModel.addElement(city[i]); rModel = new DefaultListModel(); lList = new JList(lModel); rList = new JList(rModel); ljsp = new JScrollPane(lList); rjsp = new JScrollPane(rList); jsp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,true,ljsp,rjsp); con.add(jsp, BorderLayout.CENTER); jp.add(addBtn); jp.add(delBtn); con.add(jp, BorderLayout.SOUTH); jf.setSize(500, 400); jf.setLocation(300, 200); jf.setVisible(true); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jsp.setDividerLocation(0.5); } public void actionPerformed(ActionEvent e) { int i; if(e.getSource()==addBtn){ for(i=0;i<lModel.size();i++) if(lList.isSelectedIndex(i)) rModel.addElement(lModel.getElementAt(i)); for(i--;i>=0;i--) if(lList.isSelectedIndex(i)) lModel.removeElementAt(i); }else{ for(i=0;i<rModel.size();i++) if(rList.isSelectedIndex(i)) lModel.addElement(rModel.getElementAt(i)); for(i--;i>=0;i--) if(rList.isSelectedIndex(i)) rModel.removeElementAt(i); } } public static void main(String[] args) { new demoJList(); } }
14. 组合框(JComboBox)使用示例
例. 组合框使用示例。
package GUI; import java.awt.Container; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import javax.swing.*; public class demoJComboBox implements ItemListener,ActionListener{ JFrame jf; JLabel jl1,jl2; JComboBox jcb; JButton btn; Container con; static final String city[] = {"北京","上海","天津","辽宁","吉林","四川","湖南","湖北","广东"}; public demoJComboBox(){ jf = new JFrame("JComboBox使用示例"); jl1 = new JLabel("您的选择是:"); jl2 = new JLabel(" "); jcb = new JComboBox(city); jcb.setEditable(true); jcb.addItemListener(this); btn = new JButton("可以编辑"); btn.addActionListener(this); con = jf.getContentPane(); con.setLayout(new FlowLayout()); con.add(jl1); con.add(jl2); con.add(jcb); con.add(btn); jf.setSize(500, 400); jf.setLocation(300, 200); jf.setVisible(true); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent e) { if(e.getSource()==btn){ if(btn.getText().compareTo("可以编辑")==0){ btn.setText("不可编辑"); jcb.setEditable(true); }else{ btn.setText("可以编辑"); jcb.setEditable(false); } } } public void itemStateChanged(ItemEvent e) { if(e.getStateChange()==ItemEvent.SELECTED) jl2.setText((String)jcb.getSelectedItem()); } public static void main(String[] args) { new demoJComboBox(); } }
15. 表格(Jtable)使用示例
一般情况下,可以通过Jtable(int row,int col)来指定表格拥有的行和列。如果需要动态地调整列数,可以直接使用它的方法addColumn()和removeColumn()。如果需要调整行数,则像JList一样,需要调用和它的联系的DefaultTableModel的addRow()和removeRow()方法。还有,JTable本身不提供滚动条,需要把它放到JScrolPane中才能滚动。
例15.1 表格使用示例1。
package GUI; import java.awt.Container; import javax.swing.*; public class demoJTable_1 { JFrame jf; JScrollPane jsp; JTable jtab; Container con; public demoJTable_1(){ jf = new JFrame("JTable使用示例"); jtab = new JTable(10,3); jsp = new JScrollPane(jtab); con = jf.getContentPane(); con.add(jsp); jf.setSize(500, 400); jf.setLocation(300, 200); jf.setVisible(true); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { new demoJTable_1(); } }
例15.2 表格使用示例2.
package GUI; import javax.swing.*; public class demoJTable_2 { JFrame jf; JScrollPane jsp; JTable jtab; public demoJTable_2(){ Object[][] stu = { {"小王",new Integer(66),new Integer(72),new Integer(98),new Boolean(false)}, {"小张",new Integer(82),new Integer(69),new Integer(78),new Boolean(true)} }; String[] title = {"姓名","语文","数学","总分","及格"}; jf = new JFrame("JTable使用示例"); jtab = new JTable(stu,title); jsp = new JScrollPane(jtab); jf.add(jsp); jf.setSize(500, 400); jf.setLocation(300, 200); jf.setVisible(true); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { new demoJTable_2(); } }
注意:这里必须要使用滚动面板来显示表格,如果直接将表格加入到JFrame中,表头将无法正常显示。
例15.3 表格使用示例3。
package GUI; import java.awt.Container; import javax.swing.*; import javax.swing.table.TableColumn; public class demoJTable_3 { JFrame jf; JScrollPane jsp; JTable jtab; Container con; Object[][] stu = { {"小王",new Integer(66),new Integer(72),new Integer(98),new Boolean(false),new Boolean(false)}, {"小张",new Integer(82),new Integer(69),new Integer(78),new Boolean(true),new Boolean(false)} }; String[] title = {"姓名","语文","数学","总分","及格","作弊"}; public demoJTable_3(){ jf = new JFrame(); jf.setTitle("JTable使用示例"); jtab = new JTable(stu,title); //利用JTable中的getColumnModel()方法取得TableColumnModel对象的引用 //利用对象的setPreferredWidth()方法就可以控制字段的宽度 for(int i=0;i<title.length;i++){ TableColumn column = jtab.getColumnModel().getColumn(i); if(i%2==0) column.setPreferredWidth(150); else column.setPreferredWidth(50); } jsp = new JScrollPane(jtab); con = jf.getContentPane(); con.add(jsp); jf.setSize(500, 400); jf.setLocation(300, 200); jf.setVisible(true); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { new demoJTable_3(); } }
前面的3个例子都只是显示数据供用户查看,如果需要获取用户修改后的数据,程序只需利用getColumnCount()和getRowCount()方法,获得JTable的列数和行数,然后遍历整个JTable,利用getValueAt()方法获取单元格里的内容就可以了。如果修改某个单元格里面的值,也可以利用setValueAt()来完成。
例15.4 表格使用示例4.
package GUI; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class demoJTable_4 implements ActionListener { JFrame jf; JTable sourceTable,destTable; JScrollPane jsp1,jsp2; JButton copyBtn; Container con; JPanel jp; int row,col; public demoJTable_4(){ jf = new JFrame("JTable使用示例"); sourceTable = new JTable(2,3); col = sourceTable.getColumnCount(); row = sourceTable.getRowCount(); destTable = new JTable(col,row); jsp1 = new JScrollPane(sourceTable); jsp2 = new JScrollPane(destTable); copyBtn = new JButton("复制数据"); copyBtn.addActionListener(this); jp = new JPanel(); jp.add(copyBtn); con = jf.getContentPane(); con.setLayout(new GridLayout(3,1)); con.add(jsp1); con.add(jp); con.add(jsp2); jf.setSize(500, 400); jf.setLocation(300, 200); jf.setVisible(true); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent e) { int i,j; Object obj; if(e.getSource()==copyBtn){ for(i=0;i<row;i++) for(j=0;j<col;j++){ obj = sourceTable.getValueAt(i, j); destTable.setValueAt(obj, j, i); } } } public static void main(String[] args){ new demoJTable_4(); } }
与JTable相关的模型有3个:TableModel、TableColumnModel和ListSelectionModel。其中最常用的是TableModel。
重写一个MyTableModle来代替系统提供的DefaultTableModle,这样可以显示Boolean类型的数据时,不以字符串形式显示,而是以checkBox的形式显示,并且字符串会左对齐,而数值则右对齐。
例15.5 表格使用示例5.
package GUI; import javax.swing.table.AbstractTableModel; final class MyTableModel extends AbstractTableModel { private Object data[][]; //存储表格中的数据 private String[] tableName; //存储表头 public MyTableModel(Object[][] data, String[] tableName){ this.data = data; this.tableName = tableName; } public MyTableModel(Object[][] data){ char[] tch = {'A'}; tableName = new String[data[0].length]; this.data = data; for(int i=0;i<tableName.length;i++){ tableName[i] = new String(tch); tch[0]++; } } public int getRowCount() { return data.length; } public int getColumnCount() { return data[0].length; } public Object getValueAt(int rowIndex, int columnIndex) { return data[rowIndex][columnIndex]; } public Class<?> getColumnClass(int columnIndex) { return data[0][columnIndex].getClass(); } public String getColumnName(int column) { return tableName[column]; } }
在上述类中,真正和显示有关的就只有getColumnClass()方法。该方法返回实际存储数据的类类型,因此在显示的时候,表格会根据这些类型做调整。
package GUI; import java.awt.Container; import javax.swing.*; import javax.swing.table.TableColumn; public class demoJTable_5 { JFrame jf; JScrollPane jsp; JTable jtab; MyTableModel mtm; Container con; Object[][] stu = { {"小王",new Integer(66),new Integer(72),new Integer(98),new Boolean(false),new Boolean(false)}, {"小张",new Integer(82),new Integer(69),new Integer(78),new Boolean(true),new Boolean(false)} }; String[] title = {"姓名","语文","数学","总分","及格","作弊"}; public demoJTable_5(){ jf = new JFrame(); jf.setTitle("JTable使用示例"); //创建带内容和表头信息的模型 mtm = new MyTableModel(stu,title); //用模型创建表格,取代默认的模型 jtab = new JTable(mtm); //利用JTable中的getColumnModel()方法取得TableColumnModel对象的引用 //利用对象的setPreferredWidth()方法就可以控制字段的宽度 for(int i=0;i<title.length;i++){ TableColumn column = jtab.getColumnModel().getColumn(i); if(i%2==0) column.setPreferredWidth(150); else column.setPreferredWidth(50); } jsp = new JScrollPane(jtab); con = jf.getContentPane(); con.add(jsp); jf.setSize(500, 400); jf.setLocation(300, 200); jf.setVisible(true); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { new demoJTable_5(); } }