java swing总结
来源:互联网 发布:农产品进出口数据 编辑:程序博客网 时间:2024/06/10 15:34
java中编译出错常见问题:
1.Exception in thread "main" java.lang.NullPointerException
Stru_TreeParam treeParam=null ;(出错!!!)
Stru_TreeParam treeParam= new Stru_TreeParam();(正确)
//应该为变量申请空间,不应该简单赋空值
//new一个变量的重要性和c中的指针一样重要,否则必定会出现存数取数错误。。。。。。。。。。。。。
2.不要为class命名重复,会出现不同错误。比如:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
No enclosing instance of type NPanel is accessible. Must qualify the allocation with an enclosing instance of type NPanel (e.g. x.new A() where x is an instance of NPanel).
java中出错进行长时间调试尝试后的总结:(跟踪断点调查,很重要。。。。)
1.JComboBox控件的响应事件调试感想:
JComboBox有两个响应事件,(VC里面很多个,非常人性化主义),所以只要别的事件或者函数对combobox进行添加,清空删除等操作,都会自动调用这个combobox的响应事件,这个有些时候会非常的麻烦,对里面定义的list,vector等越界经常会出错。(感受很深啊,调试了一天啊一天啊),所以要注意这几个变量和combobox添加数据的顺序(先添加数据,后对combobox添加),有必要的,要在combobox响应事件函数中进行变量或者控件的大小,选择项等进行判断。
addActionListener(new ActionListener())
addItemListener(new ItemListener())
2.JCTable鼠标响应事件配合自定义弹出对话框
当一个JDialog要在多处被利用,并且每次被利用的时候要获得值或者功能不一样的时候,最好不要在调用该对话框的具体对象事例处重写okbt.addActionListener(new ActionListener())。尽量在JDialog自身添加okbt.addActionListener(new ActionListener()),在具体对象处进行传值的结果处理。
1.根据屏幕设置框架大小
Toolkit kit=Toolkit.getDefaultToolkit();
Dimension screenSize=kit.getScreenSize();
int h=screenSize.height;
int w=screenSize.width;
setSize(w/2,h/2);
1.2框架中的关闭按钮激活
Frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
2.1按钮控件
panel =new JPanel();
JButton openbt=new JButton("打开配置文件");
openbt.setIcon(new ImageIcon("./open.GIF"));//按钮上添加图标
panel.add(openbt);
add(panel,BorderLayout.WEST);
actforme yact=new actforme(Color.yellow); //控件事件响应
openbt.addActionListener(yact);
private class actforme implements ActionListener
{
public actforme(Color cc)
{
c=cc;
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
panel.setBackground(c);
}
private Color c;
}
2.2控件消息响应的匿名类法
openbt.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
panelnew.setBackground(Color.cyan);
}
}
);
2.3JList控件
JList有多种构造器,例如:1.用Vector做参数进行构造JList.
2.用模型构造DefaultListModel model = new DefaultListModel();
model.addElement(str);……
m_list.setModel(model);
2.4JTextField文本控件修改相应事件//当修改文本的希望对话框能做出事件响应
m_strFilter.getDocument().addDocumentListener(new DocumentListener(){
public void changedUpdate(DocumentEvent e) {
// TODO Auto-generated method stub
}
public void insertUpdate(DocumentEvent e) {
// TODO Auto-generated method stub
}
public void removeUpdate(DocumentEvent e) {
// TODO Auto-generated method stub
}
});
3.1树形控件结点建立
DefaultMutableTreeNode root=new DefaultMutableTreeNode("word"); //实体节点类
DefaultMutableTreeNode country=new DefaultMutableTreeNode("country");
root.add(country);
JTree tree =new JTree(root);
add(new JScrollPane(tree));
3.2树形控件的建立
TreeNode root=maketree(); //maketree()建立结点
DefaultTreeModel model=new DefaultTreeModel(root); //用根结点建立树模型
JTree tree =new JTree(model);
//通过模型传递给JTree构造器,或者直接JTree tree =new JTree(root);使用默认树模型
tree.setEditable(true); //结点可编辑
JScrollPane panel1 =new JScrollPane(tree);
add(panel1,BorderLayout.CENTER);
3.3树形控件中选择的节点
TreePath selectionPath=tree.getSelectionPath(); //返回被选择节点的路径(从树根开始到该节点)
DefaultMutableTreeNode selectNode=(DefaultMutableTreeNode)selectionPath.getLastPathComponent();
//获得该路径中的最后一个节点
//更方便的方法是:
DefaultMutableTreeNode node=(DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
3.4为树中选中的节点添加兄弟节点,放置在最后一个。
model.insertNodeInto(newNode,parent,parent.getIndex(selectNode)+1);
//同理添加孩子节点
model.insertNodeInto(newNode,selectNode,selectNode.getChildCount());
//删除节点
model.removeNodeFromParent(selectNode);
//显示新加入的节点
TreeNodenodesmodel.getPathToRoot(newNode);
TreePath path=new TreePath(nodes);
tree.scrollPathToVisible(path);
//makeVisible(path)通过一个树路径让某个节点变成可见
//如果树是防止在滚动面板里面,则用scrollPathToVisible(path)
3.5//为每个节点绑定一个元素(与树中该节点显示的名字不一样的元素)//此应用用在点击树中不同节点需要作出不同响应时,便可方便的根据此来断定
class TreeType {
public Object[] data;
public TreeType(Object[] data) {
this.data = data;
}
public String toString() {
return data[0].toString(); //根据DefaultMutableTreeNode的属性,此处一定要重写toString方法,表示在树中显示的是结构体中哪一个元素
}
}
private TreeType treeselected=new TreeType(new Object[]{});
DefaultMutableTreeNode root1 = new DefaultMutableTreeNode(new TreeType(new Object[] {"Diana",new Integer(1)}));
DefaultMutableTreeNode selectedNode=(DefaultMutableTreeNode)path.getLastPathComponent();
treeselected=(TreeType) selectedNode.getUserObject();
System.out.print(treeselected.data[1]);
//获得object类型中的整数值Integer.parseInt(selectedNode.data[1].toString());
3.6不要树的根节点(当几个头节点等级相同,但是没有共同根节点的时候)
tree.setRootVisible(false); //不要根节点
tree.putClientProperty("JTree.lineStyle", "Angled"); //设置树显示线条
tree.setShowsRootHandles(true); //设置树把手
panel2.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS ); //一直显垂直滚动条
panel2.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS ); //一直显水平滚动条
3.7树更新
DefaultTreeModel newmodel;
TreeNode root = maketree();
newmodel = new DefaultTreeModel(root);
tree.setModel(newmodel);
tree.updateUI();
4.“打开”文件对话框及其设置
JFileChooser chooser=new JFileChooser();
chooser.setAcceptAllFileFilterUsed(false);//去除“所有文件”过滤器
FileNameExtensionFilter filter=new FileNameExtensionFilter("水电高级应用配置文件(.rscfg)","rscfg");
//只能设置一个过滤器
//如果要设置多个过滤器,第一个表示过滤器显示时候的文字,后面都是过滤的后缀名
FileNameExtensionFilter filter1=new FileNameExtensionFilter("图像文件","img","jpg","ico");
chooser.addChoosableFileFilter(filter1);
chooser.setFileFilter(filter);
chooser.setCurrentDirectory(new File("D:\\VC编译环境20091213\\debug\\RSTEMP")); //文件对话框默认文件夹
chooser.setSelectedFile(new File("RSConfigure.rscfg")); //默认选择文件
int result=chooser.showOpenDialog(CFrame.this); //显示对话框,需要提供父组件
if(result==JFileChooser.APPROVE_OPTION) //如果选择OK
{
String name=chooser.getSelectedFile().getPath();
}
5.
//java设置和vc中GroupBox控件一样的功能(TitleBorder???)
panel1.setBorder(BorderFactory.createTitledBorder("124356"));
5.1 GridBagLayout布局器(最复杂布局)
Container panel=getContentPane();
GridBagLayout layout=new GridBagLayout();
panel.setLayout(layout);
JTextArea txtarea=new JTextArea(10,10);
GridBagConstraints constraints=new GridBagConstraints();
constraints. weightx=100;
constraints. weighty=100;
constraints. gridx=0;
constraints. gridy=0;
constraints. gridwidth=3;
constraints. gridheight=3;
panel.add(txtarea, constraints);
5.2 CardLayout布局模式
p1=new JPanel();
JFrame.getContentPane().add(p1); //JPanel.add(p1);
p1.setLayout(new CardLayout(10,10));
//p1面板中添加10个按钮
for (int i=1;i<=10;i++)
{
p1.add("a"+i,new JButton("第"+i+"个"));
}
//在其他控件的响应事件里面就可以添加这个进行切换
((CardLayout)p1.getLayout()).first(p1);//显示首个
((CardLayout)p1.getLayout()).next(p1);//显示下一个
((CardLayout)p1.getLayout()).previous(p1);//指定显示上一个
((CardLayout)p1.getLayout()).last(p1);//显示末个
((CardLayout)p1.getLayout()).show(p1,"a3");//指定显示第三个
//show(Container parent, String name)翻转到具有指定 name 的组件。如果不存在这样的组件,则不发生任何操作。
6.对话框
6.1
Color cc= JColorChooser.showDialog(Component component, String title, Color initialColor) ; // 颜色选择器对话框
6.2
OptionPane.showConfirmDialog(table,"hello,java","title",JOptionPane.OK_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE);//确认对话框
6.3
Dialog.setModal(true); //对话框设置成模态
6.4自定义对话框传回返回值
//创建的对话框中设置
一.将对话框设置成模态的this.setModal(true);
二.创建返回值函数
public int getresult()
{
setVisible(true); //对话框激活,下面语句不执行
return result; //当对话框消失时,即(setVisible(false))该语句被执行
}
okbtn.addActionListener(new ActionListener()
{
public void actionPerformed(final ActionEvent e) {
result=Integer.parseInt(first.getText());
setVisible(false);
}
});
cancelbtn.addActionListener(new ActionListener()
{
public void actionPerformed(final ActionEvent e) {
result=0;
setVisible(false);
}
});
}
//主窗口调用对话框,并将结果显示在主窗口控件中
if(d==null){
d=new adddialog();
int a=d.getresult();
d.setLocationRelativeTo(null); //居中显示
if(a!=0)
{
text.setText(Integer.toString(d.result));
}
}
7.弹出式菜单,鼠标左键坐标
7.1
//JScrollPane panel3 = new JScrollPane(table);
//this.add(panel3, BorderLayout.EAST);
JPopupMenu popup=new JPopupMenu();
JMenuItem item=new JMenuItem("添加");
popup.add(item);
item=new JMenuItem("删除");
popup.add(item);
panel3.setComponentPopupMenu(popup);
table.setInheritsPopupMenu(true);
// 一个含有弹出菜单的组件中放置一个组件的情况,这个子组件可以调用setInheritsPopupMenu(true)继承父组件的弹出菜单
//table.setComponentPopupMenu(popup);
//在表格中实现弹出式菜单响应。弹出式触发器是鼠标左键,因此此处不需要在鼠标响应事件中进行判断是否为左键,而只需要直接设置组件的弹出菜单即可。
//缺点是:在试验中,只能在表格区域中的空白处而非表格内,才能有弹出菜单响应。
7.2完整的弹出菜单功能,改正了7.1的缺点。
e.getXOnScreen(), e.getYOnScreen()获得相对与响应addMouseListener的容器的坐标
e.getX(), e.getY()获得相对屏幕坐标
table.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) { //鼠标释放
if(e.getButton()==MouseEvent.BUTTON3){
//popup.setVisible(true);
popup.show(table, e.getX(),e.getY());
}
}
public void mousePressed(MouseEvent e) { //鼠标按下
final JCCellPosition cp = table.XYToCell(e.getX(), e.getY());
if(e.getButton()==MouseEvent.BUTTON3){ //判断是否是鼠标右击
//popup.setLocation(e.getXOnScreen(), e.getYOnScreen());
//popup.setVisible(true);
popup.show(table, e.getX(),e.getY());}
//上述的setvisible只是对弹出菜单的显示,但是当鼠标移动到相应菜单项时,菜单项不能获得焦点。
//show的功能就是对菜单
8.强烈推荐JClass(jcdesktopviews.exe)
8.1JTable里面添加一行数据
通过DefaultTableModel中的addRow进行添加,同理还有删除行,以及对列的操作。AbstractTableModel,TableColumnModel,TableModel,AbstractCellEditor,TableCellEditor,DefaultCellEditor,TableCellRenderer
Vector<String> a = new Vector<String>(4);
a.add(first.getText());
a.add(second.getText());
a.add(third.getText());
a.add(fourth.getText());
evds.addRow(JCTableEnum.MAXINT, null, a); // 在表格中添加一行数据
//为不同列或者行设置宽度
table.setPixelWidth(JCTableEnum.ALL, JCTableEnum.VARIABLE);
table.setPixelHeight(JCTableEnum.ALL, JCTableEnum.VARIABLE);
table.setPixelWidth(2, 40); //为第2列设置宽度
//为表格右击选中一行
table1.setSelectionPolicy(JCTableEnum.SELECT_RANGE); //首先要确定表格能够进行区域选择
table.setRowSelection(cp.row, cp.row); //cp是表哥响应事件中的参数JCCellPosition cp = table.XYToCell(e.getX(), e.getY());
8.2JCTable
evds = new JCEditableVectorDataSource(); //反过来,由JCTable获得JCEditableVectorDataSource是利用:table.getDataSource()
evds.setNumRows(contentArr.size()+1);
evds.setNumColumns(2);
evds.setColumnLabel(0, "项目");
evds.setColumnLabel(1, "是否需要");
table.setSelectionPolicy(JCTableEnum.SELECT_RANGE);
table.setDataSource(evds);
//添加复选框单元格
evds.setCell(1, 1, new Boolean(false));
//添加组合框单元格
private String colors[] = { "yellow", "green", "blue", "orange", "purple","white", "black" };
JCCellStyle comboboxStyle = new JCCellStyle(table.getDefaultCellStyle());
comboboxStyle.setCellEditor(new JCComboBoxCellEditor(colors));
comboboxStyle.setCellRenderer(new JCComboBoxCellRenderer(colors));
table.setCellStyle(JCTableEnum.ALLCELLS, 3, comboboxStyle);
evds.setTableDataItem(colors[3], 3, 3);//设置单元格为组合框中的一个值
//如果添加颜色单元格,可以设置鼠标双击显示颜色对话框等设置
JCCellStyle combStyle = new JCCellStyle(table.getDefaultCellStyle());
combStyle.setBackground(Color.blue);
table.setCellStyle(JCTableEnum.ALLCELLS, 2, combStyle);
//单元格设置获取数值(此处以“是”/“否”为例)
JCCellStyle checkboxStyle = new JCCellStyle(table.getDefaultCellStyle());
checkboxStyle.setCellRenderer(checkboxR);
checkboxStyle.setCellEditor(checkboxE);
table.setCellStyle(JCTableEnum.ALLCELLS, 4, checkboxStyle);
evds.setCell(1, 4, new Boolean(false));
evds.getTableDataItem(1, 1).toString();
8.3表格响应事件
补充:public void mouseExited(MouseEvent e) //该事件表示鼠标离开组件时事件,可用于对表格鼠标修改过后,进行取之和存值等。
table.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON3) {
//popup.setVisible(true);
popup.show(table, e.getX(),e.getY());
}
}
public void mousePressed(MouseEvent e) {
final JCCellPosition cp = table.XYToCell(e.getX(), e.getY());
if (e.getButton() == MouseEvent.BUTTON3) {
if (e.getClickCount() == 1) {
double_click_edit = false;
table.setRowSelection(cp.row, cp.row);
table.setBackground(Color.gray);
//popup.setLocation(e.getXOnScreen(), e.getYOnScreen());
//popup.setVisible(true);
popup.show(table, e.getX(),e.getY());
selectrow = cp.row;
}
}
if (e.getButton() == MouseEvent.BUTTON1) {
//System.out.print(evds.getTableDataItem(1, 1).toString());
if (e.getClickCount() == 2) {
if (cp.column == 2) {
Color cc = JColorChooser.showDialog(table,"W", Color.black);
if (cc != null) {
JCCellStyle cellStyle = new JCCellStyle();
cellStyle.setBackground(cc);
table.setCellStyle(cp.row, cp.column,cellStyle);
}
double_click_edit = false;
} else if (cp.column != 2) {
double_click_edit =true;
table.beginEdit(cp.row, cp.column);
}
}
else if(e.getClickCount() == 1)
{
double_click_edit =false;
popup.setVisible(false);
}
}
}
});
9.java中整型转字符型
Integer.toString(n);
StringValuOf(n);
字符型转整型
Integer.parseInt
10.java中嵌入html语言(优点:文档美观)
private static String INSTRUCTIONS =
"<html>Customize the editor/renderer for a column by:<br>" +
"<ol>" +
"<li>Selecting an editor/renderer pair from the list at left</li>" +
"<li>Selecting a target:" +
"<ul>" +
"<li>Clicking on a column header assigns the editor/renderer pair to the column</li>" +
"<li>Selecting a cell range assigns the editor/render pair to the cells in the range</li>" +
"</ul></li>" +
"</ol>" +
"If you let the mouse dwell over a cell, a tool tip will show " +
"the current editor/renderer pair for the cell.";
JLabel p = new JLabel(INSTRUCTIONS);//文本显示
11.读写文件对象流和序列化
ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("2.txt"));
Sclass c2=new Sclass("小红",25,"爬山");
out.writeObject(c2);
out.close();
ObjectInputStream in=new ObjectInputStream(new FileInputStream("2.txt"));
Sclass cl=(Sclass)in.readObject();
System.out.println(cl.name);
System.out.println(cl.ege);
System.out.println(cl.special);
in.close();
其中Sclass类必须实现Serializable接口
public static class Sclass implements Serializable {
public Sclass(String n, int e, String s) {
name=n;
ege=e;
special=s;
}
public String name;
public int ege;
public String special;
}
}
12.Map,HashMap,LinkedHashMap,List,Vector
Vector<Integer> v=Vector<Integer>
Map是无序的,LinkedHashMap是有序的
Map<String,String> m=new LinkedHashMap<String,String>();
Set<Map.Entry<String,String>> set=m.entrySet();
Iterator<Map.Entry<String,String>> it=m.entrySet().iterator();
Map.Entry<String,String> enter=it.next();
while(it.hasNext())
{
System.out.println(enter.getKey()+" "+enter.getValue());
enter=it.next();
}
List<Stru_TreeParam> m_treeParams = new ArrayList<Stru_TreeParam>()
不能用List和Map初始化,必须是HashMap和ArraryList,因为List和Map只是个接口。
13.String.format
String str="";
str=String.format("%1$s(%2$d)",Name,Id);
14.将object数值整体转化为字符串
String[] m_selStationCSIDS;
Object[] values=m_listStation.getSelectedValues();
int len=values.length;
m_selStationCSIDS=new String[len];
System.arraycopy(values,0,m_selStationCSIDS, 0,len);
15.屏幕输出
Scanner s=new Scanner(System.in); //要想通过控制台进行输入,首先需要构造一个Scanner对象与“System.in”关联
int a=s.nextInt();
String str=(a==0)?"is 0":(a==1?"is 1":"is 2"); //三个条件判断
- JAVA SWING学习总结
- java swing 项目总结
- java swing总结
- java Swing常见问题总结
- Java实用经验Swing总结
- Java Swing开发知识总结
- Java Swing 总结应注意的问题
- Java Swing 总结应注意的问题
- java swing下JComoponent的特性--总结
- Java Swing的一些技巧总结
- 对Java 中Swing的小总结
- java swing 开发中的一些坑总结
- Swing总结
- java画图总结之一 java.awt和javax.swing
- Java Swing
- java-swing
- JAVA SWING
- java swing
- Socket网络编程学习笔记(2):面向连接的Socket
- hdu 5137 2014ACM/ICPC亚洲区广州站K 最短路
- Thread类的join方法使用
- nyoj32组合数(DFS)
- 10种方法使你的IE如现代浏览器一般
- java swing总结
- JDBC: DAO&VO
- 单词查找树的实现
- 10个200万的网络监控摄像机应该配置百兆还是千兆的交换机?
- jsp与service
- 《c++ primer》第10章 泛型算法 学习笔记
- Android双向滑动菜单
- 2.3 寻找发帖水王
- [BZOJ 1103][POI 2007]大都市(DFS求拓扑序+树状数组)