هنا و فى هذا الكود البسيط أواجه مشكلتان :
--------------------------------------------------
1- قمت بإنشاء panel صفراء اللون ، أريدها فى منتصف ال panel الأم قمت بعمل ذاك :
x = testGame.getPanel().getWidth() / 2;
y = testGame.getPanel().getHeight() / 2;
setLocation(x, y);و لكنها لم تظهر فى المنتصف . لماذا ؟؟
و أريد أن أُظهر صورة على هذه ال Panel الصفراء و قمت فعلاً برسمها و لكنها لم تظهر لماذا ؟!!
الكود :
----------------
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TestGame extends JFrame {
private JPanel panel;
private MainPanel mainPanel;
public TestGame() {
panel = new JPanel();
mainPanel = new MainPanel(this);
panel.add(mainPanel);
getContentPane().add(panel);
}
public JPanel getPanel() {
return panel;
}
public static void main(String[] args) {
TestGame testGame = new TestGame();
testGame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
testGame.setSize(new Dimension(600, 300));
testGame.setLocationRelativeTo(null);
testGame.setVisible(true);
testGame.setExtendedState(MAXIMIZED_BOTH);
}
}
--------------------------------------------------------------------------------------------------------
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class MainPanel extends JPanel {
private int x, y;
private ImageIcon imageIcon;
public MainPanel(TestGame testGame) {
x = testGame.getPanel().getWidth() / 2;
y = testGame.getPanel().getHeight() / 2;
setLocation(x, y);
setPreferredSize(new Dimension(200, 400));
setBackground(Color.YELLOW);
///////////////////////////////////////////////////////////////
imageIcon = new ImageIcon("F.bmp");
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(imageIcon.getImage(), 200, y, this);
}
}الكود مرفق و مع الصورة .
شكراً