Java實(shí)現(xiàn)Map集合二級(jí)聯(lián)動(dòng)示例
Map集合可以保存鍵值映射關(guān)系,這非常適合本實(shí)例所需要的數(shù)據(jù)結(jié)構(gòu),所有省份信息可以保存為Map集合的鍵,而每個(gè)鍵可以保存對(duì)應(yīng)的城市信息,本實(shí)例就是利用Map集合實(shí)現(xiàn)了省市級(jí)聯(lián)選擇框,當(dāng)選擇省份信息時(shí),將改變城市下拉選擇框?qū)?yīng)的內(nèi)容。
思路分析:
1. 創(chuàng)建全國(省,直轄市,自治區(qū))映射集合,即LinkedHashMap對(duì)象,使用Map接口的put()方法向集合中添加指定的省與城市的映射關(guān)系,其中值為String型一維數(shù)組。
2. 定義獲取省份的方法,創(chuàng)建一個(gè)Map集合,將上一步得到的映射集合賦值給它,使用Map集合的keySet()方法獲取該集合中的所有鍵對(duì)象組成的Set集合,即為省分集合,創(chuàng)建一個(gè)Object型一維數(shù)組,使用Set接口的toArray()方法將Set集合轉(zhuǎn)換為數(shù)組,返回此數(shù)組作為省份選擇下拉列表的參數(shù)。
3. 使用JComboBox類的setModel()方法為省份下拉列表添加省份信息,參數(shù)即為上一步中的獲取省份方法。
4. 定義根據(jù)省份獲取市/縣的方法,創(chuàng)建一個(gè)Map集合,將步驟1中得到的映射集合賦值給它,使用Map集合的get()方法獲取指定鍵的值,即為市/縣集合,創(chuàng)建一個(gè)String[]型一維數(shù)組,將市/縣集合賦值給該數(shù)組。
5. 定義省份下拉列表的選項(xiàng)狀態(tài)更改事件,在該事件中通過JComboBox類的getSelectedItem()方法獲取選中的省份,默認(rèn)為省份集合中的第一個(gè)值,然后使用JComboBox類的removeAllItems()方法清空市/縣列表,根據(jù)選中的省份獲取市/縣數(shù)組,最后使用JComboBox的setModel()方法重新添加市/縣列表的值。
代碼如下:
BackgroundPanel.java
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JPanel;
/**
* 帶背景的面板組件
*
* @author ZhongWei Lee
*/
public class BackgroundPanel extends JPanel {
/**
*
*/
private static final long serialVersionUID = 7758689434195492602L;
/**
* 背景圖片
*/
private Image image;
/**
* 構(gòu)造方法
*/
public BackgroundPanel() {
super();
setOpaque(false);
setLayout(null);
}
/**
* 設(shè)置圖片的方法
*/
public void setImage(Image image) {
this.image = image;
}
@Override
protected void paintComponent(Graphics g) {// 重寫繪制組件外觀
if (image != null) {
int width = getWidth();// 獲取組件大小
int height = getHeight();
g.drawImage(image, 0, 0, width, height, this);// 繪制圖片與組件大小相同
}
super.paintComponent(g);// 執(zhí)行超類方法
}
}
SwingResourceManager.java
import java.awt.Image;
import java.awt.Toolkit;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import javax.swing.ImageIcon;
/**
* Utility class for managing resources such as colors, fonts, images, etc.
*
* This class may be freely distributed as part of any application or plugin.
* <p>
* Copyright (c) 2003 - 2004, Instantiations, Inc. <br>All Rights Reserved
*
* @author scheglov_ke
*/
public class SwingResourceManager {
/**
* Maps image names to images
*/
private static HashMap<String, Image> m_ClassImageMap = new HashMap<String, Image>();
/**
* Returns an image encoded by the specified input stream
* @param is InputStream The input stream encoding the image data
* @return Image The image encoded by the specified input stream
*/
private static Image getImage(InputStream is) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte buf[] = new byte[1024 * 4];
while (true) {
int n = is.read(buf);
if (n == -1)
break;
baos.write(buf, 0, n);
}
baos.close();
return Toolkit.getDefaultToolkit().createImage(baos.toByteArray());
} catch (Throwable e) {
return null;
}
}
/**
* Returns an image stored in the file at the specified path relative to the specified class
* @param clazz Class The class relative to which to find the image
* @param path String The path to the image file
* @return Image The image stored in the file at the specified path
*/
public static Image getImage(Class<?> clazz, String path) {
String key = clazz.getName() + '|' + path;
Image image = m_ClassImageMap.get(key);
if (image == null) {
if ((path.length() > 0) && (path.charAt(0) == '/')) {
String newPath = path.substring(1, path.length());
image = getImage(new BufferedInputStream(clazz.getClassLoader().getResourceAsStream(newPath)));
} else {
image = getImage(clazz.getResourceAsStream(path));
}
m_ClassImageMap.put(key, image);
}
return image;
}
/**
* Returns an image stored in the file at the specified path
* @param path String The path to the image file
* @return Image The image stored in the file at the specified path
*/
public static Image getImage(String path) {
return getImage("default", path); //$NON-NLS-1$
}
/**
* Returns an image stored in the file at the specified path
* @param section String The storage section in the cache
* @param path String The path to the image file
* @return Image The image stored in the file at the specified path
*/
public static Image getImage(String section, String path) {
String key = section + '|' + SwingResourceManager.class.getName() + '|' + path;
Image image = m_ClassImageMap.get(key);
if (image == null) {
try {
FileInputStream fis = new FileInputStream(path);
image = getImage(fis);
m_ClassImageMap.put(key, image);
fis.close();
} catch (IOException e) {
return null;
}
}
return image;
}
/**
* Clear cached images in specified section
* @param section the section do clear
*/
public static void clearImages(String section) {
for (Iterator<String> I = m_ClassImageMap.keySet().iterator(); I.hasNext();) {
String key = I.next();
if (!key.startsWith(section + '|'))
continue;
Image image = m_ClassImageMap.get(key);
image.flush();
I.remove();
}
}
/**
* Returns an icon stored in the file at the specified path relative to the specified class
* @param clazz Class The class relative to which to find the icon
* @param path String The path to the icon file
* @return Icon The icon stored in the file at the specified path
*/
public static ImageIcon getIcon(Class<?> clazz, String path) {
return getIcon(getImage(clazz, path));
}
/**
* Returns an icon stored in the file at the specified path
* @param path String The path to the icon file
* @return Icon The icon stored in the file at the specified path
*/
public static ImageIcon getIcon(String path) {
return getIcon("default", path); //$NON-NLS-1$
}
/**
* Returns an icon stored in the file at the specified path
* @param section String The storage section in the cache
* @param path String The path to the icon file
* @return Icon The icon stored in the file at the specified path
*/
public static ImageIcon getIcon(String section, String path) {
return getIcon(getImage(section, path));
}
/**
* Returns an icon based on the specified image
* @param image Image The original image
* @return Icon The icon based on the image
*/
public static ImageIcon getIcon(Image image) {
if (image == null)
return null;
return new ImageIcon(image);
}
}
MainFrame.java
import java.awt.EventQueue;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Map;
import java.util.Set;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.border.TitledBorder;
public class MainFrame extends JFrame {
/**
*
*/
private static final long serialVersionUID = -4595347311922711984L;
private JTextField textField_3;
private JTextField textField_1;
private JComboBox comboBox_1;
private JTextField textField;
private JComboBox cityComboBox;
private JComboBox comboBox;
/**
* Launch the application
*
* @param args
*/
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
MainFrame frame = new MainFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame
*/
public MainFrame() {
getContentPane().setLayout(null);
setBounds(100, 100, 518, 379);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//獲取默認(rèn)的市/縣
String province=(String)getProvince()[0];
setTitle("輸入指定省/直轄市查詢對(duì)應(yīng)的市縣");
final BackgroundPanel backgroundPanel = new BackgroundPanel();
backgroundPanel.setImage(SwingResourceManager.getImage(MainFrame.class, "/images/background.jpg"));
backgroundPanel.setBounds(0, 0, 510, 380);
getContentPane().add(backgroundPanel);
final JPanel panel = new JPanel();
panel.setOpaque(false);
panel.setBounds(36, 126, 438, 70);
backgroundPanel.add(panel);
panel.setLayout(null);
panel.setBorder(new TitledBorder(null, "居住地", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, null, null));
cityComboBox = new JComboBox();
cityComboBox.setBounds(245, 25, 124, 27);
panel.add(cityComboBox);
cityComboBox.setModel(new DefaultComboBoxModel(getCity(province)));
comboBox = new JComboBox();
comboBox.setBounds(25, 25, 124, 27);
panel.add(comboBox);
comboBox.addItemListener(new ItemListener() {
public void itemStateChanged(final ItemEvent e) { // 選項(xiàng)狀態(tài)更改事件
itemChange();
}
});
comboBox.setModel(new DefaultComboBoxModel(getProvince())); // 添加省份信息
final JLabel label = new JLabel();
label.setText("省/直轄市");
label.setBounds(155, 30, 66, 18);
panel.add(label);
final JLabel label_1 = new JLabel();
label_1.setText("市/縣");
label_1.setBounds(375, 30, 37, 18);
panel.add(label_1);
final JLabel label_2 = new JLabel();
label_2.setBounds(36, 43, 65, 18);
backgroundPanel.add(label_2);
label_2.setHorizontalAlignment(SwingConstants.RIGHT);
label_2.setHorizontalTextPosition(SwingConstants.LEADING);
label_2.setText("姓 名:");
textField = new JTextField();
textField.setBounds(113, 38, 154, 28);
backgroundPanel.add(textField);
final JLabel label_3 = new JLabel();
label_3.setBounds(36, 84, 65, 18);
backgroundPanel.add(label_3);
label_3.setHorizontalAlignment(SwingConstants.RIGHT);
label_3.setHorizontalTextPosition(SwingConstants.LEADING);
label_3.setText("性 別:");
comboBox_1 = new JComboBox();
comboBox_1.setBounds(113, 81, 66, 25);
backgroundPanel.add(comboBox_1);
comboBox_1.setModel(new DefaultComboBoxModel(new String[] {"男", "女"}));
final JLabel label_4 = new JLabel();
label_4.setBounds(36, 212, 65, 18);
backgroundPanel.add(label_4);
label_4.setHorizontalAlignment(SwingConstants.RIGHT);
label_4.setHorizontalTextPosition(SwingConstants.LEADING);
label_4.setText("詳細(xì)地址:");
textField_1 = new JTextField();
textField_1.setBounds(113, 208, 367, 28);
backgroundPanel.add(textField_1);
final JLabel label_4_1 = new JLabel();
label_4_1.setBounds(36, 252, 65, 18);
backgroundPanel.add(label_4_1);
label_4_1.setHorizontalTextPosition(SwingConstants.LEADING);
label_4_1.setHorizontalAlignment(SwingConstants.RIGHT);
label_4_1.setText("E-mail:");
textField_3 = new JTextField();
textField_3.setBounds(113, 248, 367, 27);
backgroundPanel.add(textField_3);
final JButton button = new JButton();
button.setBounds(159, 289, 75, 28);
backgroundPanel.add(button);
button.setText("保存");
final JButton button_1 = new JButton();
button_1.setBounds(265, 289, 75, 28);
backgroundPanel.add(button_1);
button_1.setText("重置");
//
}
/**
* 獲取省、直轄市,自治區(qū)
*
* @return
*/
public Object[] getProvince() {
Map<String, String[]> map = CityMap.model;// 獲取省份信息保存到Map中
Set<String> set = map.keySet(); // 獲取Map集合中的鍵,并以Set集合返回
Object[] province = set.toArray(); // 轉(zhuǎn)換為數(shù)組
return province; // 返回獲取的省份信息
}
/**
* 獲取指定省對(duì)應(yīng)的市/縣
*
* @param selectProvince
* @return
*/
public String[] getCity(String selectProvince) {
Map<String, String[]> map = CityMap.model; // 獲取省份信息保存到Map中
String[] arrCity = map.get(selectProvince); // 獲取指定鍵的值
return arrCity; // 返回獲取的市/縣
}
private void itemChange() {
String selectProvince = (String) comboBox.getSelectedItem();
cityComboBox.removeAllItems(); // 清空市/縣列表
String[] arrCity = getCity(selectProvince); // 獲取市/縣
cityComboBox.setModel(new DefaultComboBoxModel(arrCity)); // 重新添加市/縣列表的值
}
}
效果如圖:
相關(guān)文章
java中優(yōu)化大量if...else...方法總結(jié)
在我們平時(shí)的開發(fā)過程中,經(jīng)??赡軙?huì)出現(xiàn)大量If else的場景,代碼顯的很臃腫,非常不優(yōu)雅,下面這篇文章主要給大家介紹了關(guān)于java中優(yōu)化大量if...else...方法的相關(guān)資料,需要的朋友可以參考下2023-03-03SpringMVC使用MultipartResolver實(shí)現(xiàn)文件上傳
MultipartResolver 用于處理文件上傳,當(dāng)收到請(qǐng)求時(shí) DispatcherServlet 的 checkMultipart() 方法會(huì)調(diào)用 MultipartResolver 的 isMultipart() 方法判斷請(qǐng)求中是否包含文件2023-02-02詳解Java中使用ImageIO類對(duì)圖片進(jìn)行壓縮的方法
這篇文章主要介紹了Java中使用ImageIO類對(duì)圖片進(jìn)行壓縮的方法,能夠按指定的比例調(diào)整圖片的寬高,需要的朋友可以參考下2016-04-04java錯(cuò)誤:?不支持發(fā)行版本?22的簡單解決方法
這篇文章主要給大家介紹了關(guān)于java錯(cuò)誤:?不支持發(fā)行版本?22的簡單解決方法,這個(gè)錯(cuò)誤通常是由于Java版本不兼容導(dǎo)致的,請(qǐng)檢查您的項(xiàng)目所使用的Java版本是否與您當(dāng)前安裝的Java版本一致,需要的朋友可以參考下2024-06-06Spring?Security內(nèi)置過濾器的維護(hù)方法
這篇文章主要介紹了Spring?Security的內(nèi)置過濾器是如何維護(hù)的,本文給我們分析一下HttpSecurity維護(hù)過濾器的幾個(gè)方法,需要的朋友可以參考下2022-02-02Java Properties簡介_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
Java中有個(gè)比較重要的類Properties(Java.util.Properties),主要用于讀取Java的配置文件,各種語言都有自己所支持的配置文件,配置文件中很多變量是經(jīng)常改變的,這樣做也是為了方便用戶,讓用戶能夠脫離程序本身去修改相關(guān)的變量設(shè)置2017-05-05