java动态添加组件_有关Java Swing动态增加组件
展開全部
效果圖
參考代碼import?java.awt.*;
import?java.awt.event.*;
import?javax.swing.*;
//本類繼承自JFrame?實現了?ActionListener接口
public?class?DemoFrame1?extends?JFrame?implements?ActionListener??{
JPanel?jpc?;//存放組件的面板
JScrollPane?jsp;//滾動面板
JButton?jbAdd?,jbRemove,jbReset;//?增加,刪除按62616964757a686964616fe4b893e5b19e31333365633932鈕
int?index?=?1;//開始的字符
//構造函數
public?DemoFrame1()?{
jpc?=?new?JPanel();
jpc.setLayout(new?BoxLayout(jpc,??BoxLayout.Y_AXIS));//盒子布局.從上到下
jsp?=?new?JScrollPane(jpc,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
add(jsp);
jbAdd?=?new?JButton("增加");
jbAdd.addActionListener(this);
jbRemove?=?new?JButton("刪除");
jbRemove.addActionListener(this);
jbReset?=?new?JButton("重置");
jbReset.addActionListener(this);
JPanel?jps?=?new?JPanel();
jps.add(jbAdd);
jps.add(jbRemove);
jps.add(jbReset);
add(jps,BorderLayout.SOUTH);
setTitle("增刪組件");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300,?220);//大小
setLocationRelativeTo(null);//居中
}
//main函數
public?static?void?main(String[]?args)?{
new?DemoFrame1().setVisible(true);//初始化并可見
}
@Override
public?void?actionPerformed(ActionEvent?e)?{
JButton?jb?=?(JButton)?e.getSource();
if(jb==jbAdd)?{//當點擊添加按鈕時
jpc.add(new?MyJPanel(index));//添加1個自己定義的面板組件
index++;//自加1
myUpdateUI();//刷新界面
}else?if(jb?==jbRemove)?{//當點擊刪除按鈕時
if(jpc.getComponentCount()>0)?{?//?得到jpc里的MyJPanel的組件數量
jpc.remove(jpc.getComponentCount()-1);//刪除末尾的一個組件?,
index-=1;
myUpdateUI();
}
}else?if(jb==jbReset)?{
for?(int?i?=?0;?i?
MyJPanel?mjp?=?(MyJPanel)?jpc.getComponent(i);
//也就是說取值,可以根據文本框所在的位置來取
System.out.println("第"+(i+1)+"個文本框的值是"+mjp.getJTFValue());
mjp.setJTFValue("");//清空,重置
System.out.println("第"+(i+1)+"個文本框的值已清空重置");
}
}
}
//刷新界面函數
private?void?myUpdateUI()?{
SwingUtilities.updateComponentTreeUI(this);//添加或刪除組件后,更新窗口
JScrollBar?jsb?=?jsp.getVerticalScrollBar();//得到垂直滾動條
jsb.setValue(jsb.getMaximum());//把滾動條位置設置到最下面
}
}
//自定義一個JPanle類
class?MyJPanel?extends?JPanel{
public?JTextField?jtf;
public?MyJPanel(int?index)?{
JLabel?jl?=?new?JLabel("字符"+index);
jtf?=?new?JTextField(15);
add(jl);
add(jtf);
}
//獲取文本框的值
public?String?getJTFValue()?{
return?jtf.getText();
}
//設置文本框的值
public?void?setJTFValue(String?value)?{
jtf.setText(value);
}
}
總結
以上是生活随笔為你收集整理的java动态添加组件_有关Java Swing动态增加组件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java dayofweek_Java
- 下一篇: java 消息队列_java消息队列