gpt4 book ai didi

java - 修改 ArrayList 中所有 JPanel 的字体大小

转载 作者:行者123 更新时间:2023-11-29 08:01:35 25 4
gpt4 key购买 nike

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

最佳答案

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

enter image description here

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);
}
});
}
}

关于java - 修改 ArrayList<JPanel> 中所有 JPanel 的字体大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14102692/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com