[英]Custom painted JPanel won't appear in JFrame
I've been trying to come up with a program that for a physics project, but I'm having problems. 我一直在尝试为物理项目设计一个程序,但是遇到了问题。 Here's the code:
这是代码:
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
displays fine but the JPanel
, which I added before the Modifier, is not being displayed. ModifierPanel
可以正常显示,但是未显示我在Modifier之前添加的JPanel
。
JPanel
ImageJPanel doesn't show anything, so its dimension is (0,0). JPanel
ImageJPanel不显示任何内容,因此其尺寸为(0,0)。 Try to give your JPanel a dimension overriding method getPreferredSize
like this: 尝试为您的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
}
}
You're using FlowLayout
that honors getPreferredSize
so you won't have any problems. 您正在使用
FlowLayout
getPreferredSize
FlowLayout
,因此不会有任何问题。 Try and let me know... 尝试让我知道...
try buffered image in image panel .. 尝试在图像面板中缓冲图像。
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.