我一直在努力想出一个针对物理项目的程序,但我遇到了问题。这是代码:
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class Cannon extends JFrame {
Cannon() {
setTitle("Cannonball Experiment");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(new FlowLayout());
c.add(new ImagePanel());
c.add(new ModifierPanel());
setSize(400,600);
setVisible(true);
}
class ImagePanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(0,100,200,300);
}
}
class ModifierPanel extends Panel {
JLabel Text = new JLabel("Speed");
JTextField Tf = new JTextField(10);
ModifierPanel() {
add(Text);
add(Tf);
}
}
public static void main(String[] args) {
Cannon frame = new Cannon();
}
}
ModifierPanel
显示正常,但我在修改器之前添加的JPanel
未显示。
答案 0 :(得分:3)
JPanel
ImageJPanel没有显示任何内容,因此其尺寸为(0,0)。
尝试为您的JPanel提供尺寸覆盖方法getPreferredSize
,如下所示:
class ImagePanel extends JPanel {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(0,100,200,300);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(500,300); //for example
}
}
您正在使用尊重FlowLayout
的{{1}},因此您不会遇到任何问题。试着让我知道......
答案 1 :(得分:0)
在图像面板中尝试缓冲图像..
public class ImagePanel extends JPanel{
private BufferedImage image;
public ImagePanel() {
try {
image = ImageIO.read(new File("specify image name and path"));
} catch (IOException ex) {
// exception...
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}