在运行时将组件添加到jpanel [英] add component to jpanel on runtime
问题描述
我在JFrame
上有一个JPanel
和JButton
.
在运行时,将JLabel
添加到JPanel
时,单击JButton
.
I have a JPanel
and JButton
on the JFrame
.
on runtime add JLabel
to JPanel
When click JButton
.
我使用以下代码:
I use of the following code:
panel.setLayout(null);
jLabel _lbl=new jLabel();
_lbl.setText("Label");
panel.add(_lbl);
panel.validate();
,但在JPanel
中不显示任何JLabel
.
推荐答案
我看到您创建了一个名为_lbl
的JLabel
:
I see you create a JLabel
called _lbl
:
JLabel _lbl=new JLabel();
,但是您永远不会将其添加到面板中.相反,您将没有文本的新JLabel
添加到面板中:
but you never add it to your panel. Instead you add a new JLabel
with no text to your panel:
panel.add(new JLabel());
这当然会构建一个不可见的空标签.
This would ofcourse construct an empty label which wont be visible.
还应尝试在添加JLabel
之后在JPanel
实例上调用revalidate()
和repaint()
,如下所示:
Also try calling revalidate()
and repaint()
on your JPanel
instance after adding the JLabel
like so:
JLabel _lbl=new JLabel("Label");//make label and assign text in 1 line
panel.add(_lbl);//add label we made
panel.revalidate();
panel.repaint();
为此,您可能还需要在框架实例上调用pack()
,以便调整JFrame
的大小以适合新组件.
With this you may also need to call pack()
on your frames instance so as to resize the JFrame
to fit the new components.
也请不要使用null
/Absolute
布局,这是非常不好的做法(除非制作动画),并且可能会出现问题并且很难使用.
Also please never use a null
/Absolute
layout this is very bad practice (unless doing animation) and may prove to be problematic and very hard to use.
宁可使用LayoutManager
:
,或者如果JPanel
上只有一个组件,则只需调用add(label);
,因为它会扩展到JPanel
的大小.
or if you only have a single component on the JPanel
simply call add(label);
as it will stretch to the JPanel
size.
更新:
这是一个小样本.只需在每次按下JButton
时将JLabel
添加到JPanel
:
Here is a small sample. Simply adds JLabel
s to the JPanel
each time JButton
is pressed:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class JavaApplication116 {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new JavaApplication116().createAndShowUI();
}
});
}
private void createAndShowUI() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initComponents(frame);
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
private void initComponents(final JFrame frame) {
final JPanel panel = new JPanel(new FlowLayout());
JButton button = new JButton("Add label");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JLabel _lbl = new JLabel("Label");//make label and assign text in 1 line
panel.add(_lbl);//add label we made
panel.revalidate();
panel.repaint();
frame.pack();//so our frame resizes to compensate for new components
}
});
frame.getContentPane().add(panel, BorderLayout.CENTER);
frame.getContentPane().add(button, BorderLayout.SOUTH);
}
}
这篇关于在运行时将组件添加到jpanel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!