首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将JPanel绘制为JPanel

将JPanel绘制为JPanel
EN

Stack Overflow用户
提问于 2016-07-02 10:31:39
回答 1查看 111关注 0票数 0

我有两个扩展JPanel的类: MapPanel和CityPanel。我试图将一个CityPanel绘制成一个MapPanel,但是什么也没有出现。我不明白为什么如果我以同样的方式添加一个JButton,它将被完美地显示出来。下面是代码:

代码语言:javascript
复制
public class PanelMap extends JPanel {

    public PanelMap() {
        CityPanel city = new CityPanel();
        city.setVisible(true);
        this.add(city);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
    }

}



public class CityPanel extends JPanel {

    private BufferedImage image;

    public CityPanel() {
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawString("Test", 0, 0);     }

}

编辑:

我在CityMap中有这段代码。它显示字符串,但不显示图像。

代码语言:javascript
复制
public CityPanel(String filePath, int red, int green, int blue) {
        this.image = colorImage(filePath, red, green, blue);
        this.setSize(100, 100);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 50, 50, null); 
        g.drawString("sdjkfpod", 50, 50);
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-07-02 10:58:19

请您替换以下PanelMap.java构造函数好吗?

代码语言:javascript
复制
public PanelMap() {
  CityPanel city = new CityPanel();
  city.setVisible(true);
  this.add(city);
}

通过以下构造函数:

代码语言:javascript
复制
public PanelMap() {
    String filePath = "C:\\...\\city2.png";
    CityPanel city = new CityPanel(filePath, 0, 255, 255);       
    this.setLayout(new BorderLayout());
    this.add(city, BorderLayout.CENTER);        
}

看到结果了吗?

对您的代码进行了以下更改:

  • 语句city.setVisible(true);被删除,因为它根本不需要。
  • this.add(city);的声明确实将CityPanel添加到PanelMap中,但是CityPanel占用了很小的空间,看起来是一个很小的矩形。这就是使用BorderLayout的原因。

遵循PanelMapDemo.java,将PanelMap添加到JFrame中,并创建一个可执行示例。

代码语言:javascript
复制
public class PanelMapDemo extends javax.swing.JFrame {
private static final long serialVersionUID = 1L;

public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            PanelMapDemo demoFrame = new PanelMapDemo("PanelMapDemo");
            demoFrame.setVisible(true);
        }
    });
}

public PanelMapDemo(String title) {
    super(title);
    setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
    add(new PanelMap());
    setSize(new java.awt.Dimension(400, 200));
    setLocationRelativeTo(null);
 }
}

在我的系统中,当原始图片是:

您的MapPanel将图片更改为:

希望这个能帮上忙。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38159117

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档