void setHorizontalTextPosition(int textPosition)
void setVerticalTextPosition(int textPosition)
void setHorizontalAlignment(int alignment)
void setVerticalAlignment(int alignment)
import javax.swing.*;
import java.awt.*;
public class Main {
private static class ColorfulLabel extends JLabel {
private static final long serialVersionUID = 1L;
ColorfulLabel(String text,Color color)
{
super(text);
setFont(new Font(null, Font.PLAIN, 20));
setBackground(color);
setOpaque(true);
setPreferredSize(new Dimension(100, 100));
setHorizontalAlignment(SwingConstants.CENTER);
setVerticalAlignment(SwingConstants.BOTTOM);
}
}
public static void main(String[] args) throws AWTException {
JFrame jf = new JFrame("测试窗口");
jf.setSize(500, 300);
jf.setLocationRelativeTo(null);
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new FlowLayout());
JLabel lab1 = new ColorfulLabel("1",Color.CYAN);
JLabel lab2 = new ColorfulLabel("2",Color.YELLOW);
JLabel lab3 = new ColorfulLabel("3",Color.ORANGE);
panel.add(lab1);
panel.add(lab2);
panel.add(lab3);
jf.setContentPane(panel);
jf.setVisible(true);
}
}