Java Code Examples for javax.swing.plaf.basic.BasicComboBoxEditor

The following examples show how to use javax.swing.plaf.basic.BasicComboBoxEditor. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: netbeans   Source File: GenericToolbar.java    License: Apache License 2.0 6 votes vote down vote up
public Dimension getPreferredSize() {
    Dimension dim = super.getPreferredSize();
    if (PREFERRED_HEIGHT == -1) {
        GenericToolbar tb = new GenericToolbar();
        tb.setBorder(getBorder());
        tb.setBorderPainted(isBorderPainted());
        tb.setRollover(isRollover());
        tb.setFloatable(isFloatable());
        Icon icon = Icons.getIcon(GeneralIcons.SAVE);
        tb.add(new JButton("Button", icon)); // NOI18N
        tb.add(new JToggleButton("Button", icon)); // NOI18N
        tb.add(new JTextField("Text")); // NOI18N
        JComboBox c = new JComboBox();
        c.setEditor(new BasicComboBoxEditor());
        c.setRenderer(new BasicComboBoxRenderer());
        tb.add(c);
        tb.addSeparator();
        PREFERRED_HEIGHT = tb.getSuperPreferredSize().height;
    }
    dim.height = getParent() instanceof JToolBar ? 1 :
                 Math.max(dim.height, PREFERRED_HEIGHT);
    return dim;
}
 
Example 2
Source Project: visualvm   Source File: GenericToolbar.java    License: GNU General Public License v2.0 6 votes vote down vote up
public Dimension getPreferredSize() {
    Dimension dim = super.getPreferredSize();
    if (PREFERRED_HEIGHT == -1) {
        GenericToolbar tb = new GenericToolbar();
        tb.setBorder(getBorder());
        tb.setBorderPainted(isBorderPainted());
        tb.setRollover(isRollover());
        tb.setFloatable(isFloatable());
        Icon icon = Icons.getIcon(GeneralIcons.SAVE);
        tb.add(new JButton("Button", icon)); // NOI18N
        tb.add(new JToggleButton("Button", icon)); // NOI18N
        tb.add(new JTextField("Text")); // NOI18N
        JComboBox c = new JComboBox();
        c.setEditor(new BasicComboBoxEditor());
        c.setRenderer(new BasicComboBoxRenderer());
        tb.add(c);
        tb.addSeparator();
        PREFERRED_HEIGHT = tb.getSuperPreferredSize().height;
    }
    dim.height = getParent() instanceof JToolBar ? 1 :
                 Math.max(dim.height, PREFERRED_HEIGHT);
    return dim;
}
 
Example 3
AutoCompletionDocumentListener(JComboBox<E> box) {
	if (box == null) {
		throw new IllegalArgumentException("comboBox must not be null");
	}
	comboBox = box;
	comboBox.setEditable(true);
	if (comboBox.getEditor() == null) {
		comboBox.setEditor(new BasicComboBoxEditor());
	}
	//Only do this once
	comboBox.setEditor(new ComboBoxEditorWrapper(comboBox.getEditor()) {
		@Override
		public void setItem(Object anObject) {
			isLoading = true;
			super.setItem(anObject);
			isLoading = false;
		}
	});
	if (comboBox.getModel() == null) {
		comboBox.setModel(new DefaultComboBoxModel<>());
	}
	comboBox.addPropertyChangeListener(MODEL, this::initComboBoxModel);
	comboBox.addPropertyChangeListener(EDITOR, this::initComboBoxEditor);
	initComboBoxModel();
	initComboBoxEditor();
}
 
Example 4
Source Project: binnavi   Source File: CGraphSearchField.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new search field.
 *
 * @param graph Graph searched through by this field.
 */
public CGraphSearchField(final ZyGraph graph) {
  super(20);

  Preconditions.checkNotNull(graph, "IE01812: Target view can't be null");

  m_graph = graph;

  m_searcher = new GraphSearcher();

  setEditor(new BasicComboBoxEditor() {
    @Override
    protected JTextField createEditorComponent() {
      return m_textField;
    }
  });

  registerHotkeys();
}
 
Example 5
Source Project: FlatLaf   Source File: FlatCustomBordersTest.java    License: Apache License 2.0 5 votes vote down vote up
private void applyCustomComboBoxEditorBorder( JComboBox<String> comboBox, Border border ) {
	JTextField customTextField = new JTextField();
	customTextField.setBorder( border );
	comboBox.setEditor( new BasicComboBoxEditor() {
		@Override
		protected JTextField createEditorComponent() {
			return customTextField;
		}
	} );
}
 
