【发布时间】:2015-11-25 07:12:00
【问题描述】:
我尝试用 Java 为一个大学项目构建一个网络摄像头应用程序。到目前为止,我从来不需要 GUI,所以我没有这方面的经验,为此我使用了 netbeans 中的 gui builder。
现在的 GUI 看起来像这样:
它只是在 gui builder 中添加了一个 jPanel 和一个 jButton。
我要显示的图像是使用 openCV 拍摄的。这工作得很好,我得到一个缓冲图像。为了显示这个图像,我创建了一个 jPanel 的子类并更改了 paintComponent 方法。
package WebcamImageCapture;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
public class ImagePanel extends JPanel
{
/**
* Creates a new empty ImagePanel.
*/
public ImagePanel()
{
this.image = null;
}
/**
* Creates a new ImagePanel from BufferedImage img.
* @param img The BufferedImage to display on the ImagePanel
*/
public ImagePanel(BufferedImage img)
{
this.image = img;
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(this.image, 0, 0, this.image.getWidth(), this.image.getHeight(), null);
g.setColor(new Color(240, 160, 40));
g.fillRect(10, 10, 25, 25);
this.repaint();
}
/**
* Sets the BufferedImage img to display on ImagePanel.
* @param img The BufferedImage to display on the ImagePanel
*/
public void setImage(BufferedImage img)
{
this.image = img;
}
private BufferedImage image;
}
GUI 类有成员openCameraButton 和outputPanel,这是您可以在屏幕截图中看到的元素。我尝试以下方法将我的imagePanel 添加到处理按钮的ActionPerformed 事件的方法内部的outputPanel。
// create the custom jPanel
ImagePanel webcamFrame = new ImagePanel(img);
webcamFrame.setPreferredSize(new Dimension(640, 480));
this.outputPanel.getLayout().addLayoutComponent("webcamFrame", webcamFrame);
this.outputPanel.revalidate();
this.outputPanel.repaint();
this.revalidate();
this.repaint();
这不起作用 =(。我用谷歌搜索并测试了 2 天(还阅读了有关布局的 oracle 文档:documentation)没有找到解决方案。
所以主要问题是:
- 如何添加 ImagePanel?
- 我是否应该使用其他布局手动实现 GUI?
提前感谢您的帮助。
【问题讨论】:
标签: java swing user-interface