在这里我向您展示从以下位置转移城市名称的示例list
to list_1
。您将收到如下输出:
代码是:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.DefaultListModel;
import java.awt.Font;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class ListTransfer {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ListTransfer window = new ListTransfer();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ListTransfer() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
String[] values = new String[] {"Surat", "Ahmedabad", "Vadodra", "Anand", "Bharuch", "Maninagar", "Mumbai", "Pune", "Hydrabad", "Banglore"};
DefaultListModel<Object> model_list = new DefaultListModel<Object>();
DefaultListModel<Object> model_list_1 = new DefaultListModel<Object>();
for (String value : values) {
model_list.addElement(value);
}
JList<Object> list = new JList<Object>();
list.setFont(new Font("Lucida Grande", Font.PLAIN, 21));
list.setBounds(17, 41, 174, 194);
list.setModel(model_list);
JScrollPane listScroller = new JScrollPane();
listScroller.setLocation(15, 43);
listScroller.setSize(174, 194);
listScroller.setViewportView(list);
list.setLayoutOrientation(JList.VERTICAL);
frame.getContentPane().add(listScroller);
JList<Object> list_1 = new JList<Object>();
list_1.setFont(new Font("Lucida Grande", Font.PLAIN, 21));
list_1.setBounds(262, 41, 174, 194);
list_1.setModel(model_list_1);
JScrollPane listScroller1 = new JScrollPane();
listScroller1.setLocation(262, 41);
listScroller1.setSize(174, 194);
listScroller1.setViewportView(list_1);
list_1.setLayoutOrientation(JList.VERTICAL);
frame.getContentPane().add(listScroller1);
JButton shiftbutton = new JButton(">>>");
shiftbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
list.getSelectedValuesList().stream().forEach((data) -> {
model_list_1.addElement(data);
model_list.removeElement(data);
});
}
});
shiftbutton.setBounds(192, 116, 66, 52);
frame.getContentPane().add(shiftbutton);
}
}