我有一个简单的问题,因为我不太熟悉Java GUI。我试图让JLable在下面的代码中可见,因为我发现很难理解这个概念。但仍然看不到标签,但框架确实在运行时打开。
public class Sample extends JPanel {
public void Sample() {
JPanel p = new JPanel();
JLabel lab1 = new JLabel("User Name", JLabel.LEFT);
p.setLayout(new FlowLayout());
p.add(lab1 = new JLabel("add JLabel"));
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new Sample());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
}
}发布于 2011-05-13 13:38:45
您忘记将面板p添加到示例中。要么在最后使用add(p),要么直接删除面板p,因为您的示例类正在扩展JPanel。
选项1:
JPanel p = new JPanel();
JLabel lab1 = new JLabel("User Name", JLabel.LEFT);
p.setLayout(new FlowLayout());
p.add(lab1 = new JLabel("add JLabel"));
add(p);选项2:
JLabel lab1 = new JLabel("User Name", JLabel.LEFT);
setLayout(new FlowLayout());
add(lab1 = new JLabel("add JLabel"));另外,为什么要覆盖JLabel的初始化?在您的代码中,JLable将始终保持值"add JLabel“。如果你想看到“用户名”,那么使用这个add(lab1);而不是add(lab1 = new JLabel("add JLabel"));。
也许你只需要这样:
JLabel lab1 = new JLabel("User Name", JLabel.LEFT);
setLayout(new FlowLayout());
add(lab1);另外,构造函数不能有返回类型,所以从构造函数中删除void。
发布于 2011-05-13 13:49:59
您正在使用的构造函数不是正确的构造函数。java构造函数没有返回类型,并且void是额外的。当您在main方法中调用new Sample()时,它实际上并没有调用您的方法,而是默认存在的默认构造函数。
试着这样..。
public Sample() {
JPanel p = new JPanel();
JLabel lab1 = new JLabel("User Name", JLabel.LEFT);
p.setLayout(new FlowLayout());
p.add(lab1 = new JLabel("add JLabel"));
}此外,您还需要按照@Harry Joy建议的方式添加add(p);语句,否则面板仍然不会添加。
发布于 2011-05-13 14:06:25
请注意注释。
import java.awt.*;
import javax.swing.*;
public class Sample extends JPanel {
public Sample() {
// set the layout in the constructor
super(new FlowLayout(FlowLayout.LEADING));
// best not to set size OR preferred size!
setPreferredSize( new Dimension(200,200) );
JLabel lab1 = new JLabel("User Name");
add(lab1);
}
public static void main(String[] args) {
// construct the GUI on the EDT
SwingUtilities.invokeLater( new Runnable() {
public void run() {
JFrame frame = new JFrame("User Details");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Sample());
// important!
frame.pack();
frame.setVisible(true);
}
});
}
}还请注意,除非添加自定义功能,否则通常不认为扩展组件是一个好主意。这将意味着(例如)为Sample面板定义新方法(如果我正确地猜测您要使用该代码的位置,则最好将其标记为UserDetails或UserDetailsContainer )。或者它可能是一个Login组件。
https://stackoverflow.com/questions/5987600
复制相似问题