下面列出了怎么用javax.swing.AbstractButton的API类实例代码及写法,或者点击链接到github查看源代码。
private AbstractButton findButton(Container c, String s) {
if (c instanceof AbstractButton && s.equals(((AbstractButton) c).getText())) {
return ((AbstractButton) c);
} else {
Component[] cs = c.getComponents();
for (int i=0; i < cs.length; i++) {
if (cs[i] instanceof Container) {
AbstractButton result = findButton((Container) cs[i], s);
if (result != null) {
return result;
}
}
}
}
return null;
}
public ArrayList<DomPlayer> initPlayers() {
myPlayers = new HashMap<DomPlayer, JButton>();
ArrayList<DomPlayer> thePlayers = new ArrayList<DomPlayer>();
for (JButton theSelector : myBotSelectors ) {
if (getSelectedPlayer(theSelector) == null)
continue;
DomPlayer theSelectedBot = getSelectedPlayer(theSelector);
DomPlayer thePlayer = theSelectedBot.getCopy( theSelectedBot + "(Plr " + (myBotSelectors.indexOf( theSelector )+1) + ")" );
int j=0;
for (Enumeration< AbstractButton > theEnum = myStartStateButtonGroups.get( theSelector ).getElements(); theEnum.hasMoreElements(); j++) {
if (theEnum.nextElement().isSelected() ){
if (j==1)
thePlayer.forceStart( 43 );
if (j==2)
thePlayer.forceStart( 52 );
}
}
myPlayers.put(thePlayer, theSelector);
thePlayers.add(thePlayer);
}
return thePlayers;
}
/** This is called when the user does Application->Quit */
@Override
public void handleQuit(ApplicationEvent event) {
// TODO this should not be hardcoded --> look up by menuitem name
Component[] sampleFile = parent.getJMenuBar().getMenu(0).getMenuComponents();
for (Component sampleFile1 : sampleFile) {
if (sampleFile1.getClass().getName().equalsIgnoreCase("javax.swing.JMenuItem")) {
if (((AbstractButton) sampleFile1).getText().equalsIgnoreCase("Exit")) {
((AbstractButton) sampleFile1).doClick();
event.setHandled(true);
}
}
}
}
@Override
protected AbstractButton buildButton() {
return new JButton() {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Gradient gradient = getGradient();
if (gradient != null) {
Rectangle r = new Rectangle(0, 0, getWidth(), getHeight());
r.grow(-3, -3);
Graphics2D g2 = (Graphics2D) g;
RenderingHints rh = g2.getRenderingHints();
g2.setRenderingHints(edu.xtec.jclic.Constants.DEFAULT_RENDERING_HINTS);
gradient.paint(g2, r);
g2.setRenderingHints(rh);
}
}
};
}
@Override
protected JPanel createParametersPanel() {
JPanel paramsPanel = new JPanel();
BoxLayout layout = new BoxLayout(paramsPanel, BoxLayout.PAGE_AXIS);
paramsPanel.setLayout(layout);
AbstractButton addParamBut = ToolButtonFactory.createButton(UIUtils.loadImageIcon(Bundle.Icon_Add()), false);
addParamBut.setText("New Parameter");
addParamBut.setMaximumSize(new Dimension(150, controlHeight));
addParamBut.setAlignmentX(Component.LEFT_ALIGNMENT);
addParamBut.setAlignmentY(Component.TOP_ALIGNMENT);
paramsPanel.add(addParamBut);
JScrollPane tableScrollPane = new JScrollPane(paramsTable);
tableScrollPane.setAlignmentX(Component.LEFT_ALIGNMENT);
paramsPanel.add(tableScrollPane);
addParamBut.addActionListener(e -> paramsTable.addParameterToTable());
return paramsPanel;
}
@Override
public Insets getBorderInsets( Component c, Insets insets ) {
if( FlatButtonUI.isToolBarButton( c ) ) {
// In toolbars, use button margin only if explicitly set.
// Otherwise use toolbar margin specified in UI defaults.
Insets margin = (c instanceof AbstractButton)
? ((AbstractButton)c).getMargin()
: null;
FlatUIUtils.setInsets( insets, UIScale.scale( FlatUIUtils.addInsets( toolbarSpacingInsets,
(margin != null && !(margin instanceof UIResource)) ? margin : toolbarMargin ) ) );
} else {
insets = super.getBorderInsets( c, insets );
// use smaller left and right insets for icon-only or single-character buttons (so that they are square)
if( FlatButtonUI.isIconOnlyOrSingleCharacterButton( c ) && ((AbstractButton)c).getMargin() instanceof UIResource )
insets.left = insets.right = Math.min( insets.top, insets.bottom );
}
return insets;
}
@NbBundle.Messages({"CTL_DeactivateAllBreakpoints=Deactivate all breakpoints in current session",
"CTL_ActivateAllBreakpoints=Activate all breakpoints in current session",
"CTL_NoDeactivation=The current session does not allow to deactivate breakpoints",
"CTL_NoSession=No debugger session"})
public static AbstractButton createActivateBreakpointsActionButton() {
ImageIcon icon = ImageUtilities.loadImageIcon(DEACTIVATED_LINE_BREAKPOINT, false);
final JToggleButton button = new JToggleButton(icon);
// ensure small size, just for the icon
Dimension size = new Dimension(icon.getIconWidth() + 8, icon.getIconHeight() + 8);
button.setPreferredSize(size);
button.setMargin(new Insets(1, 1, 1, 1));
button.setBorder(new EmptyBorder(button.getBorder().getBorderInsets(button)));
button.setToolTipText(Bundle.CTL_DeactivateAllBreakpoints());
button.setFocusable(false);
final BreakpointsActivator ba = new BreakpointsActivator(button);
button.addActionListener(ba);
DebuggerManager.getDebuggerManager().addDebuggerListener(DebuggerManager.PROP_CURRENT_ENGINE, new DebuggerManagerAdapter() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
DebuggerEngine de = (DebuggerEngine) evt.getNewValue();
ba.setCurrentEngine(de);
}
});
ba.setCurrentEngine(DebuggerManager.getDebuggerManager().getCurrentEngine());
return button;
}
@Override
protected void installDefaults( AbstractButton b ) {
super.installDefaults( b );
if( !defaults_initialized ) {
selectedBackground = UIManager.getColor( "ToggleButton.selectedBackground" );
selectedForeground = UIManager.getColor( "ToggleButton.selectedForeground" );
disabledSelectedBackground = UIManager.getColor( "ToggleButton.disabledSelectedBackground" );
toolbarSelectedBackground = UIManager.getColor( "ToggleButton.toolbar.selectedBackground" );
tabUnderlineHeight = UIManager.getInt( "ToggleButton.tab.underlineHeight" );
tabUnderlineColor = UIManager.getColor( "ToggleButton.tab.underlineColor" );
tabDisabledUnderlineColor = UIManager.getColor( "ToggleButton.tab.disabledUnderlineColor" );
tabSelectedBackground = UIManager.getColor( "ToggleButton.tab.selectedBackground" );
tabHoverBackground = UIManager.getColor( "ToggleButton.tab.hoverBackground" );
tabFocusBackground = UIManager.getColor( "ToggleButton.tab.focusBackground" );
defaults_initialized = true;
}
}
public void paint(Graphics g, JComponent c) {
AbstractButton button = (AbstractButton)c;
if (button.getModel().isRollover()
|| button.getModel().isArmed()
|| button.getModel().isSelected()) {
Color oldColor = g.getColor();
if (button.getModel().isSelected()) {
g.setColor(blueishBackgroundSelected);
} else {
g.setColor(blueishBackgroundOver);
}
g.fillRect(0, 0, c.getWidth() - 1, c.getHeight() - 1);
if (button.getModel().isSelected()) {
g.setColor(blueishBorderSelected);
} else {
g.setColor(blueishBorderOver);
}
g.drawRect(0, 0, c.getWidth() - 1, c.getHeight() - 1);
g.setColor(oldColor);
}
super.paint(g, c);
}
/**
* @noinspection ALL
*/
private void $$$loadButtonText$$$(AbstractButton component, String text) {
StringBuffer result = new StringBuffer();
boolean haveMnemonic = false;
char mnemonic = '\0';
int mnemonicIndex = -1;
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == '&') {
i++;
if (i == text.length()) break;
if (!haveMnemonic && text.charAt(i) != '&') {
haveMnemonic = true;
mnemonic = text.charAt(i);
mnemonicIndex = result.length();
}
}
result.append(text.charAt(i));
}
component.setText(result.toString());
if (haveMnemonic) {
component.setMnemonic(mnemonic);
component.setDisplayedMnemonicIndex(mnemonicIndex);
}
}
public void paintIcon(Component c, Graphics g, int x, int y)
{
AbstractButton b = (AbstractButton) c;
ButtonModel model = b.getModel();
Image selectedImg = __IconFactory__.getInstance().getCheckboxMenuItemSelectedNormalIcon().getImage();
boolean isSelected = model.isSelected();
// boolean isArmed = model.isArmed();
if (isSelected)
{
// if(isArmed)
// selectedImg = __IconFactory__.getInstance().getCheckboxMenuItemSelectedRoverIcon().getImage();
}
else
selectedImg = __IconFactory__.getInstance().getCheckboxMenuItemNoneIcon().getImage();
g.drawImage(selectedImg
, x+(usedForVista?5:-4)//* 注意:当用于windows平台专用主类且处于Vista及更高版win时要做不一样的处理哦
, y - 3
, null);
}
/**
* This method builds the specified button according to the specified
* parameters.
*
* @param button The button to build.
* @param text The text displayed on the button.
* @param icon The icon to use.
* @param handler The action listener that monitors the buttons events.
* @param command The action command used when the button is clicked.
* @param group The group the button should belong to.
* @param selected The initial selected state of the button.
* @param tip The tool tip to display.
*/
public
static
void
buildButton(AbstractButton button, String text, Icon icon,
ActionListener handler, String command, ButtonGroup group,
boolean selected, String tip)
{
button.addActionListener(handler);
button.setActionCommand(command);
button.setIcon(icon);
button.setSelected(selected);
button.setText(text);
button.setToolTipText(tip);
if(group != null)
{
group.add(button);
}
}
@Override
protected void applyRadioGroupRules() {
if ( radioGroupMap != null )
{
for ( ButtonGroup tempSwingRadioButtonListener : radioGroupMap.values() )
{
// -- If no RadioButtons within the radioGroup are selected, then first one in list will be selected --
if (tempSwingRadioButtonListener.getSelection() == null){
AbstractButton ab = tempSwingRadioButtonListener.getElements().nextElement();
if (ab != null) {
ab.setSelected(true);
}
}
}
}
}
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);
}
}
}
/**
* Create a imaged button for the given menu item.
* @param graphicsResource the graphics resource location.
* @param tooltip the tooltip text
* @param inMenu the menu item to relay the click to.
* @param toggle create a toggle button?
* @return the button
*/
AbstractButton createFor(String graphicsResource, String tooltip, final JMenuItem inMenu, boolean toggle) {
AbstractButton result = toggle ? new JToggleButton() : new JButton();
URL res = CampaignEditor.class.getResource("/hu/openig/editors/" + graphicsResource);
if (res != null) {
ImageIcon icon = new ImageIcon(res);
result.setIcon(icon);
inMenu.setIcon(icon);
}
result.setToolTipText(tooltip);
result.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
inMenu.doClick();
}
});
return result;
}
/**
* Remove all action listeners from a button.
*
* @param button Button.
*/
public static void removeActionListeners(AbstractButton button) {
if (button == null) {
return;
}
ActionListener[] listeners = button.getActionListeners();
if (listeners == null) {
return;
}
for (ActionListener listener : listeners) {
button.removeActionListener(listener);
}
}
@Override
void paintBackground(SynthContext context, Graphics g, JComponent c) {
if (((AbstractButton) c).isContentAreaFilled()) {
int x = 0, y = 0, w = c.getWidth(), h = c.getHeight();
SynthPainter painter = context.getPainter();
painter.paintToggleButtonBackground(context, g, x, y, w, h);
}
}
public CheckErrorPageListPopupListener(
EnumWikipedia wiki,
MWPane textComponent,
AbstractButton button) {
this.wiki = wiki;
this.textComponent = textComponent;
this.button = button;
}
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
AbstractButton b = (AbstractButton)c;
if (b.isSelected()) {
Color color = c.getBackground();
g.setColor(Utilities.deriveColorHSB(color, 0, 0, -.20f));
g.drawLine(x, y, x + width, y);
g.setColor(Utilities.deriveColorHSB(color, 0, 0, -.10f));
g.drawLine(x, y + 1, x + width, y + 1);
g.drawLine(x, y + 2, x, y + height - 2);
g.setColor(Utilities.deriveColorHSB(color, 0, 0, .24f));
g.drawLine(x, y + height - 1, x + width, y + height-1);
}
}
@Override
public void restoreDefaultValue() throws IllegalAccessException, InvocationTargetException {
if (this.getValue() instanceof FormDesignValue) {
FormDesignValue formValue = (FormDesignValue) this.getValue();
if (formValue.getDesignValue() instanceof ButtonGroup) {
AbstractButton button = (AbstractButton) this.getRADComponent().getBeanInstance();
synchronizeButtonGroupInAWT(button, formValue, null);
}
}
super.restoreDefaultValue();
}
/**
*
*/
public SimpleGeomPanel(PreferencesExt prefs) {
super(prefs, "dataset:", true, false);
sgTable = new SimpleGeomTable(prefs, true);
add(sgTable, BorderLayout.CENTER);
AbstractButton viewButton = BAMutil.makeButtcon("alien", "Grid Viewer", false);
viewButton.addActionListener(e -> {
if (ds != null) {
GridDataset gridDataset = sgTable.getGridDataset();
if (sgUI == null) {
makeSimpleGeomUI();
}
sgUI.setDataset(gridDataset);
viewerWindow.show();
}
});
buttPanel.add(viewButton);
AbstractButton imageButton = BAMutil.makeButtcon("VCRMovieLoop", "Image Viewer", false);
imageButton.addActionListener(e -> {
if (ds != null) {
GridDatatype grid = sgTable.getGrid();
if (grid == null) {
return;
}
if (imageWindow == null) {
makeImageWindow();
}
imageViewer.setImageFromGrid(grid);
imageWindow.show();
}
});
buttPanel.add(imageButton);
sgTable.addExtra(buttPanel, fileChooser);
}
@Override
public void mouseExited(MouseEvent e) {
Component component = e.getComponent();
if (component instanceof AbstractButton) {
AbstractButton button = (AbstractButton) component;
button.setBorderPainted(false);
}
}
/**
* Maps {@code AbstractButton.getSelectedObjects()} through queue
*/
public Object[] getSelectedObjects() {
return ((Object[]) runMapping(new MapAction<Object>("getSelectedObjects") {
@Override
public Object map() {
return ((AbstractButton) getSource()).getSelectedObjects();
}
}));
}
public final Map<String,String> getData() {
Map<String,String> retVal = new HashMap<String,String>(getDataComponents().size());
for (Component c : getDataComponents()) {
// fill in the blanks...
String compName = c.getName();
if (compName != null) {
// construct the key
String key = compName;
if (c instanceof JComboBox) {
final JComboBox jcb = (JComboBox) c;
retVal.put(key, (String) jcb.getSelectedItem());
} else if (c instanceof JTextComponent) {
final JTextComponent jtc = (JTextComponent) c;
retVal.put(key, jtc.getText());
} else if (c instanceof AbstractButton) {
AbstractButton ab = (AbstractButton) c;
retVal.put(key, Boolean.toString(ab.isSelected()));
} else if (c instanceof JTable) {
JTable table = (JTable) c;
TableCellEditor tce = table.getCellEditor();
if (null != tce) {
tce.stopCellEditing();
}
Object tm = table.getModel();
if (tm instanceof DataTableModel) {
DataTableModel model = (DataTableModel) tm;
retVal.putAll(model.getData());
}
}
}
}
return retVal;
}
/**
* Maps {@code AbstractButton.setVerticalTextPosition(int)} through queue
*/
public void setVerticalTextPosition(final int i) {
runMapping(new MapVoidAction("setVerticalTextPosition") {
@Override
public void map() {
((AbstractButton) getSource()).setVerticalTextPosition(i);
}
});
}
static final void updateButton(AbstractButton btnResume) {
if (isSuspended()) {
int pending = Integer.getInteger("org.netbeans.io.pending", 0); // NOI18N
btnResume.setText(Bundle.MSG_Resume(pending));
btnResume.setSelected(true);
} else {
btnResume.setText(null);
btnResume.setSelected(false);
}
}
/**
* Renders a text String in Windows without the mnemonic.
* This is here because the WindowsUI hiearchy doesn't match the Component heirarchy. All
* the overriden paintText methods of the ButtonUI delegates will call this static method.
* <p>
*
* @param g Graphics context
* @param b Current button to render
* @param textRect Bounding rectangle to render the text.
* @param text String to render
* @param textShiftOffset the text shift offset
*/
public static void paintText(Graphics g, AbstractButton b,
Rectangle textRect, String text,
int textShiftOffset) {
// FontMetrics fm = SwingUtilities2.getFontMetrics(b, g);
FontMetrics fm = MySwingUtilities2.getFontMetrics(
b, g);//* modified by Jack Jiang 为了非公开api的兼容性
int mnemIndex = b.getDisplayedMnemonicIndex();
// W2K Feature: Check to see if the Underscore should be rendered.
// if (WindowsLookAndFeel.isMnemonicHidden() == true) {
if (isMnemonicHidden() == true) {//* modified by jack jiang
mnemIndex = -1;
}
//
// XPStyle xp = XPStyle.getXP();
// if (xp != null && !(b instanceof JMenuItem))
// {
// paintXPText(b, g, textRect.x + textShiftOffset,
// textRect.y + fm.getAscent() + textShiftOffset,
// text, mnemIndex);
// }
// else
{
paintClassicText(b, g, textRect.x + textShiftOffset,
textRect.y + fm.getAscent() + textShiftOffset,
text, mnemIndex);
}
}
private void addDataRow(AggregatorItem ac) {
EmptyBorder emptyBorder = new EmptyBorder(2, 2, 2, 2);
JLabel typeLabel = new JLabel(getTypeText(ac));
typeLabel.setBorder(emptyBorder);
JLabel sourceBandsLabel = new JLabel(getSourceBandsText(ac));
sourceBandsLabel.setBorder(emptyBorder);
JLabel parametersLabel = new JLabel(getParametersText(ac));
parametersLabel.setBorder(emptyBorder);
JLabel targetBandsLabel = new JLabel(getTargetBandsText(ac));
targetBandsLabel.setBorder(emptyBorder);
final AbstractButton editButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("/org/esa/snap/resources/images/icons/Edit16.gif"),
false);
editButton.setRolloverEnabled(true);
editButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int rowIndex = grid.findDataRowIndex(editButton);
editAggregatorItem(aggregatorItems.get(rowIndex), rowIndex);
}
});
grid.addDataRow(
/*1*/ typeLabel,
/*2*/ sourceBandsLabel,
/*3*/ parametersLabel,
/*4*/ targetBandsLabel,
/*5*/ editButton);
aggregatorItems.add(ac);
}
public void paintIcon(Component c, Graphics g, int x, int y)
{
AbstractButton cb = (AbstractButton) c;
ButtonModel model = cb.getModel();
boolean isPressed = (model.isArmed() && model.isPressed());
boolean isRollver = (model.isRollover() && cb.isRolloverEnabled());
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
drawOval(g2d, x, y, (isRollver || isPressed));
if(model.isSelected())
{
fillOval(g2d, x, y);
}
else if(isRollver && isPressed)
{
drawOvalShadow(g2d, x, y);
}
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
}
@Override
protected void uninstallDefaults( AbstractButton b ) {
super.uninstallDefaults( b );
MigLayoutVisualPadding.uninstall( b );
defaults_initialized = false;
}