Java 从 NetBeans GUI Builder 在 JPanel 中显示图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20886415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Displaying image in JPanel from NetBeans GUI Builder
提问by Magda
I created a JFrame
in Netbeans and added a JPanel
(automatically declared in non-editable code as private javax.swing.JPanel jPanel1
).
我JFrame
在 Netbeans 中创建了一个并添加了一个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.
我的表单上有一个按钮,并希望在单击该按钮时在面板中显示一个图像 - 但是我不确定我需要什么代码来显示图像。
回答by nachokk
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);
}
});
回答by Paul Samsotha
Follow these steps
按着这些次序
- Create new JFrame Form (DUH)
- Drag a JPanel to your frame (jPanel1);
Drag a JLabel into that JPanel (jLabel1);
Right - click on your project, and create a new package named "resources". You do this so the image will be imported into your project in the jar
Hightlight your JLabel and open your properties pane
- Click on the ...button to the right of the
icon
property. - Select "External Image", click the ...button to select an image, then click "Import to Project" and click OK
You should see the icon in the frame
Drag a JButton into the frame
Right - click the button, select "Events -> Actions -> actionPerformed"
Go your source code, in your constructor add this
initComponents(); jPanel1.setVisible(false); <------
In your actionPerfomed, add this
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { jPanel1.setVisible(true); <------- }
Run your masterpiece. Try and click the button.
- 创建新的 JFrame 表单 (DUH)
- 将 JPanel 拖到您的框架中 (jPanel1);
将 JLabel 拖入该 JPanel (jLabel1);
右键单击您的项目,然后创建一个名为“resources”的新包。您这样做是为了将图像导入到 jar 中的项目中
突出显示您的 JLabel 并打开您的属性窗格
- 单击属性...右侧的按钮
icon
。 - 选择“外部图像”,单击...按钮选择图像,然后单击“导入到项目”,然后单击“确定”
您应该会在框架中看到图标
将 JButton 拖入框架
右键单击按钮,选择“事件 -> 操作 -> actionPerformed”
去你的源代码,在你的构造函数中添加这个
initComponents(); jPanel1.setVisible(false); <------
在您的 actionPerfomed 中,添加此
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { jPanel1.setVisible(true); <------- }
运行您的杰作。尝试并单击按钮。