我已经在这一天工作了一天,我无法理解为什么不能调用paintComponent(Graphics g)
方法。我使用我的第二个构造函数来实例化对象,但仍然没有。我的室友有一个非常相似的代码,并且有效。我做错了什么?
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JPanel;
public class squareImage extends JPanel{
Image picture;
String name;
baharKa outerPanel; // a panel that I add these sqaures in
String topLabel;
int a = 0;
int b = 0;
public squareImage(baharKa out, String top, String name, Image im){ //This is the first constructor
this.outerPanel = out;
this.name = name;
this.picture = im;
this.topLabel = top;
this.setPreferredSize(new Dimension(80, 60));
this.setBounds(a, b, getWidth(), getHeight());
this.setPreferredSize(new Dimension(80,80));
this.setOpaque(false);
}
public squareImage(baharKa out, String top, String name, Image im, int a, int b){ //This is second contructor
this(out, top, name, im);
this.a = a;
this.b = b;
this.setBounds(a, b, getWidth(), getHeight());
out.revalidate();
}
protected void paintComponent(Graphics g) { //This is never called
super.paintComponent(g);
System.out.println ("hi!");
int i = g.getFontMetrics().stringWidth(name);
int j = g.getFontMetrics().stringWidth(topLabel);
g.drawImage(picture, 20, 20, 40, 40, null);
g.setColor(Color.BLACK);
g.setFont(new Font("Calibri", Font.PLAIN, 12));
g.drawString(name, i/2 + 40, 45);
g.drawString(name, j/2 + 40, 15);
}
}
/////////我在这里使用它///////
protected void showMeTheSquares(){
try {
System.out.println("showme");
wood = new squareImage(baharKaPanel, "0", "Wood", ImageIO.read(new File("images/wood.png")), 200, 75);
metal = new squareImage(baharKaPanel, "0", "Metal", ImageIO.read(new File("images/metal.png")), 300, 75);
plastic = new squareImage(baharKaPanel, "0", "Plastic", ImageIO.read(new File("images/plastic.png")), 400, 75);
screwD = new squareImage(baharKaPanel, "0", "Plastic", ImageIO.read(new File("images/screwdriver.png")), 10, 100);
hammer = new squareImage(baharKaPanel, "0", "Hammer", ImageIO.read(new File("images/hammer.png")), 10, 180);
pliers = new squareImage(baharKaPanel,"0", "Pliers", ImageIO.read(new File("images/pliers.png")), 10, 340);
scissors = new squareImage(baharKaPanel,"0", "Scissors", ImageIO.read(new File("images/scissors.png")), 10, 420);
brush = new squareImage(baharKaPanel, "0", "Paint Brush", ImageIO.read(new File("images/paintbrush.png")), 10, 260);
wood.repaint();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
addEverything();
}
protected void addEverything(){
baharKaPanel.add(wood);
baharKaPanel.add(metal);
baharKaPanel.add(plastic);
baharKaPanel.add(screwD);
baharKaPanel.add(hammer);
baharKaPanel.add(pliers);
baharKaPanel.add(scissors);
baharKaPanel.add(brush);
}
答案 0 :(得分:1)
这和你使用null布局将创建一个0乘0大小的组件:
this.setBounds(a, b, getWidth(), getHeight());
如果此时输入代码并打印出getWidth()
和getHeight()
在未渲染的组件中返回的内容,则会发现它为0或1。
你不应该使用null布局或设置边界,而是使用尊重首选大小的布局管理器,因为使用null布局会使GUI非常不灵活,虽然它们在一个平台上看起来很好但看起来很糟糕大多数其他平台或屏幕分辨率,并且很难更新和维护。