Adjust the text on the button, then check the "preferred width" of the button. If it is too large, adjust the text accordingly.
Here is an example with two buttons at the top:
private static int BUTTON_WIDTH = 90; // Adjust this as necessary public static void main(String[] args) { JFrame frame = new JFrame(); JPanel pnl = new JPanel(); JButton btn1 = new JButton(getBtnDisplayStr("Table H/V",null,"909.0 / 500.0")); if (btn1.getPreferredSize().width > BUTTON_WIDTH) { btn1.setText(getBtnDisplayStr("Table H/V", "909.0 /", "500.0")); } JButton btn2 = new JButton(getBtnDisplayStr("Acq/ISD",null,"1 / 1")); if (btn2.getPreferredSize().width > BUTTON_WIDTH) { btn2.setText(getBtnDisplayStr("Acq/ISD","1 /","1")); } pnl.add(btn1,BorderLayout.LINE_START); pnl.add(btn2,BorderLayout.LINE_END); frame.add(pnl); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } private static String getBtnDisplayStr(String name, String valueLine1, String valueLine2) { StringBuilder sBuilder = new StringBuilder(); sBuilder.append("<html><center><b>"); sBuilder.append(name); sBuilder.append("</b><br/>"); if (valueLine1 != null) { sBuilder.append("<font size=\"2\">"); sBuilder.append(valueLine1); sBuilder.append("</font>"); } sBuilder.append("<br/>"); if (valueLine2 != null) { sBuilder.append("<font size=\"2\">"); sBuilder.append(valueLine2); sBuilder.append("</font>"); } sBuilder.append("<br/>"); sBuilder.append("</center></html>"); return sBuilder.toString(); }
source share