JPanel を拡張し、L のように見える新しいクラス LShapePanel を定義しました。
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);
}
}
これらの LShapePanels の 2 つを次のように配置したいと思います。
でも方法がわからない?これは、2 つの LShapePanels を連続して配置するための私のコードです。
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);
}
});
}
}
そして結果: