Ahoj, snazim se udelat jednoduche kreslitko.
Trida imgPanel je potomkem tridy javax.swing.JPanel a prekryva metodu paintComponent:
package gui;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
public class imgPanel extends JPanel{
private BufferedImage buffer;
private int sirka;
private int vyska;
public imgPanel() {
sirka = 200;
vyska = 200;
buffer = new BufferedImage(sirka, vyska, BufferedImage.TYPE_3BYTE_BGR);
}
@Override
public void paintComponent(Graphics g) {
prepareImage();
g.drawImage(buffer, 0, 0, null);
g.dispose();
}
private void prepareImage() {
Graphics g = buffer.createGraphics();
g.drawLine(5, 5, 20, 50);
g.setColor(Color.BLUE);
g.dispose();
}
public int getSirka() {
return sirka;
}
public void setSirka(int sirka) {
this.sirka = sirka;
}
public int getVyska() {
return vyska;
}
public void setVyska(int vyska) {
this.vyska = vyska;
}
}
A trida Okno pak pomoci JPanelu z tridy imgOkno zobrazi jednoduche kreslitko:
package gui;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class Okno extends JFrame {
private JPanel contentPane;
private JPanel abc;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Okno frame = new Okno();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Okno() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
abc = new imgPanel();
/* System.out.println(abc.getVyska); */
contentPane.add(abc, BorderLayout.CENTER);
}
}
Kdyz se ale snazim v tride Okno zavolat metodu tridy imgPanel getVyska(), tak program vzdy spadne pri kompilaci.
Nevite, cim to muze byt?