2015-10-24 5 views
0

im пытается построить диалог ввода с помощью swt. Я хочу прочитать мои свойства класса и сделать диалоговое окно в указанном порядке или даже лексикографическом порядке. Я сохраню свойства класса в связанном файле hahmap \ treemap.Как я могу читать свойства класса (участников) в лексикографическом порядке на java?

пример:

public class MazeProperties { 


    /** Maze Name. */ 
    private String MazeName; 


    /** Number of rows in maze. */ 
    private int x; 

    /** The Floors. */ 
    private int y; 

    /** Number of columns in maze. */ 
    private int z; 

    public MazeProperties(String mazeName, int rows, int floors, int columns) { 
     MazeName = mazeName; 
     Rows = rows; 
     Floors = floors; 
     Columns = columns; 

} 
public class ClassInputDialog extends Dialog{ 

    /** The shell. */ 
    Shell shell; 

    /**  the generic class. */ 
    private Class<?> template; 

    /**  Property Descriptors give me the ability to see what properties the class contains - and has generic functionalities for setters and getters for fields!. */ 
    PropertyDescriptor[] descs; 
    /** I wanna have a robust connection between a property to a text box - that way upon pressing OK I could know what class property was written in it. 
    * 
    */ 
    HashMap<PropertyDescriptor,Text> txtMap=new LinkedHashMap<PropertyDescriptor,Text>(); 
    //TreeMap<String,Text> txtMapOrderName=new TreeMap<String,Text>(); 
    //Map<PropertyDescriptor, Text> txtMap = Collections.synchronizedMap(new LinkedHashMap<PropertyDescriptor, Text>()); 
    /** The bonus demanded that this dialog will support all given classes 
    * but what happens when a class has an enum? a whole new story with combo-boxes and once again I wanna have a connection between the class field enum to the String that was selected in the form. 
    * 
    */ 
    HashMap<PropertyDescriptor,String> enumMap=new **HashMap<PropertyDescriptor,String>();** 

     /** This is the reference of the instance I will return. 
    * 
    */ 
    private Object input; 

     /** Ct'r for people that don't know a thing about SWT. 
    * @param parent - Shell 
    * @param template - The Class to create form to 
    */ 
    public ClassInputDialog(Shell parent,Class<?> template) { 
      this(parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL,template); 
      } 

     /** 
    * Ct'r with SWT style. 
    * 
    * @param parent - Shell 
    * @param style - SWT style 
    * @param template - The Class to create form to 
    */ 
    public ClassInputDialog(Shell parent, int style,Class<?> template) { 
     super(parent, style); 
     this.template=template; 
     descs=PropertyUtils.getPropertyDescriptors(template); 
     setText("Set Properties"); 
     } 


     /** 
    * Gets the input. 
    * 
    * @return the input 
    */ 
    public Object getInput() { 
     return input; 
     } 

     /** 
    * Sets the input. 
    * 
    * @param input the new input 
    */ 
    public void setInput(Object input) { 
     this.input = input; 
     } 

     /** Here the window layout is set and the main loop event happens. When window closes User's input is returned. 
    * @return The user's input 
    */ 
    public Object open() { 
     this.shell = new Shell(getParent(), getStyle()); 
     shell.setText(getText()); 
     createContents(shell); 
     shell.pack(); 
     shell.open(); 
     Display display = getParent().getDisplay(); 
     while (!shell.isDisposed()) { 
      if (!display.readAndDispatch()) { 
      display.sleep(); 
      } 
     } 
     //display.dispose(); 
     return input; 
     } 

     /** Creates Window content and layout - sets Labels, Text boxes and combo boxes nicely. 
    * @param shell - window's parent 
    */ 
    private void createContents(final Shell shell) { 
     shell.setLayout(new GridLayout(2, true)); 
     for(**PropertyDescriptor propDesc: descs**) 
      if(!propDesc.getName().equals("class")) 
      { 
       if(!propDesc.getPropertyType().isEnum()) 
       { 
        Label label = new Label(shell, SWT.NONE); 
        label.setText(propDesc.getName()); 
        GridData data = new GridData(); 
        data.horizontalSpan = 2; 
        label.setLayoutData(data); 

        final Text text = new Text(shell, SWT.BORDER); 
        data = new GridData(GridData.FILL_HORIZONTAL); 
        data.horizontalSpan = 2; 
        text.setLayoutData(data); 
        txtMap.put(propDesc, text); 
        // txtMapOrderName.put(propDesc.getDisplayName(), text); 


        System.out.println(propDesc.getDisplayName()); 
       } 
       else 
       { 
        Label label = new Label(shell, SWT.NONE); 
        label.setText(propDesc.getName()); 
        GridData data = new GridData(); 
        data.horizontalSpan = 2; 
        label.setLayoutData(data); 

        final Combo combo = new Combo(shell, SWT.DROP_DOWN); 

        String[] toCombo=new String[propDesc.getPropertyType().getEnumConstants().length]; 
        for(int i=0;i<propDesc.getPropertyType().getEnumConstants().length;i++) 
         toCombo[i]=propDesc.getPropertyType().getEnumConstants()[i].toString(); 
        combo.setItems(toCombo); 
        data = new GridData(GridData.FILL_HORIZONTAL); 
        data.horizontalSpan = 2; 
        combo.setLayoutData(data); 
        combo.addSelectionListener(new SelectionListener() { 

         @Override 
         public void widgetSelected(SelectionEvent arg0) { 
          enumMap.put(propDesc, combo.getText()); 
         } 

         @Override 
         public void widgetDefaultSelected(SelectionEvent arg0) { 


         } 
        }); 

       } 

      } 

выход не как заказать свойства класса, это что-то вроде

y 
mazeName 
x 
z 
+0

Что делает двойной синтаксис '**' в вашем коде? Я не похож на стандартный [tag: javascript] для меня. – Eric

+1

его ошибка моего плагина javadoc, обрабатывайте его без **, его просто регулярного члена. btw, его java не javascript. –

+0

отредактируйте ваше сообщение, чтобы исправить это – Eric

ответ

0

Если вы хотите отобразить ключи значений в детерминированной, предсказуемый порядок, вы должны хранить их в TreeMap, следя за тем, чтобы класс ключей реализовал Comparator. Если это не так, вы должны реализовать свой собственный Comparator и передать его в качестве параметра в конструктор TreeMap.

В вашем случае, если вы хотите, чтобы PropertyDescriptor в качестве ключа, вы должны реализовать свой собственный Comparator, чтобы сравнить PropertyDescriptor объектов.

 Смежные вопросы

  • Нет связанных вопросов^_^