下面列出了怎么用javax.swing.SwingConstants的API类实例代码及写法,或者点击链接到github查看源代码。
private int layout(ArrayList<Component> list, int y, int width, Insets insets) {
for (Component component : list) {
if (component.isVisible()) {
Dimension size = component.getPreferredSize();
int x = 0;
if (myAlignment == -1) {
size.width = width;
}
else if (myAlignment != SwingConstants.LEFT) {
x = width - size.width;
if (myAlignment == SwingConstants.CENTER) {
x /= 2;
}
}
component.setBounds(x + insets.left, y + insets.top, size.width, size.height);
y += size.height + myGap;
}
}
return y;
}
public void testNewlineLineOne() throws Exception {
loggingOn();
RandomTestContainer container = createContainer();
JEditorPane pane = container.getInstance(JEditorPane.class);
Document doc = pane.getDocument();
doc.putProperty("mimeType", "text/plain");
ViewHierarchyRandomTesting.initRandomText(container);
ViewHierarchyRandomTesting.addRound(container).setOpCount(OP_COUNT);
ViewHierarchyRandomTesting.testFixedScenarios(container);
RandomTestContainer.Context context = container.context();
// Clear document contents
DocumentTesting.remove(context, 0, doc.getLength());
DocumentTesting.insert(context, 0, "\n");
EditorPaneTesting.moveOrSelect(context, SwingConstants.NORTH, false);
EditorPaneTesting.moveOrSelect(context, SwingConstants.SOUTH, true);
EditorPaneTesting.performAction(context, pane, DefaultEditorKit.deleteNextCharAction);
DocumentTesting.undo(context, 1);
}
@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;
}
/**
* Sets up the GUI card responsible for displaying no result information on an "All Studio" search to the user.
*/
private void setupNoResultGloballyGUI() {
JPanel noResultPanel = new JPanel();
noResultPanel.setName(CARD_NO_RESULTS_GLOBALLY);
noResultPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
noResultPanel.setOpaque(false);
noResultPanel.setBorder(TOP_BORDER);
// no results label
JLabel noResults = new JLabel(I18N.getGUIMessage("gui.dialog.global_search.no_results.label"));
noResults.setIcon(INFORMATION_ICON);
noResults.setFont(noResults.getFont().deriveFont(FONT_SIZE_NO_RESULTS));
noResults.setHorizontalAlignment(SwingConstants.LEFT);
gbc.weightx = 1.0d;
gbc.weighty = 1.0d;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(3, 10, 3, 10);
noResultPanel.add(noResults, gbc);
rootPanel.add(noResultPanel, CARD_NO_RESULTS_GLOBALLY);
}
/**
* Creates a new InterBoard object.
*
* @param sheet the related sheet
* @param selected true for pre-selected, false for collapsed
*/
public InterBoard (Sheet sheet,
boolean selected)
{
super(Board.INTER, sheet.getInterIndex().getEntityService(), true);
this.sheet = sheet;
// Force a constant height for the shapeIcon field, despite variation in size of the icon
Dimension dim = new Dimension(
constants.shapeIconWidth.getValue(),
constants.shapeIconHeight.getValue());
shapeIcon.setPreferredSize(dim);
shapeIcon.setMaximumSize(dim);
shapeIcon.setMinimumSize(dim);
details.setToolTipText("Grade details");
details.setHorizontalAlignment(SwingConstants.CENTER);
paramAction = new ParamAction();
// Initial status
grade.setEnabled(false);
details.setEnabled(false);
defineLayout();
}
public void showError(final String message) {
if (!SwingUtilities.isEventDispatchThread()) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
showError(message);
}
});
return;
}
removeAll();
msgLabel.setIcon(null);
msgLabel.setForeground(Color.GRAY);
msgLabel.setText(NbBundle.getMessage(AbstractXMLNavigatorContent.class, message));
msgLabel.setHorizontalAlignment(SwingConstants.CENTER);
add(emptyPanel, BorderLayout.CENTER);
revalidate();
repaint();
}
private void initComponents()
{
CharacterManager.getCharacters().addListListener(this);
frame.getSelectedCharacterRef().addReferenceListener(this);
setTabPlacement(SwingConstants.BOTTOM);
addChangeListener(this);
setSharedComponent(infoTabbedPane);
//Initialize popup menu
PCGenActionMap actions = frame.getActionMap();
popupMenu.add(actions.get(PCGenActionMap.NEW_COMMAND));
popupMenu.add(actions.get(PCGenActionMap.CLOSE_COMMAND));
popupMenu.add(actions.get(PCGenActionMap.SAVE_COMMAND));
popupMenu.add(actions.get(PCGenActionMap.SAVEAS_COMMAND));
addMouseListener(new PopupMouseAdapter()
{
@Override
public void showPopup(final MouseEvent e)
{
popupMenu.setVisible(true);
popupMenu.show(e.getComponent(), e.getX(), e.getY() - popupMenu.getHeight());
}
});
}
/**
* Draws the component border.
*
* @param g
* the graphics context
*/
public void paintBorder(Graphics g) {
Shape borderShape;
int radius = RapidLookAndFeel.CORNER_DEFAULT_RADIUS;
switch (position) {
case SwingConstants.LEFT:
borderShape = new RoundRectangle2D.Double(0, 0, button.getWidth() + radius, button.getHeight() - 1, radius, radius);
RapidLookTools.drawButtonBorder(button, g, borderShape);
break;
case SwingConstants.CENTER:
borderShape = new Rectangle2D.Double(0, 0, button.getWidth() + radius, button.getHeight() - 1);
RapidLookTools.drawButtonBorder(button, g, borderShape);
break;
default:
borderShape = new RoundRectangle2D.Double(-radius, 0, button.getWidth() + radius - 1, button.getHeight() - 1, radius, radius);
RapidLookTools.drawButtonBorder(button, g, borderShape);
// special case, right button has a left border
borderShape = new Line2D.Double(0, 0, 0, button.getHeight());
RapidLookTools.drawButtonBorder(button, g, borderShape);
break;
}
}
private void createDeitiesPanel(World world, int infoPanelWidth, int infoPanelHeight, JPanel infoPanel) {
JPanel deitiesPanel = JPanelFactory.createJPanel("Deities");
deitiesPanel.setLayout(null);
deitiesPanel.setBounds(510, 363, infoPanelWidth + 5, infoPanelHeight);
infoPanel.add(deitiesPanel, DEITIES_KEY);
DeityAttributes deityAttributes = GroupPropertyUtils.getVillagersOrganization(world).getProperty(Constants.DEITY_ATTRIBUTES);
String deityTooltip = "deity hapiness indicator: if a deity becomes unhappy, they may lash out against the population";
for(int i=0; i<Deity.ALL_DEITIES.size(); i++) {
Deity deity = Deity.ALL_DEITIES.get(i);
Image image = imageInfoReader.getImage(deity.getBoonImageId(), null);
JLabel nameLabel = JLabelFactory.createJLabel(deity.getName(), image);
nameLabel.setBounds(15, 30 + 40 * i, 150, 50);
nameLabel.setHorizontalAlignment(SwingConstants.LEFT);
nameLabel.setToolTipText(deityTooltip);
deitiesPanel.add(nameLabel);
JProgressBar relationshipProgresBar = JProgressBarFactory.createHorizontalJProgressBar(deityAttributes.getMinHapinessValue(), deityAttributes.getMaxHapinessValue(), imageInfoReader);
relationshipProgresBar.setBounds(175, 40 + 40 * i, 300, 30);
relationshipProgresBar.setValue(deityAttributes.getHappiness(deity));
relationshipProgresBar.setToolTipText(deityTooltip);
deitiesPanel.add(relationshipProgresBar);
}
}
public PluginErrorPanel()
{
setOpaque(false);
setBorder(new EmptyBorder(50, 10, 0, 10));
setLayout(new BorderLayout());
noResultsTitle.setForeground(Color.WHITE);
noResultsTitle.setHorizontalAlignment(SwingConstants.CENTER);
noResultsDescription.setFont(FontManager.getRunescapeSmallFont());
noResultsDescription.setForeground(Color.GRAY);
noResultsDescription.setHorizontalAlignment(SwingConstants.CENTER);
add(noResultsTitle, BorderLayout.NORTH);
add(noResultsDescription, BorderLayout.CENTER);
setVisible(false);
}
protected void addSeperatorToPanel(JPanel addTarget) {
if (!(addTarget.getLayout() instanceof GridBagLayout)) {
throw new RuntimeException("JPanel with GridBagLayout is mandatory!");
}
JSeparator separator = new JSeparator(SwingConstants.HORIZONTAL);
GridBagConstraints itemConstraint = new GridBagConstraints();
itemConstraint.gridx = GridBagConstraints.RELATIVE;
itemConstraint.weightx = 1.0;
itemConstraint.gridwidth = GridBagConstraints.REMAINDER; // end row
itemConstraint.fill = GridBagConstraints.HORIZONTAL;
itemConstraint.insets = new Insets(0, 5, 5, 5);
addTarget.add(separator, itemConstraint);
}
private void createSettingsLabel(String label, Container cont){
JLabel labelField = new JLabel(label);
labelField.setHorizontalAlignment(SwingConstants.LEFT);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.insets = new Insets(0, 10, 0, 0);
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
cont.add(labelField, gbc);
}
@Override
protected Insets getTabInsets(int tabPlacement, int tabIndex) {
Insets t = new Insets(8, 8, 8, 8);
if (tabPlacement == SwingConstants.TOP) {
t.top = t.bottom = 6;
if (isDockingFrameworkTab) {
t.left = 5;
t.right = -10;
}
}
return t;
}
static void init(int length, boolean hex, JFormattedTextField text) {
ValueFormatter formatter = new ValueFormatter(length, hex);
text.setColumns(length);
text.setFormatterFactory(new DefaultFormatterFactory(formatter));
text.setHorizontalAlignment(SwingConstants.RIGHT);
text.setMinimumSize(text.getPreferredSize());
text.addFocusListener(formatter);
}
private JLabel getLabel(String text) {
JLabel lbl = new JLabel(text);
lbl.setForeground(Color.WHITE);
lbl.setFont(FontsAndBorders.FONT0);
lbl.setHorizontalAlignment(SwingConstants.CENTER);
return lbl;
}
/**
* Constructor
*/
public DoubleRenderer() {
super();
numberField = new NumberField(0);
setHorizontalAlignment(SwingConstants.RIGHT);
setBackground(Color.WHITE);
}
/**
* Create the dialog.
*/
public ProgressDialog()
{
setUndecorated(true);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setAlwaysOnTop(true);
setResizable(false);
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(screen.width - 450, 0, 450, 200);
getContentPane().setLayout(
new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
Component glue = Box.createGlue();
getContentPane().add(glue);
JLabel lblImage = new JLabel("HookManager");
lblImage.setFont(new Font("Verdana", Font.BOLD, 40));
lblImage.setAlignmentX(Component.CENTER_ALIGNMENT);
lblImage.setHorizontalAlignment(SwingConstants.CENTER);
getContentPane().add(lblImage);
{
lblProgress =
new JLabel("<html>\r\n<center>\r\n<h1>Updating...</h1>");
lblProgress.setAlignmentX(Component.CENTER_ALIGNMENT);
lblProgress.setFont(new Font("Verdana", Font.PLAIN, 16));
getContentPane().add(lblProgress);
lblProgress.setHorizontalAlignment(SwingConstants.CENTER);
}
Component glue_1 = Box.createGlue();
getContentPane().add(glue_1);
}
public JCheckBoxTableHeaderCellRenderer() {
jCheckBox = new JCheckBox();
jCheckBox.setFont(UIManager.getFont("TableHeader.font"));
jCheckBox.setBorder(UIManager.getBorder("TableHeader.cellBorder"));
jCheckBox.setBackground(UIManager.getColor("TableHeader.background"));
jCheckBox.setForeground(UIManager.getColor("TableHeader.foreground"));
jCheckBox.setHorizontalAlignment(SwingConstants.CENTER);
jCheckBox.setBorderPainted(true);
}
/**
* Basic constructor, to set common characteristics.
*
* @param controller the related glyphs controller, if any
* @param useSpinners true for use of spinners
* @param selected true if board must be initially selected
*/
public GlyphBoard (GlyphsController controller,
boolean useSpinners,
boolean selected)
{
super(Board.GLYPH, (EntityService<Glyph>) controller.getGlyphService(), selected);
this.controller = controller;
groupField.setHorizontalAlignment(SwingConstants.CENTER);
groupField.setToolTipText("Assigned group(s)");
defineLayout();
}
@Override
protected void paintContentBorder(Graphics g, int tabPlacement, int selectedIndex) {
// Calculate the content area
int width = tabPane.getWidth();
int height = tabPane.getHeight();
Insets insets = tabPane.getInsets();
int x = insets.left;
int y = insets.top;
// Adjust for tabs. Only top and bottom positions are supported for now.
int tabHeight = calculateTabAreaHeight(tabPlacement, runCount, maxTabHeight);
switch (tabPlacement) {
case SwingConstants.TOP:
y += tabHeight;
break;
default:
// keep at top
}
height -= tabHeight;
// Drawing the background is this method's responsibility, even though
// Thats not obvious from the name
StyleUtil.fillBackground(style, g, x, y, width, height);
// Then the actual border
style.getBorder().paintBorder(tabPane, g, x, y, width, height);
// Paint background over the area between the selected tab and the
// content area
int selected = tabPane.getSelectedIndex();
Rectangle r = getTabBounds(selected, calcRect);
r = r.intersection(new Rectangle(x, y, width, height));
// Find out the border width
int bwidth = style.getBorder().getBorderInsets(tabPane).left;
StyleUtil.fillBackground(style, g, r.x + bwidth, r.y,
r.width - 2 * bwidth, r.height);
}
public Component getLayoutComponent(int constraint) {
if (constraint == SwingConstants.NORTH) return north;
if (constraint == SwingConstants.WEST) return west;
if (constraint == SwingConstants.SOUTH) return south;
if (constraint == SwingConstants.EAST) return east;
if (constraint == SwingConstants.CENTER) return center;
throw new IllegalArgumentException("Illegal constraint: " + // NOI18N
constraintName(constraint));
}
public static void main(String[] args) {
if(OSInfo.getOSType() != OSInfo.OSType.WINDOWS){
return;
}
bug6416920 test = new bug6416920();
test.layout.padSelectedTab(SwingConstants.TOP, 0);
if (test.rects[0].width < 0) {
throw new RuntimeException("A selected tab isn't painted properly " +
"in the scroll tab layout under WindowsLookAndFeel " +
"in Windows' \"Windows XP\" theme.");
}
}
protected JComponent makeTextPanel(String text) {
JPanel panel = new JPanel(false);
JLabel filler = new JLabel(text);
filler.setHorizontalAlignment(SwingConstants.CENTER);
panel.setLayout(new GridLayout(1, 1));
panel.add(filler);
return panel;
}
/** Creates a new instance of NoWebServiceClientsPanel */
public NoWebServiceClientsPanel(String text) {
setLayout(new GridBagLayout());
label = new JLabel(text);
label.setVerticalAlignment(SwingConstants.CENTER);
label.setHorizontalAlignment(SwingConstants.CENTER);
GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(label, gridBagConstraints);
}
private void installExtraComponents(Container container,
List<JComponent> components, boolean forceReinstall) {
if (components == null)
components = new ArrayList<>();
Component[] oldComponents = container.getComponents();
if (!Arrays.asList(oldComponents).equals(components)) {
forceReinstall = true;
}
if (forceReinstall) {
container.removeAll();
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 100;
c.weightx = 1;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;
for (JComponent jc : components) {
container.add(jc, c);
if (tabs.getTabPlacement() == SwingConstants.LEFT) {
c.gridy--;
} else if (tabs.getTabPlacement() == SwingConstants.RIGHT) {
c.gridy++;
} else {
c.gridx++;
}
jc.removeComponentListener(extraComponentListener);
jc.addComponentListener(extraComponentListener);
for (Component oldComponent : oldComponents) {
if (components.contains(oldComponent)) {
oldComponent
.removeComponentListener(extraComponentListener);
}
}
}
container.revalidate();
}
refreshExtraContainerVisibility();
}
/**
* Constructor.
*
* @param parentComponent Parent component.
*/
public LanguageSelector(Component parentComponent) {
this.parentComponent = parentComponent;
this.changeListeners = new ArrayList<>();
// Create combo box
Configuration configuration = Configuration.getConfiguration();
EnumLanguage defaultLanguage = configuration.getLanguage();
combo = new JComboBox<>(EnumLanguage.getList().toArray(new EnumLanguage[0]));
combo.setEditable(false);
combo.setSelectedItem(defaultLanguage);
combo.addItemListener(EventHandler.create(
ItemListener.class, this, "notifyLanguageChange"));
// Create label
label = Utilities.createJLabel(GT._T("Language"));
label.setLabelFor(combo);
label.setHorizontalAlignment(SwingConstants.TRAILING);
// Create button
toolbar = new JToolBar(SwingConstants.HORIZONTAL);
toolbar.setFloatable(false);
toolbar.setBorderPainted(false);
JButton buttonLanguageInfo = Utilities.createJButton(
"tango-help-browser.png", EnumImageSize.SMALL,
GT._T("Other Language"), false, null);
buttonLanguageInfo.addActionListener(EventHandler.create(
ActionListener.class, this, "actionOtherLanguage"));
toolbar.add(buttonLanguageInfo);
}
/**
* Builds the details panel for the given nation type.
*
* @param nationType - the IndianNationType
* @param panel the panel to use
*/
private void buildIndianNationTypeDetail(IndianNationType nationType,
JPanel panel) {
List<RandomChoice<UnitType>> skills = nationType.getSkills();
panel.setLayout(new MigLayout("wrap 2, gapx 20", "", ""));
JLabel name = Utility.localizedHeaderLabel(nationType, FontLibrary.FontSize.SMALL);
panel.add(name, "span, align center, wrap 40");
panel.add(Utility.localizedLabel("colopedia.nationType.aggression"));
panel.add(Utility.localizedLabel("colopedia.nationType."
+ nationType.getAggression().getKey()));
panel.add(Utility.localizedLabel("colopedia.nationType.settlementNumber"));
panel.add(Utility.localizedLabel("colopedia.nationType."
+ nationType.getNumberOfSettlements().getKey()));
panel.add(Utility.localizedLabel("colopedia.nationType.typeOfSettlements"));
panel.add(new JLabel(Messages.getName(nationType.getCapitalType()),
new ImageIcon(getImageLibrary()
.getScaledSettlementTypeImage(nationType.getCapitalType())),
SwingConstants.CENTER));
List<String> regionNames = toList(map(nationType.getRegions(),
n -> Messages.getName(n)));
panel.add(Utility.localizedLabel("colopedia.nationType.regions"));
panel.add(new JLabel(join(", ", regionNames)));
panel.add(Utility.localizedLabel("colopedia.nationType.skills"), "top, newline 20");
GridLayout gridLayout = new GridLayout(0, 2);
gridLayout.setHgap(10);
JPanel unitPanel = new JPanel(gridLayout);
unitPanel.setOpaque(false);
for (RandomChoice<UnitType> choice : skills) {
unitPanel.add(getUnitButton(choice.getObject()));
}
panel.add(unitPanel);
}
@Override
public void paintBorder( Component c, Graphics g, int x, int y, int width, int height ) {
if( origBorder != null )
origBorder.paintBorder( c, g, x, y, width, height );
if( sortIcon != null ) {
int xi = x + ((width - sortIcon.getIconWidth()) / 2);
int yi = (sortIconPosition == SwingConstants.TOP)
? y + UIScale.scale( 1 )
: y + height - sortIcon.getIconHeight()
- 1 // for gap
- (int) (1 * UIScale.getUserScaleFactor()); // for bottom border
sortIcon.paintIcon( c, g, xi, yi );
}
}
/**
* Converts {@code Label} alignment constant to the {@code JLabel} constant.
* If wrong Label alignment provided returns default alignment.
*
* @param alignment {@code Label} constant.
*
* @return {@code JLabel} constant.
*/
private static int convertAlignment(final int alignment) {
switch (alignment) {
case Label.CENTER:
return SwingConstants.CENTER;
case Label.RIGHT:
return SwingConstants.RIGHT;
default:
return SwingConstants.LEFT;
}
}
/**
* JSpinField constructor with given minimum and maximum vaues and initial
* value 0.
*/
public JSpinField(int min, int max) {
super();
setName("JSpinField");
this.min = min;
if (max < min)
max = min;
this.max = max;
value = 0;
if (value < min)
value = min;
if (value > max)
value = max;
darkGreen = new Color(0, 150, 0);
setLayout(new BorderLayout());
textField = new JTextField();
textField.addCaretListener(this);
textField.addActionListener(this);
textField.setHorizontalAlignment(SwingConstants.RIGHT);
textField.setBorder(BorderFactory.createEmptyBorder());
textField.setText(Integer.toString(value));
textField.addFocusListener(this);
spinner = new JSpinner() {
private static final long serialVersionUID = -6287709243342021172L;
private JTextField textField = new JTextField();
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
return new Dimension(size.width, textField.getPreferredSize().height);
}
};
spinner.setEditor(textField);
spinner.addChangeListener(this);
// spinner.setSize(spinner.getWidth(), textField.getHeight());
add(spinner, BorderLayout.CENTER);
}