Java Code Examples for javax.swing.JComponent#getPreferredSize()

The following examples show how to use javax.swing.JComponent#getPreferredSize() . 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 File: GraphicUtils.java    From xyTalk-pc with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
    * Makes all Compontens the same Size
    * 
    * @param comps
    */
   public static void makeSameSize(JComponent... comps) {
if (comps.length == 0) {
    return;
}

int max = 0;
for (JComponent comp1 : comps) {
    int w = comp1.getPreferredSize().width;
    max = w > max ? w : max;
}

Dimension dim = new Dimension(max, comps[0].getPreferredSize().height);
for (JComponent comp : comps) {
    comp.setPreferredSize(dim);
}
   }
 
Example 2
Source File: HideableBarRenderer.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void paint(Graphics g) {
    g.setColor(getBackground());
    g.fillRect(location.x, location.y, size.width, size.height);
    
    JComponent component = mainRenderer.getComponent();
    int componentWidth = component.getPreferredSize().width;
    int componentX = size.width - componentWidth;
    
    mainRenderer.move(location.x + componentX, location.y);
    component.setSize(componentWidth, size.height);
    component.paint(g);
    
    if (numberPercentRenderer == null || numberPercentRenderer.valueRenderers()[1].getComponent().isVisible()) {
        int freeWidth = size.width - maxRendererWidth - renderersGap();
        if (freeWidth >= MIN_BAR_WIDTH) {
            barRenderer.setSize(Math.min(freeWidth, MAX_BAR_WIDTH), size.height);
            barRenderer.move(location.x, location.y);
            barRenderer.paint(g);
        }
    }
}
 
Example 3
Source File: DataView.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public Dimension preferredLayoutSize(Container parent) {
    JComponent filter = filterPanel;
    if (filter != null && !filter.isVisible()) filter = null;
    
    JComponent search = searchPanel;
    if (search != null && !search.isVisible()) search = null;
    
    Dimension dim = new Dimension();
    
    if (filter != null && search != null) {
        Dimension dim1 = filter.getPreferredSize();
        Dimension dim2 = search.getPreferredSize();
        dim.width = dim1.width + dim2.width + 1;
        dim.height = Math.max(dim1.height, dim2.height);
    } else if (filter != null) {
        dim = filter.getPreferredSize();
    } else if (search != null) {
        dim = search.getPreferredSize();
    }
    
    if ((filter != null || search != null) && hasBottomFilterFindMargin())
        dim.height += 1;
    
    return dim;
}
 
Example 4
Source File: JTicker.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Calculate the positions of each of the items.
 */
protected void calculatePositionArray() {
	if (model == null) {
		return;
	}

	int pos = 0;
	int items = model.getSize();
	positions = new int[items + 1];
	positions[0] = 0;

	for (int i = 0; i < items; i++) {
		Object value = model.getElementAt(i);
		JComponent component = renderer.getTickerRendererComponent(this, value);
		Dimension size = component.getPreferredSize();
		pos += size.width + gap;
		positions[i + 1] = pos;
	}
}
 
Example 5
Source File: MemorySamplerViewSupport.java    From visualvm with GNU General Public License v2.0 6 votes vote down vote up
public Dimension preferredLayoutSize(Container parent) {
    JComponent filter = filterPanel;
    if (filter != null && !filter.isVisible()) filter = null;

    JComponent search = searchPanel;
    if (search != null && !search.isVisible()) search = null;

    Dimension dim = new Dimension();

    if (filter != null && search != null) {
        Dimension dim1 = filter.getPreferredSize();
        Dimension dim2 = search.getPreferredSize();
        dim.width = dim1.width + dim2.width + 1;
        dim.height = Math.max(dim1.height, dim2.height);
    } else if (filter != null) {
        dim = filter.getPreferredSize();
    } else if (search != null) {
        dim = search.getPreferredSize();
    }

    if ((filter != null || search != null) /*&& hasBottomFilterFindMargin()*/)
        dim.height += 1;

    return dim;
}
 
