我是Java的新手,我正在尝试创建一个JFrame,其中包含一个JPanel,一个JLabel内部的图像。然后通过将JLabel添加到JPanel它必须正常工作?但是,这是它在docs.oracle.com上完成的方式......
这是代码:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Interface {
private JPanel panel;
private JPanel buttonPane;
private JLabel label;
private JLabel label2;
private JTextField textfield;
private JTextField textfield2;
private JTextField textfield3;
private JTextField textfield4;
private JTextField textfield5;
private JButton button;
private JButton button2;
private JButton button3;
private JButton button4;
private JButton button5;
private JButton button6;
public static void main(String[] args) {
new Interface();
}
public Interface() {
JFrame frame = new JFrame("Vormen");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 300);
frame.setLocationRelativeTo(null);
panel = new JPanel();
buttonPane = new JPanel();
button = new JButton("cirkel");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JLabel label3 = new JLabel(new ImageIcon("images/cirkel.png"));
panel.add(label3);
panel.revalidate();
panel.repaint();
buttonPane.add(button);
buttonPane.add(button2);
buttonPane.add(button3);
frame.add(buttonPane, BorderLayout.NORTH);
frame.add(panel);
frame.setVisible(true);
}
}
答案 0 :(得分:1)
您的应用程序无法找到"" images / cirkel.png"。你有几个选择:
我使用绝对路径进行快速黑客攻击。对于任何严肃的事情,我会选择资源,因为它们与您的应用程序捆绑在一起。
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Interface {
private JPanel panel;
private JPanel buttonPane;
private JLabel label;
private JLabel label2;
private JTextField textfield;
private JTextField textfield2;
private JTextField textfield3;
private JTextField textfield4;
private JTextField textfield5;
private JButton button;
private JButton button2;
private JButton button3;
private JButton button4;
private JButton button5;
private JButton button6;
public static void main(String[] args) {
new Interface();
}
public Interface() {
JFrame frame = new JFrame("Vormen");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 300);
frame.setLocationRelativeTo(null);
panel = new JPanel(new FlowLayout());
buttonPane = new JPanel();
button = new JButton("cirkel");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Use absolute path here:
JLabel label = new JLabel(new ImageIcon("/home/tyrion/circle.png"));
panel.add(label);
panel.revalidate();
panel.repaint();
}
});
buttonPane.add(button);
// buttonPane.add(button2);
// buttonPane.add(button3);
frame.add(buttonPane, BorderLayout.NORTH);
frame.add(panel, BorderLayout.CENTER);
frame.setVisible(true);
}
}