问题
I am making am window application on Java. I want to add label name at run time in my Swing application. How can I do this using Java Swing?
public class Component1 extends JPanel {
Component1() {
JLabel label = new JLabel("dd");
label.setBounds(370, 340, 150, 20);
// label.setText("labeVVl");
add(label);
}
public static void main(String[] args)
{
// create frame
JFrame frame = new JFrame();
final int FRAME_WIDTH = 800;
final int FRAME_HEIGHT = 600;
// set frame attributes
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setTitle("My Frame");
frame.setVisible(true);
Component1 Com = new Component1();
Component add = frame.add(Com);
}
}
回答1:
this code should be works by add
revalidate()
andrepaint()
as notifiers forLayoutManager
don't to use NullLayout, use default FlowLayout implemented for JPanel in API do that the same way
see Initial Thread
for example
来源:https://stackoverflow.com/questions/21309627/how-to-add-jlabel-at-run-time-in-swing