Witam.
Prosze o pomoc w niniejszym kodzie. Jak nadpisuje metode paint w JPanel to po zaladowaniu do niego JButtona pojawia sie on dopiero jak na niego najade myszka. Tak samo jak zaladuje jakis obrazek to pojawia sie on dopiero jak okno przesune w lewa strone ekranu i mi ja wtedy repaintuje. Co jest nie tak?
public class Book {
/**
* @param args
*/
public static void main(String[] args) {
JFrame frame = new Ramka();
}
}
class Ramka extends JFrame
{
public static Image img;
public Ramka(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setResizable(false);
setTitle(">>Wstawianie Zdjec<<");
setSize(700,700);
//Panele
//dzielimy na polowe
Container panel = getContentPane();
panel.setLayout(new GridLayout(0,2));
//dzielimy na 2 gridy poziome lew strone
JPanel lewy = new JPanel();
lewy.setLayout(new GridLayout(2,0));
panel.add(lewy);
//lewa gora: dzielimy na 2 czesci gorna i dolna, dolna o wiele mniejsza dla buttona
final JPanel gora = new BackgroundPanel();
gora.setLayout(new BorderLayout());
lewy.add(gora);
//GridBagConstraints c = new GridBagConstraints();
//c.gridwidth = GridBagConstraints.REMAINDER;
//gora.add(new JLabel("gora"),c);
//c.gridwidth = GridBagConstraints.REMAINDER;
//c.fill = GridBagConstraints.NORTH;
//c.fill=GridBagConstraints.EAST;
final JButton cos = new JButton("Zaladuj zdjecie");
gora.add(cos,BorderLayout.PAGE_END);
gora.repaint();
cos.repaint();
cos.setVisible(true);
cos.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource()==cos)
{
//ladujemy JFileChoosera i pozniej ladujemy zdjecie
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
//System.out.println(chooser.getSelectedFile().getPath());
img = Toolkit.getDefaultToolkit().createImage(chooser.getSelectedFile().getPath());
gora.repaint();
}
}
});
lewy.add(new JLabel("dol"));
panel.add(new JLabel("tekst2"));
}
}
class BackgroundPanel extends JPanel
{
// The Image to store the background image in.
public void paint(Graphics g)
{
super.paintComponent(g);
// Draws the img to the BackgroundPanel.
if(Ramka.img == null) {
//rysujemy kwadracik i go zapelniamy color.darkgray
Graphics2D g2 = (Graphics2D)g;
Rectangle2D pros = new Rectangle2D.Double(0,0,2000,2000);
g2.setPaint(Color.DARK_GRAY);
g2.fill(pros);
//g2.draw(pros);
}
else g.drawImage(Ramka.img, 0, 0, null);
}
}