Example 6
Source File: InspectorLayoutPlacement.java    From pumpernickel with MIT License 5 votes vote down vote up
private int getBaseline(JComponent c) {
	if (c != null) {
		Dimension d = c.getPreferredSize();
		int b = c.getBaseline(d.width, d.height);
		if (b > 0) {
			return b;
		}
	}
	return -1;
}
 
Example 7
Source File: SplayedLayout.java    From pumpernickel with MIT License 5 votes vote down vote up
@Override
public void layoutContainer(Container parent) {
	JComponent[] components = getComponents(parent);
	if (components.length == 0) {
		return;
	}

	Border border = ((JComponent) parent).getBorder();
	Insets i = border == null ? new Insets(0, 0, 0, 0) : border
			.getBorderInsets(parent);
	int x = i.left;
	int y = i.top;
	int width = parent.getWidth() - i.left - i.right;
	int height = parent.getHeight() - i.top - i.bottom;

	int separators = components.length - 1;
	int requestedSize = horizontal ? separators * separatorSize.width
			: separators * separatorSize.height;
	LinkedHashMap<JComponent, Dimension> preferredSize = new LinkedHashMap<>(
			components.length);
	for (JComponent c : components) {
		Dimension d = c.getPreferredSize();
		preferredSize.put(c, d);
		requestedSize += horizontal ? d.width : d.height;
	}

	int max = horizontal ? width : height;
	Plan plan;
	if (requestedSize <= max) {
		plan = layoutContainerWithExtra((JComponent) parent, preferredSize,
				requestedSize, x, y, width, height);
	} else {
		plan = layoutContainerWithConstrainedSize((JComponent) parent,
				preferredSize, x, y, width, height);
	}
	plan.install();
}
 
Example 8
Source File: ResultTabActionVisualizer.java    From rapidminer-studio with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Creates a swing component that either consists of the only available option or shows a popup list of possible actions.
 *
 * @param exampleSetSupplier
 * 		the current exampleSetSupplier that should be used fur further actions
 * @return a Button or a PopupMenu
 */
public static JComponent createResultActionsComponent(Supplier<ExampleSet> exampleSetSupplier) {
	final List<ResultActionGuiProvider> actions = ResultTabActionRegistry.INSTANCE.getActions();
	if (actions.isEmpty()) {
		return null;
	}

	final JPanel actionsPanel = new JPanel();
	actionsPanel.setLayout(new GridBagLayout());
	actionsPanel.setOpaque(false);

	actionsPanel.setBorder(BorderFactory.createEmptyBorder(6, 6, 6, 0));
	GridBagConstraints gbc = new GridBagConstraints();
	gbc.gridx = 0;
	gbc.gridy = 0;
	gbc.anchor = GridBagConstraints.WEST;

	for (ResultActionGuiProvider action : actions) {
		final JComponent component = action.createComponent(exampleSetSupplier);
		final Dimension preferredSize = component.getPreferredSize();
		if (preferredSize.getWidth() > MAX_COMPONENT_WIDTH || preferredSize.getHeight() > MAX_COMPONENT_HEIGHT) {
			preferredSize.setSize(Math.min(preferredSize.width, MAX_COMPONENT_WIDTH), Math.min(preferredSize.height, MAX_COMPONENT_HEIGHT));
		}
		actionsPanel.add(component, gbc);
		gbc.gridx++;
	}
	return actionsPanel;
}
 
Example 9
Source File: TextHighlightingDemo.java    From filthy-rich-clients with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void installInLayeredPane(JComponent component) {
    JLayeredPane layeredPane = getRootPane().getLayeredPane();
    layeredPane.add(component, JLayeredPane.PALETTE_LAYER, 20);
    Dimension size = component.getPreferredSize();
    component.setSize(size);
    component.setLocation((getWidth() - size.width) / 2,
            (getHeight() - size.height) / 2);
    component.revalidate();
    component.setVisible(true);
}
 
