简体   繁体   English

从NetBeans GUI Builder在JPanel中显示图像

[英]Displaying image in JPanel from NetBeans GUI Builder

I created a JFrame in Netbeans and added a JPanel (automatically declared in non-editable code as private javax.swing.JPanel jPanel1 ). 我在Netbeans中创建了一个JFrame并添加了一个JPanel (在不可编辑的代码中自动声明为private javax.swing.JPanel jPanel1 )。

I have a button on my form and would like to display an image in the panel upon clicking the button - however I'm not sure what code I need to display the image. 我的表单上有一个按钮,单击该按钮后想在面板中显示图像-但是我不确定显示图像需要什么代码。

Follow these steps 跟着这些步骤

  1. Create new JFrame Form (DUH) 创建新的JFrame表单(DUH)
  2. Drag a JPanel to your frame (jPanel1); 将一个JPanel拖到您的框架(jPanel1);
  3. Drag a JLabel into that JPanel (jLabel1); 将一个JLabel拖到该JPanel(jLabel1)中;

  4. Right - click on your project, and create a new package named "resources". 右键-单击您的项目,然后创建一个名为“ resources”的新程序包。 You do this so the image will be imported into your project in the jar 您执行此操作,以便将图像导入到jar中的项目中

  5. Hightlight your JLabel and open your properties pane 突出显示您的JLabel并打开属性窗格

  6. Click on the ... button to the right of the icon property. 单击icon属性右侧的...按钮。
  7. Select "External Image", click the ... button to select an image, then click "Import to Project" and click OK 选择“外部图像”,单击“ ...”按钮以选择图像,然后单击“导入到项目”,然后单击“确定”。
  8. You should see the icon in the frame 您应该在框架中看到该图标

  9. Drag a JButton into the frame 将JButton拖入框架

  10. Right - click the button, select "Events -> Actions -> actionPerformed" 右键-单击按钮,选择“事件->操作-> actionPerformed”

  11. Go your source code, in your constructor add this 查找源代码,在构造函数中添加此代码

     initComponents(); jPanel1.setVisible(false); <------ 
  12. In your actionPerfomed, add this 在您的actionPerfomed中添加此内容

     private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { jPanel1.setVisible(true); <------- } 
  13. Run your masterpiece. 运行您的杰作。 Try and click the button. 尝试并单击按钮。

One possible solution 一种可能的解决方案

jPanel1 = new JPanel();
jPanel1.add(new JLabel(new ImageIcon("imagePath")));
jPanel.setVisible(false);
//add this panel to the frame

And then when your button is clicked. 然后单击您的按钮。

myButton.addActionListener(new ActionListener(){ 
     @Override
     public void actionPerformed(ActionEvent e) {
          jPanel1.setVisible(true);
     }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM