日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

java动态添加组件_有关Java Swing动态增加组件

發(fā)布時間:2025/4/16 75 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java动态添加组件_有关Java Swing动态增加组件 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

展開全部

效果圖

參考代碼import?java.awt.*;

import?java.awt.event.*;

import?javax.swing.*;

//本類繼承自JFrame?實現(xiàn)了?ActionListener接口

public?class?DemoFrame1?extends?JFrame?implements?ActionListener??{

JPanel?jpc?;//存放組件的面板

JScrollPane?jsp;//滾動面板

JButton?jbAdd?,jbRemove,jbReset;//?增加,刪除按62616964757a686964616fe4b893e5b19e31333365633932鈕

int?index?=?1;//開始的字符

//構造函數(shù)

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函數(shù)

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的組件數(shù)量

jpc.remove(jpc.getComponentCount()-1);//刪除末尾的一個組件?,

index-=1;

myUpdateUI();

}

}else?if(jb==jbReset)?{

for?(int?i?=?0;?i?

MyJPanel?mjp?=?(MyJPanel)?jpc.getComponent(i);

//也就是說取值,可以根據(jù)文本框所在的位置來取

System.out.println("第"+(i+1)+"個文本框的值是"+mjp.getJTFValue());

mjp.setJTFValue("");//清空,重置

System.out.println("第"+(i+1)+"個文本框的值已清空重置");

}

}

}

//刷新界面函數(shù)

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);

}

}

總結(jié)

以上是生活随笔為你收集整理的java动态添加组件_有关Java Swing动态增加组件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。