Java学习笔记--Swing用户界面组件

很多与AWT类似.

事件处理参考:Java学习笔记--AWT事件处理 

1.设计模式:

模型:存储内容
视图:显示内容
控制器:处理用户输入·

2. 文本输入常用组件

2.1 文本域:

JLabel labelname = new JLabel("username");
JTextArea textname = new JTextArea(1,40);//参数也可以为("默认字符",行,列);
JPanel panel = new JPanel();
panel.add(labelname);
panel.add(textname);

如果需要在运行时重新设定列数,需要调用包含这个文本框的容器的revalidate方法,可以重新设定容器的尺寸。
textField.setColumns(10);
panel.revalidate();

2.2 标签:JLabel
容纳文本的组件,没有任何修饰,不能响应用户输入。
可以选择内容的排列方式,可以用SwingConstants接口中的常量,如LEFT, RIGHT, CENTER, NORTH, EAST.
JLabel labelname = new JLabel("username",SwingConstants.RIGHT);

2.3 密码域:JPasswordField
JPasswordField(String text , int columns); //创建一个新的密码域
char[] getPassword() //返回密码域中的文本

2.4 文本区:
用户的输入超过一行是,也可以用JTextArea,
textArea = nwe JTextArea(8,40); //8行40列的文本区
注:用户不会受限于输入指定的行列,输入过长时,文本会滚动。
可以开启换行特性避免裁剪过长的行 textArea.setLineWrap(true);

2.5 滚动条:
在Swing中,文本区没有滚动条,需要时可以将文本区插入到滚动窗格中
textArea = new JTextArea(8,40);
JScrollPane scrollPane = new JScrollPane(textArea);

链接JScrollPane的使用http://pan.baidu.com/s/1ntHWVMx

 

例子

public class MySwingModel {
	public static void main(String args[]){
		JFrame frame = new JFrame();
		frame.setSize(450,450);
		frame.setLayout(new BorderLayout(10,10));//设置布局管理器
		
		//////////////////// PART SOUTH ///////////////////////
		//每个JButton对象都存储了一个按钮模型对象,可以这样得到它的引用
		JButton mbutton = new JButton("我的按钮");
		ButtonModel mode1 = mbutton.getModel();
		
		JPanel panelSouth = new JPanel();//新建面板
		panelSouth.add(mbutton);	//将按钮加入面板
		
		/////////////////// PART NORTH/////////////////////////		
		//指定文本域的行数、列数
		JLabel labelname = new JLabel("username",SwingConstants.CENTER);
		final JTextArea textname = new JTextArea("默认用户名,请删除后输入用户名",1,20);
		
		String strpassword = null;
		JLabel labelpassword = new JLabel("password",SwingConstants.CENTER);
		final JPasswordField textpassword = new JPasswordField(strpassword,40);
		//char [] mypassword  = textpassword.getPassword();//获取密码
		
		JPanel panelNorth = new JPanel();//创建网格布局的面板,添加用户名、密码		
		panelNorth.setLayout(new GridLayout(2,2,10,10));
		panelNorth.add(labelname);
		panelNorth.add(textname);
		panelNorth.add(labelpassword);
		panelNorth.add(textpassword);
		
		////////////////// PART CENTER //////////////////////
		final JTextArea textwords = new JTextArea(15,40);
		textwords.setLineWrap(true);//开启换行特性,避免文本过长
		JScrollPane textscrollPane = new JScrollPane(textwords);//新建滚动窗格,当行数过大时显示滚动条
		
		////////////////// 设置按钮响应 ///////////////////////
		mbutton.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent mEvent){
				String myName = textname.getText();
				char[] mypassword = textpassword.getPassword();//获取密码				
				textwords.setText("用户名:"+myName+"
密码:"+new String(mypassword));
			}
		});
		
		/////////////////////////////////////////////////////
		frame.add(panelSouth,BorderLayout.SOUTH); //将面板加入框架
		frame.add(panelNorth,BorderLayout.NORTH);
		frame.add(textscrollPane,BorderLayout.CENTER);
		
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
		
	}
}

  

3. 选择组件

3.1 复选框

复选框需要一个紧邻它的标签说明用途
JCheckBox bold = new JCheckBox("bold");

可以使用setSelected方法选定/取消复选框
bold.setSelected(true);

isSelected方法返回每个复选框当前状态。true/false
两个复选框可用同一监听器
bold.addActionListener(listener);
italic.addActionListener(listener);

public class MySwingChoose {
	public static void main(String args[]){
		JFrame frame = new JFrame();
		frame.setSize(450,450);
		frame.setLayout(new BorderLayout(10,10));  //设置布局管理器
		
		final JCheckBox bold = new JCheckBox("Bold");
		final JCheckBox italic = new JCheckBox("Italic");
		final JLabel labelSelect = new JLabel();  //显示选择了哪些选项
		
		ActionListener mylistener = new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				String strIsselect ="";
				if(bold.isSelected()==true){
					strIsselect+="Bold已选择";
					
				}if(italic.isSelected()==true){
					strIsselect+="Italic已选择";
				}
				labelSelect.setText(strIsselect);
			}
		};
		bold.addActionListener(mylistener);
		italic.addActionListener(mylistener);
		
		JPanel panel = new JPanel();
		panel.add(bold);
		panel.add(italic);
		panel.add(labelSelect);
		
		frame.add(panel);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}
}

  

