public static void initialize(){ /* Since trying Java 8, started to get weird behavior on a Linux cluster. Issue raises from GUI now trying to write on disk (ie due to Fonts...). However, that sometimes strangely fails, even though executed before any sandbox. It happens quite often on cluster experiments, but was not able to reproduce it to debug :( As workaround, we try here to load default file system (it would happen anyway when loading fonts in Java 8), but do not crash the test suite (ie throw exception here in this method, which is usually called from a @BeforeClass). Reason is that maybe not all tests will access GUI. */ try{ FileSystems.getDefault(); } catch(Throwable t){ logger.error("Failed to load default file system: "+t.getMessage()); return; } /* * Force the loading of fonts. * This is needed because font loading in the JVM can take several seconds (done only once), * and that can mess up the JUnit test execution timeouts... */ (new javax.swing.JButton()).getFontMetrics(new java.awt.Font(null)); }
void adjustDimension(JButton component) { FontMetrics metrics = component.getFontMetrics(component.getFont()); int width = metrics.stringWidth(component.getText()); component.setPreferredSize(new Dimension(width + 32, controlHeight)); component.setBounds(new Rectangle(component.getLocation(), component.getPreferredSize())); }
public static void equalizeButtonSizes(Graphics g, JButton... buttons) { String[] labels = BeanUtil.extractProperties(buttons, "text", String.class); // Get the largest width and height Dimension maxSize = new Dimension(0, 0); Rectangle2D textBounds = null; JButton button0 = buttons[0]; FontMetrics metrics = button0.getFontMetrics(button0.getFont()); for (int i = 0; i < labels.length; ++i) { textBounds = metrics.getStringBounds(labels[i], g); maxSize.width = Math.max(maxSize.width, (int) textBounds.getWidth()); maxSize.height = Math.max(maxSize.height, (int) textBounds.getHeight()); } Insets insets = button0.getBorder().getBorderInsets(button0); maxSize.width += insets.left + insets.right; maxSize.height += insets.top + insets.bottom; // reset preferred and maximum size since BoxLayout takes both into account for (JButton button : buttons) { button.setPreferredSize((Dimension) maxSize.clone()); button.setMaximumSize((Dimension) maxSize.clone()); } }
JButton component = new JButton(text); FontMetrics fontMetrics = component.getFontMetrics(component.getFont()); LineMetrics metrics = fontMetrics.getLineMetrics(text, component.getGraphics()); float ascent = metrics.getAscent(), descent = metrics.getDescent(); component.setAlignmentY(ascent / (ascent + descent));