使用JAVA SWING 实现列表以及列表的滚动条

时间:2023-01-26 22:39:32

import javax.swing.*;
import java.awt.*;
import java.util.Vector;
class MyList{
private JFrame frame = new JFrame("hello world");
private Container cont = frame.getContentPane();
private JList<String> list1 = null;
private JList<String> list2 = null;

public MyList(){
this.frame.setLayout(new GridLayout(1,3));
String nation[] ={"china","usa","japan","corea","dlsj","ldskj","ldsk","lsfjls","lsdfk"};
Vector<String> v = new Vector<String>();//可实现自动增长对象数组

v.add("hi");
v.add("you");
v.add("who");
v.add("are");

this.list1 = new JList<String>(nation);
this.list2 = new JList<String>(v);

this.list1.setBorder(BorderFactory.createTitledBorder("which country do you want to"));
this.list2.setBorder(BorderFactory.createTitledBorder("do you love me"));

this.cont.add(list1);
this.cont.add(list2);

this.cont.add(new JScrollPane(this.list1)); //对list1添加滚动条
this.cont.add(new JScrollPane(this.list2)); //对list2添加滚动条


this.frame.setSize(400,200);
this.frame.setVisible(true);
this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}


public class lalala {
public static void main(String args[]){
new MyList();
}

}


//若是要实现程下拉列表功能则只需将JList更改为用JComboBox实现即可

//若是要实现程下拉列表功能则只需将JList更改为用JComboBox实现即可

/*

用JComboBox

1.有滚动条:

使用JAVA SWING 实现列表以及列表的滚动条


2.无滚动条

使用JAVA SWING 实现列表以及列表的滚动条



用JList:

有无滚动条:

使用JAVA SWING 实现列表以及列表的滚动条


滚动条出现时间:

JTextArea txaDisplay = new JTextArea();
JScrollPane scroll = new JScrollPane(txaDisplay);

//分别设置水平和垂直滚动条自动出现
scroll.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);

//分别设置水平和垂直滚动条总是出现
scroll.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scroll.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

//分别设置水平和垂直滚动条总是隐藏scroll.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scroll.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_NEVER);



*/