Example 10
Source File: RendererPropertyDisplayer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public Dimension getPreferredSize() {
    //Optimize it shows 16% of painting time is in this call.  In some
    //cases it will be called more than once, so cache the return value
    if (prefSize == null) {
        JComponent jc = getRenderer(this);
        prefSize = jc.getPreferredSize();
    }

    return prefSize;
}
 
Example 11
Source File: DataTable.java    From osp with GNU General Public License v3.0 5 votes vote down vote up
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
  // value is column name
  String name = (value==null) ? "" : value.toString(); //$NON-NLS-1$
  textLine.setText(name);
  if (OSPRuntime.isMac()) {
  	name = TeXParser.removeSubscripting(name);
  }
  Component c = renderer.getTableCellRendererComponent(table, name, isSelected, hasFocus, row, col);
  if (!(c instanceof JComponent)) {
    return c;
  }
  JComponent comp = (JComponent) c;
  int sortCol = decorator.getSortedColumn();
  Font font = comp.getFont();
  if (OSPRuntime.isMac()) {
  	// textline doesn't work on OSX
    comp.setFont((sortCol!=convertColumnIndexToModel(col))? 
    		font.deriveFont(Font.PLAIN) : 
    		font.deriveFont(Font.BOLD));
    if (comp instanceof JLabel) {
    	((JLabel)comp).setHorizontalAlignment(SwingConstants.CENTER);
    }
    return comp;
  }
  java.awt.Dimension dim = comp.getPreferredSize();
  dim.height += 1;
  panel.setPreferredSize(dim);
  javax.swing.border.Border border = comp.getBorder();
  if (border instanceof javax.swing.border.EmptyBorder) {
    border = BorderFactory.createLineBorder(Color.LIGHT_GRAY);
  }
  panel.setBorder(border);
  // set font: bold if sorted column
  textLine.setFont((sortCol!=convertColumnIndexToModel(col)) ? font : font.deriveFont(Font.BOLD));
  textLine.setColor(comp.getForeground());
  textLine.setBackground(comp.getBackground());
  panel.setBackground(comp.getBackground());
  return panel;
}
 
Example 12
Source File: SeaGlassRootPaneUI.java    From seaglass with Apache License 2.0 4 votes vote down vote up
/**
 * Instructs the layout manager to perform the layout for the specified
 * container.
 *
 * @param parent the Container for which this layout manager is being
 *               used
 */
public void layoutContainer(Container parent) {
    JRootPane root  = (JRootPane) parent;
    Rectangle b     = root.getBounds();
    Insets    i     = root.getInsets();
    int       nextY = 0;
    int       w     = b.width - i.right - i.left;
    int       h     = b.height - i.top - i.bottom;

    if (root.getLayeredPane() != null) {
        root.getLayeredPane().setBounds(i.left, i.top, w, h);
    }

    if (root.getGlassPane() != null) {
        root.getGlassPane().setBounds(i.left, i.top, w, h);
    }
    // Note: This is laying out the children in the layeredPane,
    // technically, these are not our children.
    if (root.getWindowDecorationStyle() != JRootPane.NONE && (root.getUI() instanceof SeaGlassRootPaneUI)) {
        JComponent titlePane = ((SeaGlassRootPaneUI) root.getUI()).getTitlePane();

        if (titlePane != null) {
            Dimension tpd = titlePane.getPreferredSize();

            if (tpd != null) {
                int tpHeight = tpd.height;

                titlePane.setBounds(0, 0, w, tpHeight);
                nextY += tpHeight;
            }
        }
    }

    if (root.getJMenuBar() != null) {
        boolean   menuInTitle = (root.getClientProperty("JRootPane.MenuInTitle") == Boolean.TRUE);
        Dimension mbd         = root.getJMenuBar().getPreferredSize();
        int x = menuInTitle? 20 : 0;
        root.getJMenuBar().setBounds(x, menuInTitle ? 0 : nextY, w, mbd.height);
        root.getJMenuBar().setOpaque(false);
        root.getJMenuBar().setBackground(transparentColor);
        if (!menuInTitle) {
            nextY += mbd.height;
        }
    }

    if (root.getContentPane() != null) {
        /* Dimension cpd = */ root.getContentPane().getPreferredSize();
        root.getContentPane().setBounds(0, nextY, w, h < nextY ? 0 : h - nextY);
    }
}
 