3.2 单选按钮组 JRadioButton

实现单选按钮组
为单选按钮组构造一个ButtonGroup对象
将JRadionButton类型的对象添加到按钮组中

public class MySwingRadio {
	public static void main(String args[]){
		JFrame frame = new JFrame();
		frame.setSize(450,450);
		frame.setLayout(new BorderLayout(10,10));//设置布局管理器
		
		//创建单选按钮组
		ButtonGroup mbuttongroup = new ButtonGroup();
		
		//创建单选按钮
		JRadioButton jradioSmall = new JRadioButton("small",false);
		JRadioButton jradioMedium = new JRadioButton("medium",false);
		JRadioButton jradioLarge = new JRadioButton("large",false);
		
		//将单选按钮添加到按钮组
		mbuttongroup.add(jradioSmall);		
		mbuttongroup.add(jradioMedium);		
		mbuttongroup.add(jradioLarge);
		
		//将按钮添加到面板
		JPanel panel = new JPanel();
		panel.add(jradioSmall);
		panel.add(jradioMedium);
		panel.add(jradioLarge);
		
		//将面板添加到框架,而不是单选按钮组添加到框架
		frame.add(panel);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
		
	}
}

另一种实现方式,(不错的例子,可以直接设定监听器)

public class MySwingRadio2 {
	private final static int  DEFAULT_SIZE = 36;
	//创建单选按钮组
	private static ButtonGroup mbuttongroup = new ButtonGroup();
	//创建面板
	static JPanel panel = new JPanel();
	static JLabel mlabel = new JLabel("");
	public static void main(String args[]){
		JFrame frame = new JFrame();
		frame.setSize(450,450);
		frame.setLayout(new BorderLayout(10,10));//设置布局管理器
		
		//将单选按钮添加到按钮组
		addRadioButton("small",8);
		addRadioButton("medium",16);
		addRadioButton("large",32);
		
		//将面板添加到框架,而不是单选按钮组添加到框架
		frame.add(mlabel,BorderLayout.CENTER);
		frame.add(panel,BorderLayout.NORTH);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}

	public static void addRadioButton(final String name,final int size){
		boolean selected = (size == DEFAULT_SIZE);
		//新建单选按钮
		JRadioButton button = new JRadioButton(name,selected);
		//将单选按钮添加到单选按钮组
		mbuttongroup.add(button);
		//将单选按钮添加到面板
		panel.add(button);

		//设定监听器,在标签中显示点击的单选 按钮
		ActionListener mylistener = new ActionListener(){
			public void actionPerformed(ActionEvent e){
				mlabel.setText(name);
			}
		};
		button.addActionListener(mylistener);
	}
}

3.3 边框 Border  javax.swing.border

调用BorderFactory的静态方法创建边框  

BroderFactory.createLineBorder(Border border)
BroderFactory.createCompoundBorder(Border border)
BroderFactory.createTitledBorder(Border border)

所有的方式见javax.swing下面的类BorderFactory

调用JComponent类中setBorder方法将结果边框添加到组件

Border etched = BorderFactory.createEtchedBorder()
Border titled = BorderFactory.createTitledBorder(etched,"A Title")
panel.setBorder(titled)

框架可以组合。

示例代码

public class MySwingText {
	public static void main(String args[]){
		JFrame frame = new JFrame();
		frame.setSize(450,450);
		frame.setLayout(new BorderLayout(10,10));//设置布局管理器
		JPanel panel = new JPanel();
		Border etched = BorderFactory.createEtchedBorder();
		Border titled = BorderFactory.createTitledBorder(etched,"A Title");
		panel.setBorder(titled);
		
		frame.add(panel);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}
}

  

 3.4组合框 JComboBox<>

创建组合框 : 
JComboBox<String> faceCombo = new JConboBox<>();

调用setEditable方法让组合框可编辑

获取当前选项 :getSelectedItem 
若组合框不可编辑,最好调用 : faceCombo.getItemAt(faceCombo.getSelectedIndex())
addItem方法添加选项 : faceCombo.addItem("Serif");
在任意位置插入选项 : faceCombo.insertItemAt("Monospaced",0);

删除选项:
faceCombo.removeItem("Monospaced");
faceCombo.removeItemAt(0);

 示例

UseComboBox.java

public class UseComboBox {
	public static void main(String[] args) {
		ComboBoxFrame cbframe = new ComboBoxFrame();
		cbframe.setVisible(true);
		cbframe.setSize(400,400);
		cbframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
}

 ComboBoxFrame.java

public class ComboBoxFrame extends JFrame{
	private JComboBox<String> faceCombo;
	private JLabel label;
	private static final int DEFAULT_SIZE =24;
	
