Java Swing-10 Swing实例08Jlist
程序员文章站
2024-02-02 12:30:40
...
- [ 声明] 学习笔记和代码均参考自徐彤老师(ITFlight)的视频
package demo08;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JList;
public class Demo1 extends JFrame{
String value[]= {"Aaa","B","Ccccc","D"};
JList list=new JList(value);
public Demo1() {
setSize(500,500);
this.setLayout(new FlowLayout());
add(list);
setVisible(true);
}
public static void main(String[] args) {
new Demo1();
}
}
package demo08;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class Demo2 extends JFrame{
String value[]= {"Aaa","B","Ccccc","D"};
JList list=new JList(value);
public Demo2() {
setSize(500,500);
this.setLayout(new FlowLayout());
add(list);
list.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
// String str=(String)list.getSelectedValue();
// System.out.println(str);
int x=list.getSelectedIndex();
System.out.println(value[x]);
}
});
setVisible(true);
}
public static void main(String[] args) {
new Demo2();
}
}
package demo08;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Enumeration;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JTextField;
public class Demo3 extends JFrame implements ActionListener{
JButton button1=new JButton("add");
JButton button2=new JButton("delete");
JButton button3=new JButton("update");
JButton button4=new JButton("select");
JTextField tf=new JTextField(30);
Vector value=new Vector();
JList list=new JList(value);
public Demo3() {
setSize(500,500);
value.add("111");
value.add("222");
value.add("333");
value.add("444");
this.setLayout(new FlowLayout());
add(list);
add(button1);
add(button2);
add(button3);
add(button4);
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
button4.addActionListener(this);
add(tf);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==button1) {
value.add("xxx");
list.updateUI();
}
else if(e.getSource()==button2) {
int index=list.getSelectedIndex();//找到点击的第几个元素
value.remove(index);
list.updateUI(); //在操作之后更新界面
}
else if(e.getSource()==button3) {
int index=list.getSelectedIndex();
value.remove(index);
value.add("000");
list.updateUI();
}
else if(e.getSource()==button4) {
Object o[]=list.getSelectedValues();
for (int i = 0; i < o.length; i++) {
System.out.println(o[i]);
}
Enumeration e2=value.elements();
while(e2.hasMoreElements()) {
tf.setText(tf.getText()+e2.nextElement());
}
}
}
public static void main(String[] args) {
new Demo3();
}
}
上一篇: 环形进度条(jQuery,canvas)