下面列出了怎么用java.awt.Component的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
protected Component createContents() {
deleteLoginCheck.setSelected(true);
submit.addActionListener((e) -> this.submit());
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridy = 0;
addLabelAndInput(panel, deleteLoginLabel, deleteLoginCheck, gbc);
gbc.gridy++;
gbc.gridx = 1;
gbc.anchor = GridBagConstraints.NORTHEAST;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.NONE;
panel.add(submit, gbc.clone());
return panel;
}
/**
* Returns the <code>Component</code> at the specified corner.
* @param key the <code>String</code> specifying the corner
* @return the <code>Component</code> at the specified corner, as defined in
* {@link ScrollPaneConstants}; if <code>key</code> is not one of the
* four corners, <code>null</code> is returned
* @see JScrollPane#getCorner
*/
public Component getCorner(String key) {
if (key.equals(LOWER_LEFT_CORNER)) {
return lowerLeft;
}
else if (key.equals(LOWER_RIGHT_CORNER)) {
return lowerRight;
}
else if (key.equals(UPPER_LEFT_CORNER)) {
return upperLeft;
}
else if (key.equals(UPPER_RIGHT_CORNER)) {
return upperRight;
}
else {
return null;
}
}
private CDropTarget(DropTarget dropTarget, Component component, ComponentPeer peer) {
super();
fDropTarget = dropTarget;
fComponent = component;
fPeer = peer;
long nativePeer = CPlatformWindow.getNativeViewPtr(((LWComponentPeer) peer).getPlatformWindow());
if (nativePeer == 0L) return; // Unsupported for a window without a native view (plugin)
// Create native dragging destination:
fNativeDropTarget = this.createNativeDropTarget(dropTarget, component, peer, nativePeer);
if (fNativeDropTarget == 0) {
throw new IllegalStateException("CDropTarget.createNativeDropTarget() failed.");
}
}
protected void paintRaisedBevel(Component c, Graphics g, int x, int y, int width, int height) {
if (!c.isEnabled()) {
return;
}
Color oldColor = g.getColor();
int h = height;
int w = width;
g.translate(x, y);
g.setColor(getHighlightInnerColor(c));
g.drawLine(0, 0, 0, h - 1);
g.drawLine(1, 0, w - 1, 0);
g.setColor(getShadowOuterColor(c));
g.drawLine(0, h - 1, w - 1, h - 1);
g.drawLine(w - 1, 0, w - 1, h - 2);
g.translate(-x, -y);
g.setColor(oldColor);
}
public void listSpinnerWithInvalidValue() throws Throwable {
final LoggingRecorder lr = new LoggingRecorder();
final Exception[] exc = new Exception[] { null };
siw(new Runnable() {
@Override
public void run() {
List<Component> spinnerComponents = ComponentUtils.findComponents(JSpinner.class, frame);
JSpinner listSpinner = (JSpinner) spinnerComponents.get(0);
RSpinner rSpinner = new RSpinner(listSpinner, null, null, lr);
rSpinner.focusGained(null);
try {
listSpinner.setValue("Ostrich\"");
Call call = lr.getCall();
AssertJUnit.assertEquals("select", call.getFunction());
AssertJUnit.assertEquals("Ostrich\"", call.getState());
exc[0] = new MissingException(IllegalArgumentException.class);
} catch (IllegalArgumentException e) {
}
rSpinner.focusLost(null);
}
});
if (exc[0] != null) {
throw exc[0];
}
}
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean exp, boolean leaf, int row, boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, sel, exp, leaf, row, hasFocus);
setOpenIcon(isoIcon);
setClosedIcon(isoIcon);
setLeafIcon(isoIcon);
setFont(new Font("Arial", Font.PLAIN, 14));
if (!(((DefaultMutableTreeNode) value).getUserObject() instanceof String)) {
GenericIsoVO isoVO = (GenericIsoVO) ((DefaultMutableTreeNode) value).getUserObject();
if (isoVO instanceof MessageVO)
setIcon(validMessage);
else
setIcon(validField);
}
return this;
}
public void paintBorder(Component c, Graphics g, int x, int y,
int width, int height) {
if (c instanceof AbstractButton) {
AbstractButton b = (AbstractButton)c;
ButtonModel model = b.getModel();
if (model.isArmed() && model.isPressed() || model.isSelected()) {
drawBezel(g, x, y, width, height,
(model.isPressed() || model.isSelected()),
b.isFocusPainted() && b.hasFocus(), shadow, highlight, darkShadow, focus);
} else {
drawBezel(g, x, y, width, height,
false, b.isFocusPainted() && b.hasFocus(),
shadow, highlight, darkShadow, focus);
}
} else {
drawBezel(g, x, y, width, height, false, false,
shadow, highlight, darkShadow, focus);
}
}
@Override
public Component getTableCellRendererComponent(
final JTable table,
final Object value,
final boolean isSelected,
final boolean hasFocus,
final int row,
final int column) {
adaptee.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
final JLabel renderer =
(JLabel)
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
renderer.setHorizontalAlignment(SwingConstants.CENTER);
if (value == null) {
renderer.setBorder(BorderFactory.createEmptyBorder());
} else if (value.toString().contains("T")) {
renderer.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.green));
} else if (value.toString().contains("U")) {
renderer.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.blue));
} else if (value.toString().contains("u")) {
renderer.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.cyan));
} else {
renderer.setBorder(BorderFactory.createEmptyBorder());
}
return renderer;
}
public static void main(String[] args) throws IntrospectionException {
Class[] types = {
Component.class,
Container.class,
JComponent.class,
AbstractButton.class,
JButton.class,
JToggleButton.class,
};
// Control set. "enabled" and "name" has the same pattern and can be found
String[] names = {
"enabled",
"name",
"focusable",
};
for (String name : names) {
for (Class type : types) {
BeanUtils.getPropertyDescriptor(type, name);
}
}
}
void addListeners(Component ancestor, boolean addToFirst) {
Component a;
firstInvisibleAncestor = null;
for (a = ancestor;
firstInvisibleAncestor == null;
a = a.getParent()) {
if (addToFirst || a != ancestor) {
a.addComponentListener(this);
if (a instanceof JComponent) {
JComponent jAncestor = (JComponent)a;
jAncestor.addPropertyChangeListener(this);
}
}
if (!a.isVisible() || a.getParent() == null || a instanceof Window) {
firstInvisibleAncestor = a;
}
}
if (firstInvisibleAncestor instanceof Window &&
firstInvisibleAncestor.isVisible()) {
firstInvisibleAncestor = null;
}
}
@Override
protected Component createPageComponent() {
final PropertyChangeListener listener = evt -> getContext().updateState();
collocationCrsForm = new MyCollocationCrsForm(SnapApp.getDefault().getAppContext(), listener, getAssistantModel());
collocationCrsForm.addMyChangeListener();
final JPanel pagePanel = new JPanel(new BorderLayout());
final JPanel northPanel = new JPanel(new BorderLayout());
northPanel.add(new JLabel("Use CRS of "), BorderLayout.WEST);
northPanel.add(collocationCrsForm.getCrsUI());
pagePanel.add(northPanel, BorderLayout.NORTH);
final JPanel southPanel = new JPanel(new FlowLayout());
errorText = new JTextArea();
errorText.setBackground(southPanel.getBackground());
final JPanel jPanel = new JPanel();
jPanel.add(errorText);
southPanel.add(errorText);
pagePanel.add(southPanel, BorderLayout.SOUTH);
return pagePanel;
}
/**
* Returns the nth Accessible child of the object.
*
* @param i zero-based index of child
* @return the nth Accessible child of the object
*/
public Accessible getAccessibleChild(int i) {
Component[] children = getMenuComponents();
int count = 0;
for (Component child : children) {
if (child instanceof Accessible) {
if (count == i) {
if (child instanceof JComponent) {
// FIXME: [[[WDW - probably should set this when
// the component is added to the menu. I tried
// to do this in most cases, but the separators
// added by addSeparator are hard to get to.]]]
AccessibleContext ac = child.getAccessibleContext();
ac.setAccessibleParent(JMenu.this);
}
return (Accessible) child;
} else {
count++;
}
}
}
return null;
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
// When enabled, tracks color choices of container:
comp.setBackground(c.getBackground());
comp.setForeground(c.getForeground());
Graphics clip = g.create(x, y, getIconWidth(), getIconHeight());
comp.paint(clip);
}
private int getMaxCellHeight() {
int cellHeight = 0;
for (Component c : this.components) {
if (c.getPreferredSize().height > cellHeight) {
cellHeight = c.getPreferredSize().height;
}
}
return cellHeight;
}
@Override
public void focusLost(FocusEvent e) {
Component c = (Component) e.getSource();
if (getProperty(slider, "MultiThumbSlider.indicateComponent", "true").equals("true")) {
slider.setSelectedThumb(-1);
}
updateIndication();
c.repaint();
}
/**
* Description of the Method
*
*@param target Description of Parameter
*@return Description of the Returned Value
*/
public Dimension preferredLayoutSize(Container target) {
synchronized (target.getTreeLock()) {
Dimension dim = new Dimension(0, 0);
int nmembers = target.getComponentCount();
boolean firstVisibleComponent = true;
for (int ii = 0; ii < nmembers; ii++) {
Component m = target.getComponent(ii);
if (m.isVisible()) {
Dimension d = m.getPreferredSize();
dim.width = Math.max(dim.width, d.width);
if (firstVisibleComponent) {
firstVisibleComponent = false;
}
else {
dim.height += _vgap;
}
dim.height += d.height;
}
}
Insets insets = target.getInsets();
dim.width += insets.left + insets.right + _hgap * 2;
dim.height += insets.top + insets.bottom + _vgap * 2;
return dim;
}
}
/**
* Adds the towing text label to the towing label panel.
*/
private void addTowingTextLabel() {
try {
Component lastComponent = towingLabelPanel.getComponent(1);
if (lastComponent == towingButton) {
towingLabelPanel.remove(towingButton);
towingLabelPanel.add(towingTextLabel);
}
}
catch (ArrayIndexOutOfBoundsException e) {
towingLabelPanel.add(towingTextLabel);
}
}
protected void updateRenderer(Component c, JTable table, Object value,
boolean isSelected, boolean hasFocus, int row,
int column) {
if (!isSelected) {
c.setBackground(row % 2 == 0 ? DARKER_BACKGROUND : BACKGROUND);
// Make sure the renderer paints its background (Nimbus)
if (c instanceof JComponent) ((JComponent)c).setOpaque(true);
}
}
public Component getListCellRendererComponent(JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
JLabel comp = (JLabel) super.getListCellRendererComponent(list, value, index,
isSelected, cellHasFocus);
if (value != null) {
DBColumn column = (DBColumn) value;
if (column.isPrimaryKey()) {
comp.setIcon(primaryKeyIcon);
comp.setText(column.getName());
} else if (column.isForeignKey()) {
comp.setIcon(foreignKeyIcon);
comp.setText(column.getName());
} else if (column.isIndex()) {
comp.setIcon(indexKeyIcon);
comp.setText(column.getName());
} else {
comp.setIcon(columnIcon);
comp.setText(column.getName());
}
value = column.getName();
list.setToolTipText(value.toString());
}
return comp;
}
/**
* Returns an icon.
*
* @param shape the shape.
* @param fillPaint the fill paint.
* @param outlinePaint the outline paint.
*
* @return The icon.
*/
private Icon getIcon(Shape shape, final Paint fillPaint,
final Paint outlinePaint) {
final int width = shape.getBounds().width;
final int height = shape.getBounds().height;
final GeneralPath path = new GeneralPath(shape);
return new Icon() {
public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2 = (Graphics2D) g;
path.transform(AffineTransform.getTranslateInstance(x, y));
if (fillPaint != null) {
g2.setPaint(fillPaint);
g2.fill(path);
}
if (outlinePaint != null) {
g2.setPaint(outlinePaint);
g2.draw(path);
}
path.transform(AffineTransform.getTranslateInstance(-x, -y));
}
public int getIconWidth() {
return width;
}
public int getIconHeight() {
return height;
}
};
}
/**
* Overridden for performance reasons.
* See the <a href="#override">Implementation Note</a>
* for more information.
*/
public boolean isOpaque() {
Color back = getBackground();
Component p = getParent();
if (p != null) {
p = p.getParent();
}
// p should now be the JTable.
boolean colorMatch = (back != null) && (p != null) &&
back.equals(p.getBackground()) &&
p.isOpaque();
return !colorMatch && super.isOpaque();
}
/**
* Moves mouse pointer in the center of a given {@code comp} component
* and performs a left mouse button click using the {@code robot} parameter
* with the {@code delay} delay between press and release.
*/
public static void clickOnComp(final Component comp, final Robot robot, int delay) {
pointOnComp(comp, robot);
robot.delay(delay);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.delay(delay);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
}
/**
* upcall to handle the Drop message
*/
private void handleDropMessage(final Component component,
final int x, final int y,
final int dropAction, final int actions,
final long[] formats,
final long nativeCtxt) {
postDropTargetEvent(component, x, y, dropAction, actions,
formats, nativeCtxt,
SunDropTargetEvent.MOUSE_DROPPED,
!SunDropTargetContextPeer.DISPATCH_SYNC);
}
@Override
protected Component getAnotherObject() {
Component component = new MyComponent();
component.setForeground(Color.BLACK);
component.setFont(new Font(null, Font.ITALIC, 6));
return component;
}
private void updateClientCursor() {
Point p = MouseInfo.getPointerInfo().getLocation();
SwingUtilities.convertPointFromScreen(p, this);
Component target = SwingUtilities.getDeepestComponentAt(this, p.x, p.y);
if (target != null) {
content.setCursor(target.getCursor());
}
}
private boolean isGlue(Component c) {
if (c.isVisible() && c instanceof Box.Filler) {
Box.Filler f = (Box.Filler)c;
Dimension min = f.getMinimumSize();
Dimension pref = f.getPreferredSize();
return min.width == 0 && min.height == 0 &&
pref.width == 0 && pref.height == 0;
}
return false;
}
/**
* Creates new form NewProjectVisualPanel1
*/
@SuppressWarnings("LeakingThisInConstructor")
public ProjectAttributesPanelVisual(ProjectAttriburesPanel panel, Component bottomComponent) {
this.panel = panel;
initComponents();
if (bottomComponent != null) {
pnlExtraSpace.add(bottomComponent);
}
tfProjectName.getDocument().addDocumentListener(this);
tfProjectLocation.getDocument().addDocumentListener(this);
tfGroup.getDocument().addDocumentListener(this);
tfPackageBase.getDocument().addDocumentListener(this);
}
public final void removeView(Component view) {
if (view == null) return;
if (tabs != null) {
int viewIndex = tabs.indexOfComponent(view);
if (viewIndex == -1) return;
if (tabs.getTabCount() > 2) {
toolbars.remove(viewIndex);
tabs.remove(view);
} else {
tabs.remove(view);
firstView = tabs.getComponentAt(0);
firstName = tabs.getTitleAt(0);
firstIcon = tabs.getIconAt(0);
firstDescription = tabs.getToolTipTextAt(0);
remove(tabs);
add(firstView);
setToolbar(toolbars.get(0));
tabs = null;
}
} else if (firstView == view) {
remove(firstView);
setToolbar(null);
toolbars.clear();
firstView = null;
firstName = null;
firstIcon = null;
firstDescription = null;
fireViewOrIndexChanged();
}
}
protected void paintRaisedBevel(Component c, Graphics g, int x, int y,
int width, int height) {
Color oldColor = g.getColor();
int h = height;
int w = width;
g.translate(x, y);
g.setColor(getHighlightOuterColor(c));
g.drawLine(0, 0, 0, h-2);
g.drawLine(1, 0, w-2, 0);
g.setColor(getHighlightInnerColor(c));
g.drawLine(1, 1, 1, h-3);
g.drawLine(2, 1, w-3, 1);
g.setColor(getShadowOuterColor(c));
g.drawLine(0, h-1, w-1, h-1);
g.drawLine(w-1, 0, w-1, h-2);
g.setColor(getShadowInnerColor(c));
g.drawLine(1, h-2, w-2, h-2);
g.drawLine(w-2, 1, w-2, h-3);
g.translate(-x, -y);
g.setColor(oldColor);
}
public void printComp(Container c, String s){
System.out.println(s + c.getClass().getName());
if(c instanceof Container){
for (Component com : c.getComponents()) {
printComp((Container) com, s + "__");
}
}
}