	public ComboBoxFrame(){
		//添加文字标签
		label = new JLabel("我的标签文字");
		label.setFont(new Font("Serif",Font.PLAIN,DEFAULT_SIZE));
		add(label,BorderLayout.CENTER);
		
		//添加组合框
		faceCombo = new JComboBox(); //创建组合框
		faceCombo.addItem("Serif");//添加条目
		faceCombo.addItem("SansSerif");
		faceCombo.addItem("MonoSpaced");
		faceCombo.addItem("Dialog");
		faceCombo.addItem("DialogInput");
		//为组合框设置监听器
		faceCombo.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				label.setFont(new Font(faceCombo.getItemAt(faceCombo.getSelectedIndex()),
						Font.PLAIN,DEFAULT_SIZE));
			}
		});
		
		//将组合框添加到panel
		JPanel comboPanel = new JPanel();
		comboPanel.add(faceCombo);
		add(comboPanel,BorderLayout.SOUTH);
		pack();
	}
}

3.5 滑动条 JSlider

JSlider slider = new JSlider(min,max,initialValue);

 

4.  菜单

4.1菜单创建

(1) 创建菜单栏 : JMenuBar menubar = new JMenuBar();
(2) 将菜单栏添加到框架上: frame.setJMenuBar(menuBar);
(3) 为每一个菜单建立一个菜单对象: JMenu editMenu = new JMenu("Edit");
(4) 将顶层菜单添加到菜单栏中: menuBar.add(editMenu);

(5) 向(3)中的菜单对象添加菜单项
  JMenuItem pasteItem = new JMenuItem("Paste");
  editMenu.add(pasteItem);//添加菜单项
  editMenu.addSparator();//添加分隔符
  JMenu optionMenu = ... ; //a submenu
  editMenu.add(optionMenu);可以看到分隔符位于Paste和Read-only菜单项之间

 

 动作监听

 为每个菜单项JMenuItem安装一个动作监听器

ActionListener listener = ...;
pasteItem.addActionListener(listener);

可以使用 JMenu.add(String s)方法将菜单项插入到菜单的尾部
editMenu.add("Paste");
ADD方法返回创建的子菜单项,可以采用下列方法获取它,并添加监听器:

JMenuItem pasteItem = editMenu.add("Paste");
pasetItem.addActionListener(listener);

在通常情况下,菜单项出发的命令也可以通过其他用户界面元素(如工具栏上的按钮)激活。通常,采用扩展抽象类AbstractAction来定义一个实现Action接口的类。这里需要在AbstractAction对象的构造器中指定菜单项标签并且覆盖actionPerformed方法来获得菜单动作处理器。

Action exitAction = new AbstractAction("Edit"){
	public void actionPerformed(ActionEvent event){
		//动作代码
		System.exit(0);
	}
};

然后将动作添加到菜单中

JMenuItem exitItem = fileMenu.add(exitAction);

这个命令利用动作名将一个菜单项添加到菜单中,这个动作对象将作为它的监听器

上面这条语句是下面两条语句的快捷形式:

JMenuItem exitItem = new JMenuItem(exitAction);
fileMenu.add(exitItem);

 示例代码 

public class MyJMenu {
	public static void main(String[] args) {
		JFrame mframe = new JFrame();
		
		JMenuBar menubar = new JMenuBar();//创建菜单栏
		
		////////////////////////  菜单对象1  //////////////////////////
		JMenu editMenu = new JMenu("Edit");//为每一个菜单建立一个菜单对象
		menubar.add(editMenu);//将菜单添加到菜单栏
		//--                   菜单项1                        --//
		JMenuItem pasteItem = new JMenuItem("Paste");
		editMenu.add(pasteItem);//添加菜单项
		editMenu.addSeparator();//添加分隔符
		
		//--                   菜单项2                        --//
		JMenuItem readonlyItem = new JMenuItem("Read-Only");
		editMenu.add(readonlyItem);//添加菜单项
		
		////////////////////////菜单对象2  //////////////////////////
		JMenu sourceMenu = new JMenu("Source");
		menubar.add(sourceMenu);
		editMenu.addSeparator();//添加分隔符
		////////////////////////菜单对象3 //////////////////////////
		Action exitAction = new AbstractAction("exit"){
			public void actionPerformed(ActionEvent event){
				//动作代码
				System.exit(0);
			}
		};
		JMenuItem exitItem = editMenu.add(exitAction);
		/*
		 *  上面这条语句是下面两条语句的快捷形式:
		 * JMenuItem exitItem = new JMenuItem(exitAction);
		 * editMenu.add(exitItem);
		 * */
		////////////////////////////////////////////////////////////
		mframe.setJMenuBar(menubar);//菜单栏添加到框架上		
		mframe.setSize(450, 300);
		mframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		mframe.setVisible(true);
	}	
}

代码效果

原文地址:https://www.cnblogs.com/gnivor/p/4264174.html