【问题标题】:Modifying the font size for all JPanels in an ArrayList<JPanel>修改 ArrayList<JPanel> 中所有 JPanel 的字体大小
【发布时间】:2012-12-15 16:15:37
【问题描述】:

所以,我有一个包含 JPanels 的 ArrayList;所有的 JPanel 都有一个 BorderLayout,在 NORTH 上设置了一个 JPanel(包含两个 JLabel),在 CENTER 上设置了一个 JTextArea(当然包含文本)。我的问题是如何修改每个 JTextArea 的字体大小?

【问题讨论】:

  • 您可能需要查看PLAFUIManager

标签: java swing jpanel jtextarea font-size


【解决方案1】:

这里有一些简单的代码,允许通过setFontSize(int index, int fontSize) 方法设置JTextArea 字体大小。请注意,这仅适用于 panels 数组列表中的文本区域。在下面的示例中,我更改了文本区域 #1 和 #3 上的字体(有关执行此操作的调用,请参见 main 方法)。

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.util.ArrayList;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class SimpleFrame extends JFrame {
   ArrayList<JPanel> panels = new ArrayList<JPanel>();

   public SimpleFrame() {
      super("Simple Panel List Example");

      JPanel content = (JPanel)getContentPane();
      content.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));

      // add some panels to the array list
      for(int i = 0; i < 5; i++) {
         BorderLayout b = new BorderLayout();
         JPanel p = new JPanel(b);
         JLabel north = new JLabel("Label #"+i);
         JTextArea center = new JTextArea("TextArea #"+i);
         p.add("North", north);
         p.add("Center", center);

         panels.add(p);
         content.add(p);
      }
   }

   // change the font size of the JTextArea on panel #i
   public void setFontSize(int i, int fontSize) {
      JPanel p = panels.get(i);
      JTextArea t = (JTextArea)((BorderLayout)p.getLayout()).getLayoutComponent("Center");
      Font f = t.getFont();
      Font f2 = f.deriveFont((float)fontSize);
      t.setFont(f2);
   }

   public static void main(String[] argv) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            SimpleFrame c = new SimpleFrame();
            c.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            c.pack();
            c.setVisible(true);

            // we can change the font size using our setFontSize method
            c.setFontSize(1, 8);
            c.setFontSize(3, 16);
         }
      });
   }
}

【讨论】:

  • 建议使用 SwingUtilities.invokeLater 方法启动 swing。谷歌一下。
  • 好点@vels4j,谢谢。我已经相应地编辑了代码。
猜你喜欢
  • 1970-01-01
  • 2014-01-13
  • 2011-12-16
  • 1970-01-01
  • 2011-07-10
  • 2013-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多