JAVA 点击按钮展开一个新的Jpanel

     问题不太容易用语言来描述,先直接上图吧:

     点击按钮之前:
 
点击按钮之后:

 

那么如何实现这种功能呢?首先在图一中的主JFrame中添加一个JScrollPane,在点击按钮后new一个新的Jpanel,然后让原来的JScrollPane在这个新的Jpanel上 创建一个视口(如果有必要)并设置其视图。即调用 setViewportView ( Component  view)
方法。

public void init() {
 this.setBounds(200,30,1000,750);
  this.setResizable(false);
  this.setLayout(null);

  final JScrollPane scrollPane = new JScrollPane();
  scrollPane.setBounds(0,62,1000,690);
  this.add(scrollPane);
  btnAdd = new JButton();
  btnAdd.setText("ADD");
  btnAdd.setBounds(0, 0, 74, 26);
  btnAdd.addActionListener(this);
  this.add(btnAdd);
 
  setVisible(true);
 }

 public void actionPerformed(ActionEvent e) {
  
   final JPanel p1 = new JPanel();
scroll.setViewportView(p1);
p1.setLayout(null);
DefaultListModel model1 = new DefaultListModel();
model1.addElement("点击选中");
JList list1 = new JList(model1);
// 列表显示20行,超过20行后显示滚动条
list1.setVisibleRowCount(20);
// 单选模式
list1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane ScrollPane1 = new JScrollPane(list1);
ScrollPane1.setBounds(0,0,480,680);
ScrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
   p1.add(ScrollPane1);
   
   final DefaultListModel model2 = new DefaultListModel();
   model2.addElement("点击删除");
   final JList list2 = new JList(model2);
   // 列表显示20行,超过20行后显示滚动条
list2.setVisibleRowCount(20);
// 单选模式
list2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane ScrollPane2 = new JScrollPane(list2);
ScrollPane2.setBounds(510,0,480,600);
ScrollPane2.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
   p1.add(ScrollPane2);
   
   list1.addMouseListener(new MouseAdapter() {

@Override
public void mouseClicked(MouseEvent event) {
JList source = (JList) event.getSource();
String value = (String) source.getSelectedValue();
value = value.substring(0,value.indexOf("-"));
model2.addElement(value);
}
   });
   
   list2.addMouseListener(new MouseAdapter() {

@Override
public void mouseClicked(MouseEvent event) {
JList source = (JList) event.getSource();
Object selectedValue = source.getSelectedValue();
model2.removeElement(selectedValue);
}
   });
   JButton enterButton = new JButton("确定保存");
   JButton canselButton = new JButton("取消");
   enterButton.setBounds(600,610,120,40);
   canselButton.setBounds(850,610,100,40);
   canselButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
p1.setVisible(false);
}
});
   enterButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
int count = model2.getSize();
for(int i=0; i
System.out.println(model2.get(i));
}
});
   p1.add(enterButton);
   p1.add(canselButton);
  
 }

你可能感兴趣的:(JAVA)