Example 6
Source Project: opt4j   Source File: Query.java    License: MIT License 5 votes vote down vote up
/**
 * Create a choice menu.
 * 
 * @param name
 *            The name used to identify the entry (when calling get).
 * @param label
 *            The label to attach to the entry.
 * @param values
 *            The list of possible choices.
 * @param defaultChoice
 *            Default choice.
 * @param editable
 *            True if an arbitrary choice can be entered, in addition to the
 *            choices in values.
 * @param background
 *            The background color for the editable part.
 * @param foreground
 *            The foreground color for the editable part.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public void addChoice(String name, String label, String[] values, String defaultChoice, boolean editable,
		final Color background, final Color foreground) {
	JLabel lbl = new JLabel(label + ": ");
	lbl.setBackground(_background);

	JComboBox combobox = new JComboBox(values);
	combobox.setEditable(editable);

	// NOTE: Typical of Swing, the following does not set
	// the background color. So we have to specify a
	// custom editor. #$(#&$#(@#!!
	// combobox.setBackground(background);
	combobox.setEditor(new BasicComboBoxEditor() {
		@Override
		public Component getEditorComponent() {
			Component result = super.getEditorComponent();
			result.setBackground(background);
			result.setForeground(foreground);
			return result;
		}
	});
	combobox.setSelectedItem(defaultChoice);
	_addPair(name, lbl, combobox, combobox);

	// Add the listener last so that there is no notification
	// of the first value.
	combobox.addItemListener(new QueryItemListener(name));
}
 
Example 7
private static void testBasicComboBoxEditor() {

        BasicComboBoxEditor comboBoxEditor = new BasicComboBoxEditor();
        comboBoxEditor.setItem(new UserComboBoxEditorType("100"));

        JTextField editor = (JTextField) comboBoxEditor.getEditorComponent();
        editor.setText("200");
        UserComboBoxEditorType item = (UserComboBoxEditorType) comboBoxEditor.getItem();

        if (!item.str.equals("200")) {
            throw new RuntimeException("Wrong itme value!");
        }
    }
 
Example 8
private void constructPanel(String[] values) {
	// constructing editors
	editors = new PropertyValueCellEditor[types.length];
	for (int i = 0; i < types.length; i++) {
		editors[i] = PropertyPanel.instantiateValueCellEditor(types[i], operator);
	}

	// building panel
	panel = new JPanel();
	panel.setFocusable(true);
	panel.setLayout(new GridLayout(1, editors.length));
	for (int i = 0; i < types.length; i++) {
		Component editorComponent = editors[i].getTableCellEditorComponent(null, values[i], false, 0, 0);

		if (editorComponent instanceof JComboBox) {
			if (((JComboBox<?>) editorComponent).isEditable()) {
				ComboBoxEditor editor = ((JComboBox<?>) editorComponent).getEditor();
				if (editor instanceof BasicComboBoxEditor) {
					editor.getEditorComponent().addFocusListener(focusListener);
				}
			} else {
				editorComponent.addFocusListener(focusListener);
			}
		} else if (editorComponent instanceof JPanel) {
			JPanel editorPanel = (JPanel) editorComponent;
			Component[] components = editorPanel.getComponents();
			for (Component comp : components) {
				comp.addFocusListener(focusListener);
			}
		} else {

			editorComponent.addFocusListener(focusListener);
		}
		panel.add(editorComponent);
		panel.addFocusListener(focusListener);
	}
}
 
Example 9
Source Project: binnavi   Source File: CGotoAddressField.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new Goto Address field.
 * 
 * @param graph The graph the address field refers to.
 * @param modules The list of modules present in the graph
 * @param parent The parent JFrame
 */
