자바 맵 집합 2 급 연동 예제 실현
사고 분석:
1.전국(성,직할시,자치구)맵 집합,즉 링크 드 HashMap 대상 을 만 들 고 맵 인터페이스의 put()방법 으로 집합 에 지정 한 성과 도시 의 맵 관 계 를 추가 합 니 다.그 중에서 값 은 String 형 1 차원 배열 입 니 다.
코드 는 다음 과 같 습 니 다:
CityMap.java
import java.util.LinkedHashMap;
import java.util.Map;
public class CityMap {
    /**
     *   ( ,   ,   )    
     */
    public static Map<String,String[]> model=new LinkedHashMap<String, String[]>();
    static{
        model.put("  ", new String[]{"  "});
        model.put("  ", new String[]{"  "});
        model.put("  ", new String[]{"  "});
        model.put("  ", new String[]{"  "});
        model.put("   ", new String[]{"   ","    ","   ","  ","  ","   ","  ","  ","   ","   ","  ","  ","    "});
        model.put("  ", new String[]{"  ","  ","  ","  ","  ","  ","  ","  ","  ","  "});
        model.put("  ", new String[]{"  ","  ","   ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  "});
        model.put("   ", new String[]{"    ","    ","    ","  ","  ","   ","  ","    ","  "});
        model.put("  ", new String[]{"   ","  ","   ","  ","  ","  ","  ","  ","  ","  ","   "});
        model.put("  ", new String[]{"  ","  ","  ","   ","  ","  ","  ","  ","  ","  ","  ","   ","  ","  ","  ","  ","   "});
        model.put("  ", new String[]{"  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  "});
        model.put("  ", new String[]{"  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  "});
        model.put("  ", new String[]{"  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","   ","  ","  ","  "});
        model.put("  ", new String[]{"  ","  ","  ","  ","  ","  ","   ","  ","  ","  ","  ","  ","  ","  ","  ","  "});
        model.put("  ", new String[]{"  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  "});
        model.put("  ", new String[]{"  ","  ","  ","   ","  "});
        model.put("  ", new String[]{"  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  "});
        model.put("  ", new String[]{"  ","  ","  ","  ","  ","  ","  ","  "});
        model.put("  ", new String[]{"  ","  ","  ","  ","  ","   ","  ","  ","  ","  ","  ","  ","  ","  "});
        model.put("  ", new String[]{"  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","   "});
        model.put("  ", new String[]{"  ","  ","  ","  ","  ","  ","   ","  ","  ","  ","  ","  "});
        model.put("  ", new String[]{"  ","  ","  ","  ","  ","  ","  ","  ","  ","   ","  "});
        model.put("  ", new String[]{"  ","  ","  ","  ","  ","  ","  ","  ","  "});
        model.put("  ", new String[]{"  ","  ","  ","  ","  ","   ","  ","  ","  "});
        model.put("  ", new String[]{"  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","   ","  ","  ","  ","   ","  ","  ","  ","  ","  ","  "});
        model.put("  ", new String[]{"  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  "});
        model.put("  ", new String[]{"  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","   ","  ","  ","  ","  ","  "});
        model.put("  ", new String[]{"  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  ","  "});
        model.put("  ", new String[]{"  ","  ","  ","  ","  ","  "});
        model.put("  ", new String[]{"    ","   ","   ","  ","  ","  ","  ","    ","   ","  ","   ","   ","  "});
    }
}
2.성 을 가 져 오 는 방법 을 정의 하고 맵 집합 을 만 듭 니 다.이전 단계 에 얻 은 맵 집합 을 할당 합 니 다.맵 집합 키 set()방법 으로 이 집합 에 있 는 모든 키 대상 으로 구 성 된 set 집합 을 가 져 옵 니 다.즉,성 분 집합 입 니 다.Object 형 1 차원 배열 을 만 들 고 set 인터페이스의 toArray()방법 으로 set 집합 을 배열 로 변환 합 니 다.이 배열 을 성 으로 되 돌려 드 롭 다운 목록 의 매개 변 수 를 선택 하 십시오.3.JComboBox 류 의 setModel()방법 을 사용 하여 성 드 롭 다운 목록 에 성 정 보 를 추가 합 니 다.매개 변 수 는 이전 단계 에서 성 을 얻 는 방법 입 니 다.
4.성에 서 시/현 을 얻 는 방법 에 따라 Map 집합 을 만 들 고 절차 1 에서 얻 은 맵 집합 을 할당 하 며 Map 집합 get()방법 으로 지정 한 키 의 값 을 얻 습 니 다.즉,시/현 집합 으로 String[]형 1 차원 배열 을 만 들 고 시/현 집합 을 이 배열 에 할당 합 니 다.
5.성 드 롭 다운 목록 의 옵션 상태 변경 이 벤트 를 정의 합 니 다.이 이벤트 에서 JComboBox 류 의 getSelected Item()방법 으로 선 택 된 성 을 가 져 옵 니 다.기본 값 은 성 집합 에서 첫 번 째 값 입 니 다.그리고 JComboBox 류 의 removeAllItems()방법 으로 시/현 열 표를 비우 고 선 택 된 성에 따라 시/현 배열 을 가 져 옵 니 다.마지막 으로 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;
    /**
     *     
     */
    public BackgroundPanel() {
        super();
        setOpaque(false);
        setLayout(null);
    }
    /**
     *        
     */
    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);//       
    }
}
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);
        //      / 
        String province=(String)getProvince()[0];
        setTitle("     /          ");
        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) { //         
                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("    :");
        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("  ");
        //
    }
    /**
     *    、   ,   
     * 
     * @return
     */
    public Object[] getProvince() {
        Map<String, String[]> map = CityMap.model;//          Map 
        Set<String> set = map.keySet(); //   Map     ,  Set    
        Object[] province = set.toArray(); //      
        return province; //          
    }
    /**
     *          / 
     * 
     * @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)); //      /     
    }
}
효과 그림:
                이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JPA + QueryDSL 계층형 댓글, 대댓글 구현(2)이번엔 전편에 이어서 계층형 댓글, 대댓글을 다시 리팩토링해볼 예정이다. 이전 게시글에서는 계층형 댓글, 대댓글을 구현은 되었지만 N+1 문제가 있었다. 이번에는 그 N+1 문제를 해결해 볼 것이다. 위의 로직은 이...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.