Example 13
Source File: BERootPaneUI.java    From beautyeye with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the amount of space the layout would like to have.
 *
 * @param parent the parent
 * @return a Dimension object containing the layout's preferred size
 */ 
public Dimension preferredLayoutSize(Container parent) 
{
	Dimension cpd, mbd, tpd;
	int cpWidth = 0;
	int cpHeight = 0;
	int mbWidth = 0;
	int mbHeight = 0;
	int tpWidth = 0;
	int tpHeight = 0;
	Insets i = parent.getInsets();
	JRootPane root = (JRootPane) parent;

	if(root.getContentPane() != null) 
	{
		cpd = root.getContentPane().getPreferredSize();
	} 
	else 
	{
		cpd = root.getSize();
	}
	if (cpd != null) 
	{
		cpWidth = cpd.width;
		cpHeight = cpd.height;
	}

	if(root.getMenuBar() != null) 
	{
		mbd = root.getMenuBar().getPreferredSize();
		if (mbd != null)
		{
			mbWidth = mbd.width;
			mbHeight = mbd.height;
		}
	} 

	if (root.getWindowDecorationStyle() != JRootPane.NONE &&
			(root.getUI() instanceof BERootPaneUI)) 
	{
		JComponent titlePane = ((BERootPaneUI)root.getUI()).
		getTitlePane();
		if (titlePane != null) 
		{
			tpd = titlePane.getPreferredSize();
			if (tpd != null) 
			{
				tpWidth = tpd.width;
				tpHeight = tpd.height;
			}
		}
	}

	return new Dimension(Math.max(Math.max(cpWidth, mbWidth), tpWidth) + i.left + i.right, 
			cpHeight + mbHeight + tpWidth + i.top + i.bottom);
}
 
Example 14
Source File: SeaGlassRootPaneUI.java    From seaglass with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the amount of space the layout would like to have.
 *
 * @param  parent the Container for which this layout manager is being
 *                used
 *
 * @return a Dimension object containing the layout's preferred size
 */
public Dimension preferredLayoutSize(Container parent) {
    Dimension cpd;
    Dimension mbd;
    Dimension tpd;
    int       cpWidth  = 0;
    int       cpHeight = 0;
    int       mbWidth  = 0;
    int       mbHeight = 0;
    int       tpWidth  = 0;
    int       tpHeight = 0;
    Insets    i        = parent.getInsets();
    JRootPane root     = (JRootPane) parent;

    if (root.getContentPane() != null) {
        cpd = root.getContentPane().getPreferredSize();
    } else {
        cpd = root.getSize();
    }

    if (cpd != null) {
        cpWidth  = cpd.width;
        cpHeight = cpd.height;
    }

    if (root.getJMenuBar() != null) {
        mbd = root.getJMenuBar().getPreferredSize();
        if (mbd != null) {
            mbWidth  = mbd.width;
            mbHeight = mbd.height;
        }
    }

    if (root.getWindowDecorationStyle() != JRootPane.NONE && (root.getUI() instanceof SeaGlassRootPaneUI)) {
        JComponent titlePane = ((SeaGlassRootPaneUI) root.getUI()).getTitlePane();

        if (titlePane != null) {
            tpd = titlePane.getPreferredSize();
            if (tpd != null) {
                tpWidth  = tpd.width;
                tpHeight = tpd.height;
            }
        }
    }

    return new Dimension(Math.max(Math.max(cpWidth, mbWidth), tpWidth) + i.left + i.right,
                         cpHeight + mbHeight + tpHeight + i.top + i.bottom);
}
 