public CGotoAddressField(final ZyGraph graph, final List<INaviModule> modules, final JFrame parent) {
  super(20);

  m_graph = Preconditions.checkNotNull(graph, "IE01811: Graph argument can't be null");
  m_modules = Preconditions.checkNotNull(modules, "IE01176: Modules argument can not be null");
  m_parent = Preconditions.checkNotNull(parent, "IE02845: parent argument can not be null");

  // Code to fix some kind of combo box GUI issue with formatted text fields
  m_textField.setPreferredSize(getPreferredSize());
  m_textField.setBorder(((JTextField) new JComboBox().getEditor().getEditorComponent())
      .getBorder());

  setEditor(new BasicComboBoxEditor() {
    @Override
    protected JTextField createEditorComponent() {
      return m_textField;
    }
  });

  ((JTextField) getEditor().getEditorComponent()).getInputMap().put(
      HotKeys.GRAPH_SEARCH_NEXT_KEY.getKeyStroke(), "ZOOM");
  ((JTextField) getEditor().getEditorComponent()).getActionMap().put("ZOOM",
      new AbstractAction() {
        private static final long serialVersionUID = 4721578747969744911L;

        @Override
        public void actionPerformed(final ActionEvent event) {
          if (m_modules.size() == 1) {
            zoomToAddress();
          } else {
            buildAddressSelectionPopUp();
          }
        }
      });

  addActionListener(m_listener);
}
 
Example 10
Source Project: beautyeye   Source File: BEComboBoxUI.java    License: Apache License 2.0 5 votes vote down vote up
/**
     * Creates the default editor that will be used in editable combo boxes.  
     * A default editor will be used only if an editor has not been 
     * explicitly set with <code>setEditor</code>.
     *
     * @return a <code>ComboBoxEditor</code> used for the combo box
     * @see javax.swing.JComboBox#setEditor
     */
    protected ComboBoxEditor createEditor() 
    {
    	BasicComboBoxEditor.UIResource bcbe = new BasicComboBoxEditor.UIResource();
    	if(bcbe != null)
    	{
    		Component c = bcbe.getEditorComponent();
    		if(c != null)
    		{
    			//把默认的Editor设置成透明(editor不透明的话就会遮住NP背景图,从而使得外观难看)
    			((JComponent)c).setOpaque(false);
    			
    			//* 以下这段是为了给默认Editor加上border而加(没有它个border将使
    			//* 得与不可编辑comboBox的内容组件看起来有差异哦),
    			//* 在WindowsComboBoxUI中,这段代码是放在WindowsComboBoxEditor
    			//* 中的方法createEditorComponent中实现,由于该 方法是1.6里才有的,
    			//* BE LNF因要兼容java1.5,所以不作类似实现就在本方法中实现也没有问题。
    			//* 类似实现请参考WindowsComboBoxUI.WindowsComboBoxEditor类
//    			JTextField editor = (JTextField)c;
                Border border = (Border)UIManager.get("ComboBox.editorBorder");
                if (border != null) 
                {
                	((JComponent)c).setBorder(border);
                }
    		}
    	}
        return bcbe;
    }
 
Example 11
public FormulaFragmentCellEditor() {
  setLayout( new BorderLayout() );

  final Action action = createExtendedEditorAction();

  this.eventListenerList = new EventListenerList();

  ellipsisButton = new EllipsisButton( "..." );
  ellipsisButton.addActionListener( action );

  comboBox = new JComboBox();
  final ComboBoxEditor boxEditor = comboBox.getEditor();
  if ( boxEditor instanceof BasicComboBoxEditor ) {
    final BasicComboBoxEditor basicComboBoxEditor = (BasicComboBoxEditor) boxEditor;
    final Object editorComponent = basicComboBoxEditor.getEditorComponent();
    if ( editorComponent instanceof JTextField ) {
      final JTextField editorTextField = (JTextField) editorComponent;
      editorTextField.setDocument( new NonFilteringPlainDocument() );
    }
  }
  comboBox.setRenderer( new EmptyValueListCellRenderer() );
  comboBox.addActionListener( new SelectionAction() );
  comboBox.getInputMap().put( KeyStroke.getKeyStroke( KeyEvent.VK_ESCAPE, 0 ), new CancelAction() );
  comboBox.getInputMap().put( EditorMessages.getInstance().getKeyStroke
    ( "AbstractStringValueCellEditor.Popup.Accelerator" ), POPUP_EDITOR );
  comboBox.setBorder( BorderFactory.createEmptyBorder() );
  comboBox.setEditable( true );

  add( comboBox, BorderLayout.CENTER );
  add( ellipsisButton, BorderLayout.EAST );

  formulaContext = new DefaultFormulaContext();

  nullable = false;
}
 
