我在JAVA中有这段代码
`
public class Okno extends JFrame{
Pixel p;
private int x_zac, y_zac, x_kon, y_kon; //zaciatoca a koncova pozicia ciary
private int x_kruh, y_kruh; //suradnice kruhu
int poc_ciar=0; // premenna na pocitanie poctu vytvorenych ciar
int cokreslim=0; // pomocna premenna na urcovanie kreslenia ciar=0 alebo kruhov=1
Canvas can = new Canvas();
JButton kruh = new JButton("kruh");
JButton ciara = new JButton("ciara");
GridBagConstraints c = new GridBagConstraints();
Kreslenie_vypocty vypocty = new Kreslenie_vypocty();
Okno(Pixel p1){
setSize(800, 700);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
setResizable(false);
c.gridx = 0;
c.gridy = 0;
c.insets= new Insets(10, 10, 10, 10);
add(kruh,c);
c.gridx = 1;
c.gridy = 0;
c.insets= new Insets(10, 10, 10, 10);
add(ciara,c);
c.gridx = 2;
c.gridy = 0;
add(can,c);
can.setSize(500,700);
can.setBackground(Color.gray);
can.addMouseListener(new MouseListener() {
public void drawCenteredCircle(Graphics2D g, int x, int y, int r) {
x = x-(r/2);
y = y-(r/2);
g.fillOval(x,y,r,r);
}
public void mouseClicked(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
p.c.add(new Ciara());
x_zac = e.getX();
y_zac = e.getY();
}
public void mouseReleased(MouseEvent e) {
x_kon = e.getX();
y_kon = e.getY();
repaint();
vypocty.vypocet_bodov(x_zac, y_zac, x_kon, y_kon, p, poc_ciar);
poc_ciar++;
}
});
//can.setVisible(true);
p=p1;
kruh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cokreslim=1;
}
});
ciara.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cokreslim=0;
}
});
}
public void paint(Graphics g){
g=can.getGraphics();
g.setColor(Color.red);
if (cokreslim==0)
g.drawLine(x_zac,y_zac,x_kon,y_kon);
else
g.drawOval(x_zac-(50/2),y_zac-(50/2),50,50);}}`
当我在代码中使用绘制方法时,不显示按钮。但是当我删除它时,就可以了。
屏幕:使用绘画方法
没有油漆方法
.....当我点击画布时,会显示一个按钮
感谢
答案 0 :(得分:1)
嗯,首先,你应该致电super.paint(g)
......这非常重要,因为它的一部分工作是绘制儿童成分...
话虽如此......你应该避免覆盖paint
,尤其是覆盖JFrame
等顶级容器,而应该创建一个自JComponent
之类的自定义组件(如例如,JPanel
并覆盖它的paintComponent
方法。
您还应该避免绘制到包含其他组件的组件,除非您计划绘制某种背景图像,例如。
相反,要分开你的容器,这样你的绘画就不会在其他组件之下......除非那是你想要的东西,那么你应该继续...
详细了解Performing Custom Painting和Painting in AWT and Swing了解详情