Example 15
Source File: SdksCustomizer.java    From NBANDROID-V2 with Apache License 2.0 4 votes vote down vote up
private void selectPlatform(Node pNode) {
    Component active = null;
    for (Component c : cards.getComponents()) {
        if (c.isVisible()
                && (c == jPanel1 || c == messageArea)) {
            active = c;
            break;
        }
    }
    final Dimension lastSize = active == null
            ? null
            : active.getSize();
    this.clientArea.removeAll();
    this.messageArea.removeAll();
    this.removeButton.setEnabled(false);
    if (pNode == null) {
        ((CardLayout) cards.getLayout()).last(cards);
        return;
    }
    JComponent target = messageArea;
    JComponent owner = messageArea;
    selectedPlatform = pNode.getLookup().lookup(AndroidSdk.class);
    if (pNode != getExplorerManager().getRootContext()) {
        if (selectedPlatform != null) {
            mkDefault.setEnabled(!selectedPlatform.isDefaultSdk());
            this.removeButton.setEnabled(!selectedPlatform.isDefaultSdk());
            if (!selectedPlatform.getInstallFolders().isEmpty()) {
                this.platformName.setText(pNode.getDisplayName());
                for (FileObject installFolder : selectedPlatform.getInstallFolders()) {
                    File file = FileUtil.toFile(installFolder);
                    if (file != null) {
                        this.platformHome.setText(file.getAbsolutePath());
                    }
                }
                target = clientArea;
                owner = jPanel1;
            }
        } else {
            removeButton.setEnabled(false);
            mkDefault.setEnabled(false);
        }
        Component component = null;
        if (pNode.hasCustomizer()) {
            component = pNode.getCustomizer();
        }
        if (component == null) {
            final PropertySheet sp = new PropertySheet();
            sp.setNodes(new Node[]{pNode});
            component = sp;
        }
        addComponent(target, component);
    }
    if (lastSize != null) {
        final Dimension newSize = owner.getPreferredSize();
        final Dimension updatedSize = new Dimension(
                Math.max(lastSize.width, newSize.width),
                Math.max(lastSize.height, newSize.height));
        if (!newSize.equals(updatedSize)) {
            owner.setPreferredSize(updatedSize);
        }
    }
    target.revalidate();
    CardLayout cl = (CardLayout) cards.getLayout();
    if (target == clientArea) {
        cl.first(cards);
    } else {
        cl.last(cards);
    }
}
 
Example 16
Source File: MSMSLibrarySubmissionWindow.java    From mzmine2 with GNU General Public License v2.0 4 votes vote down vote up
private void createSubmitParamPanel() {
  // Main panel which holds all the components in a grid
  pnSubmitParam = new GridBagPanel();
  pnSideMenu.add(pnSubmitParam, BorderLayout.NORTH);

  int rowCounter = 0;
  // Create labels and components for each parameter
  for (Parameter p : paramSubmit.getParameters()) {
    if (!(p instanceof UserParameter))
      continue;
    UserParameter up = (UserParameter) p;

    JComponent comp = up.createEditingComponent();
    comp.setToolTipText(up.getDescription());

    // Set the initial value
    Object value = up.getValue();
    if (value != null)
      up.setValueToComponent(comp, value);

    // By calling this we make sure the components will never be resized
    // smaller than their optimal size
    comp.setMinimumSize(comp.getPreferredSize());

    comp.setToolTipText(up.getDescription());


    // add separator
    if (p.getName().equals(LibrarySubmitParameters.LOCALFILE.getName())) {
      pnSubmitParam.addSeparator(0, rowCounter, 2);
      rowCounter++;
    }

    JLabel label = new JLabel(p.getName());
    pnSubmitParam.add(label, 0, rowCounter);
    label.setLabelFor(comp);

    parametersAndComponents.put(p.getName(), comp);

    JComboBox t = new JComboBox();
    int comboh = t.getPreferredSize().height;
    int comph = comp.getPreferredSize().height;


    int verticalWeight = comph > 2 * comboh ? 1 : 0;
    pnSubmitParam.add(comp, 1, rowCounter, 1, 1, 1, verticalWeight, GridBagConstraints.VERTICAL);
    rowCounter++;
  }
}
 