Example 12
Source Project: java-swing-tips   Source File: MainPanel.java    License: MIT License 4 votes vote down vote up
private MainPanel() {
  super(new BorderLayout());

  String[] model = {"123456", "7890"};
  JComboBox<String> combo = new JComboBox<>(model);
  combo.setEditable(true);

  JComboBox<String> comboBox = new JComboBox<String>(model) {
    private static final int MAX_HISTORY = 10;
    private static final String ENTER_PRESSED = "enterPressed";
    @Override public void updateUI() {
      getActionMap().put(ENTER_PRESSED, null);
      super.updateUI();
      JComboBox<String> cb = this;
      Action defaultEnterPressedAction = getActionMap().get(ENTER_PRESSED);
      getActionMap().put(ENTER_PRESSED, new AbstractAction() {
        @Override public void actionPerformed(ActionEvent e) {
          boolean isPopupVisible = isPopupVisible();
          setPopupVisible(false);
          DefaultComboBoxModel<String> m = (DefaultComboBoxModel<String>) getModel();
          String str = Objects.toString(getEditor().getItem(), "");
          if (m.getIndexOf(str) < 0 && getInputVerifier().verify(cb)) {
            m.removeElement(str);
            m.insertElementAt(str, 0);
            if (m.getSize() > MAX_HISTORY) {
              m.removeElementAt(MAX_HISTORY);
            }
            setSelectedIndex(0);
            setPopupVisible(isPopupVisible);
          } else {
            defaultEnterPressedAction.actionPerformed(e);
          }
        }
      });
    }
  };
  comboBox.setEditable(true);
  comboBox.setInputVerifier(new LengthInputVerifier());
  comboBox.setEditor(new BasicComboBoxEditor() {
    private Component editorComponent;
    // // @see javax/swing/plaf/synth/SynthComboBoxUI.java
    // @Override public JTextField createEditorComponent() {
    //   JTextField f = new JTextField("", 9);
    //   f.setName("ComboBox.textField");
    //   return f;
    // }

    @Override public Component getEditorComponent() {
      // if (Objects.isNull(editorComponent)) {
      //   JTextComponent tc = (JTextComponent) super.getEditorComponent();
      //   editorComponent = new JLayer<>(tc, new ValidationLayerUI<>());
      // }
      editorComponent = Optional.ofNullable(editorComponent)
        .orElseGet(() -> new JLayer<>((JTextComponent) super.getEditorComponent(), new ValidationLayerUI<>()));
      return editorComponent;
    }
  });
  comboBox.addPopupMenuListener(new SelectItemMenuListener());

  JPanel p = new JPanel(new GridLayout(5, 1));
  p.add(new JLabel("Default:", SwingConstants.LEFT));
  p.add(combo);
  p.add(Box.createVerticalStrut(15));
  p.add(new JLabel("6 >= str.length()", SwingConstants.LEFT));
  p.add(comboBox);
  add(p, BorderLayout.NORTH);
  setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
  setPreferredSize(new Dimension(320, 240));
}
 
Example 13
Source Project: java-swing-tips   Source File: MainPanel.java    License: MIT License 4 votes vote down vote up
private MainPanel() {
  super(new BorderLayout());

  JComboBox<String> combo1 = new JComboBox<>(new String[] {"colors", "sports", "food"});
  combo1.setEditable(true);
  combo1.setSelectedIndex(-1);
  // combo1.setRenderer(new DefaultListCellRenderer() {
  //   @Override public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
  //     String str = Objects.toString(value, "- Select category -");
  //     super.getListCellRendererComponent(list, str, index, isSelected, cellHasFocus);
  //     return this;
  //   }
  // });

  String[][] arrays = {
    {"blue", "violet", "red", "yellow"},
    {"basketball", "soccer", "football", "hockey"},
    {"hot dogs", "pizza", "ravioli", "bananas"}
  };
  // JComboBox<String> combo2 = new JComboBox<String>() {
  //   @Override public void updateUI() {
  //     setBorder(null);
  //     super.updateUI();
  //     if (isWindowsLnF()) {
  //       setBorder(BorderFactory.createCompoundBorder(
  //           getBorder(), BorderFactory.createEmptyBorder(0, 2, 0, 0)));
  //     }
  //   }
  //
  //   private boolean isWindowsLnF() {
  //     return getUI().getClass().getName().contains("WindowsComboBoxUI");
  //   }
  // };
  JComboBox<String> combo2 = new JComboBox<>();
  combo2.setEditable(true);

  combo1.addItemListener(e -> {
    if (e.getStateChange() == ItemEvent.SELECTED) {
      int idx = ((JComboBox<?>) e.getItemSelectable()).getSelectedIndex();
      combo2.setModel(new DefaultComboBoxModel<>(arrays[idx]));
      combo2.setSelectedIndex(-1);
    }
  });

  combo2.setEditor(new BasicComboBoxEditor() {
    private Component editorComponent;

    @Override public Component getEditorComponent() {
      editorComponent = Optional.ofNullable(editorComponent)
          .orElseGet(() -> {
            JTextComponent tc = (JTextComponent) super.getEditorComponent();
            return new JLayer<>(tc, new PlaceholderLayerUI<>("- Select type -"));
          });
      return editorComponent;
    }
  });
  combo2.setBorder(BorderFactory.createCompoundBorder(
      combo2.getBorder(), BorderFactory.createEmptyBorder(0, 2, 0, 0)));

  JPanel p = new JPanel(new GridLayout(4, 1, 5, 5));
  setBorder(BorderFactory.createEmptyBorder(5, 20, 5, 20));
  p.add(new JLabel("Category"));
  p.add(combo1);
  p.add(new JLabel("Type"));
  p.add(combo2);

  JButton button = new JButton("clear");
  button.addActionListener(e -> {
    combo1.setSelectedIndex(-1);
    combo2.setModel(new DefaultComboBoxModel<>());
  });

  add(p, BorderLayout.NORTH);
  add(button, BorderLayout.SOUTH);
  setPreferredSize(new Dimension(320, 240));
}
 
