您的位置:首页 > 编程语言 > Java开发

Java语言的基础知识8

2014-07-23 08:32 267 查看
第十章
1、标签有JLabel类定义,它的父类为JComponent。标签可以显示一行只读文本、一个图像但不能产生任何事件。JLabel有多种构造方法,example:
JLabel()、JLable(Icon icon)、JLable(Icon icon,int aligment)、JLable(String text,int aligment)、JLale(String text,Icon icon,int aligment)
2、
package com.lenovo.dishizhang;

import java.awt.Container;
import java.net.URL;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;

public class MyImageIcon extends JFrame{
public MyImageIcon() {
// TODO Auto-generated constructor stub
Container container = getContentPane();
JLabel jl = new JLabel("带图标的标签组件", JLabel.CENTER);
URL url = MyImageIcon.class.getResource("icon.jpg");
// Icon icon = new ImageIcon(url);
ImageIcon icon = new ImageIcon("C:\\Users\\wangqm\\Desktop\\icon.jpg");
jl.setIcon(icon);
jl.setHorizontalAlignment(SwingConstants.CENTER);
jl.setOpaque(true);
container.add(jl);
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(286,168);

}
public static void main(String[] args) {
new MyImageIcon();
}
}

java.lang.Class类中的getResource()方法 可以获取资源文件的URL
3、JButton的构造方法有四种,example:
JButton()、JButton(Icon,icon),JButton(String text),JButton(String text,Icon icon)
4、JRadioButton也是一种按钮,它用于创建界面中的单选按钮。它也有和JButton类似的构造方法。
JRadioButton()、JRadioButton(Icon icon)、JRadioButton(String text,Icon icon)、JRadioButton(String text)、JRadioButton(String text,boolean selected)
单选按钮 用的时候 要放在Group类里面,即使每个按钮都放在了group里面 也要用getcontentPane()将每个按钮放在容器中,不能将group直接放在容器中
package com.lenovo.dishizhang;

import java.awt.GridLayout;

import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.WindowConstants;

public class JRadioButtonDemo extends JFrame {
public JRadioButtonDemo() {
// TODO Auto-generated constructor stub
super();
ButtonGroup group = new ButtonGroup();
getContentPane().setLayout(new GridLayout(1, 0));
setBounds(100, 100, 230,87);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
final JRadioButton radioButton = new JRadioButton();
group.add(radioButton);
radioButton.setText("优秀");
getContentPane().add(radioButton);
final JRadioButton radioButton2 = new JRadioButton("及格");
group.add(radioButton2);
getContentPane().add(radioButton2);
final JRadioButton radioButton3 = new JRadioButton("很差", true);
group.add(radioButton3);
getContentPane().add(radioButton3);
setVisible(true);
}
public static void main(String[] args) {
new JRadioButtonDemo();
}
}
上面的例子 必须将每一个按钮都放在group里面
5、文本框组件JTextFiled 常用的构造方法:
JTextField()、JTextField(String text)、JTextField(int columns)、JTextField(String text,int columns)、如果将文本框使用绝对布局或者布局在限制组件大小的布局管理器中 columns将不起作用
6、密码框组件用JPasswordField ,
JPasswordField passwordField = new JPasswordField("mrsoft");
passwordField.setEchoChar('*');
passwordField.setColumns(10);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息