Example 17
Source File: SwingHelper.java    From azure-devops-intellij with MIT License 4 votes vote down vote up
public static void setPreferredHeight(final JComponent component, final int height) {
    final Dimension size = component.getPreferredSize();
    size.setSize(size.getWidth(), JBUI.scale(height));
    component.setPreferredSize(size);
}
 
Example 18
Source File: UiUtil.java    From intellij with Apache License 2.0 4 votes vote down vote up
public static void setPreferredWidth(JComponent component, int width) {
  int height = component.getPreferredSize().height;
  component.setPreferredSize(new Dimension(width, height));
}
 
Example 19
Source File: AbstractUndoableMovesPanel.java    From triplea with GNU General Public License v3.0 4 votes vote down vote up
private void initLayout() {
  removeAll();
  setLayout(new BorderLayout());
  final JPanel items = new JPanel();
  items.setLayout(new BoxLayout(items, BoxLayout.Y_AXIS));
  // we want the newest move at the top
  moves = new ArrayList<>(moves);
  Collections.reverse(moves);
  final Iterator<AbstractUndoableMove> iter = moves.iterator();
  if (iter.hasNext()) {
    add(
        new JLabel((this instanceof UndoablePlacementsPanel) ? "Placements:" : "Moves:"),
        BorderLayout.NORTH);
  }
  int scrollIncrement = 10;
  final Dimension separatorSize = new Dimension(150, 20);
  while (iter.hasNext()) {
    final AbstractUndoableMove item = iter.next();
    final JComponent moveComponent = newComponentForMove(item);
    scrollIncrement = moveComponent.getPreferredSize().height;
    items.add(moveComponent);
    if (iter.hasNext()) {
      final JSeparator separator = new JSeparator(SwingConstants.HORIZONTAL);
      separator.setPreferredSize(separatorSize);
      separator.setMaximumSize(separatorSize);
      items.add(separator);
    }
  }
  if (movePanel.getUndoableMoves() != null && movePanel.getUndoableMoves().size() > 1) {
    final JButton undoAllButton = new JButton("Undo All");
    undoAllButton.addActionListener(new UndoAllMovesActionListener());
    items.add(undoAllButton);
  }

  final int scrollIncrementFinal = scrollIncrement + separatorSize.height;
  // JScrollPane scroll = new JScrollPane(items);
  scroll =
      new JScrollPane(items) {
        private static final long serialVersionUID = -1064967105431785533L;

        @Override
        public void paint(final Graphics g) {
          if (previousVisibleIndex != null) {
            items.scrollRectToVisible(
                new Rectangle(
                    0,
                    scrollIncrementFinal * (moves.size() - previousVisibleIndex),
                    1,
                    scrollIncrementFinal));
            previousVisibleIndex = null;
          }
          super.paint(g);
        }
      };
  scroll.setBorder(null);
  scroll.getVerticalScrollBar().setUnitIncrement(scrollIncrementFinal);
  if (scrollBarPreviousValue != null) {
    scroll.getVerticalScrollBar().setValue(scrollBarPreviousValue);
    scrollBarPreviousValue = null;
  }
  add(scroll, BorderLayout.CENTER);
  SwingUtilities.invokeLater(this::validate);
}
 
Example 20
Source File: JUtils.java    From CQL with GNU Affero General Public License v3.0 3 votes vote down vote up
/**
 * Sets the maximum width of a JComponent to its preferred width, thereby
 * preventing it from being expanded. The component itself is returned, to allow
 * shortcuts such as: xyz.add(JUtils.fixWidth(component)).
 *
 * @param c the component to be width-fixed
 * @return the component
 */
public static JComponent fixWidth(JComponent c) {
	Dimension max = c.getMaximumSize();

	max.width = c.getPreferredSize().width;

	c.setMaximumSize(max);

	return c;
}