This is my code. When I setContentPane(panel)
it works, but when I getContentPane().add(panel)
it doesn't work.
Why doesn't the second method work? (It doesn't show me anything)
public MyFrame() {
final JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setFont(new Font("Comic Sans MS", Font.BOLD, 12));
JMenuBar mnuBar = new JMenuBar();
JMenu mnu1 = new JMenu("aaa");
mnu1.setMnemonic(KeyEvent.VK_E);
JMenuItem menuItem = new JMenuItem("Insert Places", KeyEvent.VK_T);
menuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
count = 0;
jt = new ArrayList[4];
for (int i = 0; i < 4; i++)
jt[i] = new ArrayList<JTextField>();
panel = new JPanel();
panel.setLocation(0, 0);
panel.setSize(d.width, d.height);
panel.setLayout(null);
JButton add = new JButton("lllll");
add.setSize(120, 80);
add.setLocation(250, 100);
add.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
for (int i = 0; i < 4; i++) {
JTextField jt1 = new JTextField(20);
jt1.setSize(150, 30);
jt1.setLocation(450 + i * 200, 80 + count * 50);
jt1.setVisible(true);
jt[i].add(jt1);
panel.add(jt1);
}
count++;
frame.repaint();
}
});
panel.add(add);
JButton confirm = new JButton("ccc");
confirm.setSize(120, 80);
confirm.setLocation(250, 200);
confirm.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
count = 0;
for (int j = 0; j < jt[0].size(); j++) {
try {
connect.insertPlace(Integer.parseInt(jt[0]
.get(j).getText()), jt[1].get(j).getText(),
Integer.parseInt(jt[2].get(j).getText()),
Integer.parseInt(jt[3].get(j).getText()));
count++;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e, "ERROR",
0, null);
}
}
JLabel countL = new JLabel("" + count
+ " ??? ??? ?? ");
countL.setSize(100, 100);
countL.setLocation(250, 350 + jt.length * 10);
panel.add(countL);
frame.repaint();
}
});
panel.add(confirm);
frame.getContentPane().add(panel);
}
});
mnu1.add(menuItem);
mnuBar.add(mnu1);
frame.setJMenuBar(mnuBar);
frame.pack();
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
}
The
Layout
of the existing contentpane is such, that your panel isn't sized correctly and doesn't display. Compare the layout of the existing contentpane, theJFrame
and yourJPanel
and notice the differences.