我定义了一个新类 LShapePanel,它扩展了 JPanel,看起来像一个 L。
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
public class LShapePanel extends JPanel{
public Color color;
public LShapePanel(Color color) {
this.color = color;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(color);
/* coordinates for polygon */
int[] xPoints = {0,100,100,20,20,0};
int[] yPoints = {0,0,20,20,100,100};
/* draw polygon */
g2d.fillPolygon(xPoints, yPoints, 6);
}
}
我想像这样安排其中两个 LShapePanel:
但我不知道怎么做?这是我连续排列两个 LShapePanel 的代码。
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Dimension;
public class DifferentShapes extends JFrame {
public DifferentShapes() {
setTitle("different shapes");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocation(500, 300);
JPanel panel = new JPanel();
/* create and add first L in red */
LShapePanel lsp1 = new LShapePanel(new Color(255,0,0));
lsp1.setPreferredSize(new Dimension(100,100));
panel.add(lsp1);
/* create and add second L in green*/
LShapePanel lsp2 = new LShapePanel(new Color(0,255,0));
lsp2.setPreferredSize(new Dimension(100,100));
panel.add(lsp2);
add(panel);
pack();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
DifferentShapes df = new DifferentShapes();
df.setVisible(true);
}
});
}
}
结果: