画像を描画するために paintComponent メソッドがオーバーライドされるカスタム JPanel があります。
これらのカスタム パネルのいくつかをコンテナの垂直方向の中央に挿入したいと考えています。これを行うために、レイアウト マネージャーとして BoxLayout.X_AXIS を使用して jpanel を作成しました。
これはうまく機能し、私が望むものを示していますが、カスタム パネル間にマージンを追加したいと考えています。
EmptyMargins は単に無視されます。トリッキーな部分は、コンテナーのすべてのコンポーネントを取得するループから各カスタム パネルを取得する必要があるため、ストラットまたはボックスをそれらの間に追加できない (または追加したくない...) ことです。それらを CustomPanel にキャストします。
問題を参照してください。パネル間にストラットを追加すると、キャスト例外が発生し、EmptyBorders が機能しません...どんなアイデアも歓迎します!
注: 他のレイアウト マネージャーの提案も受け付けています。;-)
コードは次のとおりです。
public class StackExemple {
public StackExemple() {
JFrame frame = new JFrame();
frame.setPreferredSize(new Dimension(600, 300));
JPanel container = new JPanel();
container.setPreferredSize(new Dimension(600, 300));
container.setLayout(new BoxLayout(container, BoxLayout.X_AXIS));
CustomPanel customPanel1 = new CustomPanel();
CustomPanel customPanel2 = new CustomPanel();
CustomPanel customPanel3 = new CustomPanel();
container.add(customPanel1);
container.add(customPanel2);
container.add(customPanel3);
frame.getContentPane().add(container);
frame.pack();
frame.setVisible(true);
//Loop which takes the custompanels
for(Component comp : container.getComponents()) {
CustomPanel panel = (CustomPanel)comp;
//DO SOMETHING
System.out.println("Hello World");
}
}
private class CustomPanel extends JPanel{
private BufferedImage image;
public CustomPanel() {
setPreferredSize(new Dimension(100, 100));
setMinimumSize(getPreferredSize());
setMaximumSize(getPreferredSize());
setBorder(BorderFactory.createEmptyBorder(0,50,0,0));
setBackground(Color.RED);
// try {
// image = ImageIO.read(ClassLoader.getSystemClassLoader().getResource("Ressources/img.png"));
// } catch (IOException ex) {
// System.out.println("Ooops... ");
// }
}
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
// int x = (this.getWidth() - image.getWidth()) / 2;
// int y = (this.getHeight() - image.getHeight()) / 2;
// g.drawImage(image, x, y, null);
}
}
}