I am trying to create a resizable window with Swing and AWT components which displays numbers in a pyramid fashion depending on what the frame is sized to but I have no idea really where to start. I am not sure if I am supposed to use JLabel or StringBuilder. If it can be done without using action listeners, that would be preferred. I need some assistance.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
I would simply create a dedicated panel and override the method paintComponent. Then using the FontMetrics and the size of that panel, I would iterate and fill the panel with a pyramid.
Here is an example of what I am mentionning (although there is still a problem when the number of digits increases, but I will let you fix this problem):
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestPyramid {
private static class PyramidPanel extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setFont(new Font("Courier", Font.PLAIN, 11));
FontMetrics fm = g.getFontMetrics();
fm.getHeight();
int i = 0;
int y = 0;
int n = 1;
while (y + fm.getHeight() < getHeight()) {
int x = getWidth() / 2;
StringBuilder sb = new StringBuilder();
for (int j = 0; j < 2 * i + 1; j++) {
String v = String.valueOf(n++);
sb.append(v);
for (int fill = 0; fill < 4 - v.length(); fill++)
sb.append(" ");
}
String text = sb.toString();
int stringWidth = fm.stringWidth(text);
if (stringWidth > getWidth()) {
break;
}
x -= stringWidth / 2;
y += fm.getHeight();
g.drawString(text, x, y);
i++;
}
}
}
protected void initUI() {
JFrame frame = new JFrame(TestPyramid.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new PyramidPanel());
frame.setSize(400, 200);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TestPyramid().initUI();
}
});
}
}