Example 14
public AbstractStringValueCellEditor() {
  setLayout( new BorderLayout() );

  modelChangeHandler = new ReportModelChangeHandler();

  final Action action = createExtendedEditorAction();

  this.eventListenerList = new EventListenerList();
  this.dataAttributeContext = new DefaultDataAttributeContext();
  this.extraFields = EMPTY_EXTRA_FIELDS;

  ellipsisButton = new EllipsisButton( "..." );
  ellipsisButton.addActionListener( action );

  textField = new JTextArea();
  textField.setLineWrap( true );
  textField.setDocument( new NonFilteringPlainDocument() );
  textField.getInputMap().put( UtilMessages.getInstance().getKeyStroke
    ( "AbstractStringValueCellEditor.Popup.Accelerator" ), POPUP_EDITOR );
  textField.getActionMap().put( POPUP_EDITOR, action );
  textField.getInputMap().put( KeyStroke.getKeyStroke( KeyEvent.VK_ESCAPE, 0 ), CANCEL_EDITOR );
  textField.getActionMap().put( CANCEL_EDITOR, new CancelAction() );
  textField.getInputMap().put( KeyStroke.getKeyStroke( KeyEvent.VK_ENTER, KeyEvent.SHIFT_MASK ), NEWLINE_EDITOR );
  textField.getActionMap().put( NEWLINE_EDITOR, new InsertNewLineAction() );
  textField.getInputMap().put( KeyStroke.getKeyStroke( KeyEvent.VK_ENTER, 0 ), CONFIRM_EDITOR );
  textField.getActionMap().put( CONFIRM_EDITOR, new SelectionAction() );
  textField.setBorder( BorderFactory.createEmptyBorder() );

  comboBox = new JComboBox();
  final ComboBoxEditor boxEditor = comboBox.getEditor();
  if ( boxEditor instanceof BasicComboBoxEditor ) {
    final BasicComboBoxEditor basicComboBoxEditor = (BasicComboBoxEditor) boxEditor;
    final Object editorComponent = basicComboBoxEditor.getEditorComponent();
    if ( editorComponent instanceof JTextField ) {
      final JTextField editorTextField = (JTextField) editorComponent;
      editorTextField.setDocument( new NonFilteringPlainDocument() );
    }
  }
  comboBox.setRenderer( new EmptyValueListCellRenderer() );
  comboBox.addActionListener( new SelectionAction() );
  comboBox.getInputMap().put( KeyStroke.getKeyStroke( KeyEvent.VK_ESCAPE, 0 ), new CancelAction() );
  comboBox.getInputMap().put( UtilMessages.getInstance().getKeyStroke
    ( "AbstractStringValueCellEditor.Popup.Accelerator" ), POPUP_EDITOR );
  comboBox.setBorder( BorderFactory.createEmptyBorder() );
  comboBox.setEditable( true );

  add( textField, BorderLayout.CENTER );
  add( ellipsisButton, BorderLayout.EAST );

  nullable = false;
}