Java GUI button's label can't be seen

江枫思渺然 提交于 2019-12-01 22:14:28

Your problem is that you set the button sizes to begin with. If you instead leave the JButtons and the GUI to size itself using proper layout managers and calling pack() on the JFrame, you will get a decent looking GUI that shows all the text in any OS. Solution: don't use null layouts, don't call setBounds(...), read up on and use appropriate layout managers held in nested JPanels, and let these layout managers do all the heavy layout lifting for you.

For example, you could create a grid of buttons using a GridLayout, and alter the size of the grid and the buttons by simply changing the font size of the button. For example run the code below twice, changing the button font size (in the code below, the float constant BTN_FONT_SIZE) and seeing how the GUI automatically accommodates the button font by resizing the button to its optimal size.

import java.awt.GridLayout;
import javax.swing.*;

public class CalcEg {
   private static final float BTN_FONT_SIZE = 20f;  // **** try using 40f here ****
   private static final String[][] BTN_LABELS = {
      {"7", "8", "9", "-"},
      {"4", "5", "6", "+"},      
      {"1", "2", "3", "/"},
      {"0", ".", " ", "="}
   };
   private JPanel mainPanel = new JPanel();

   public CalcEg() {
      int rows = BTN_LABELS.length;
      int cols = BTN_LABELS[0].length;
      int gap = 4;
      mainPanel.setBorder(BorderFactory.createEmptyBorder(gap, gap, gap, gap));
      mainPanel.setLayout(new GridLayout(rows, cols, gap, gap));
      for (String[] btnLabelRow : BTN_LABELS) {
         for (String btnLabel : btnLabelRow) {
            JButton btn = createButton(btnLabel);
            // add ActionListener to btn here
            mainPanel.add(btn);
         }
      }
   }

   private JButton createButton(String btnLabel) {
      JButton button = new JButton(btnLabel);
      button.setFont(button.getFont().deriveFont(BTN_FONT_SIZE));
      return button;
   }

   public JComponent getMainComponent() {
      return mainPanel;
   }

   private static void createAndShowGui() {
      CalcEg mainPanel = new CalcEg();

      JFrame frame = new JFrame("CalcEg");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel.getMainComponent());
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

If you nest the button JPanel into a BorderLayout using JPanel and add a JTextField to its PAGE_START or the NORTH end, and you play with different font sizes, you'll see something like this:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!