我有一个按钮和JPanel
框架,因为我命名了面板,我想在点击按钮后将内部面板添加到我的面板。但是这个但是有一个问题!因为在添加第二个面板之后它没有添加任何其他面板。
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractButton;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.GridLayout;
import javax.swing.JTextField;
public class DrawImages extends JFrame{
int i;
public DrawImages() {
JButton btnNewButton = new JButton("New button");
i = 0;
getContentPane().add(btnNewButton, BorderLayout.SOUTH);
setMinimumSize(new Dimension(1000,150));
final JPanel panel = new JPanel();
panel.setSize(995, 145);
getContentPane().add(panel, BorderLayout.CENTER);
panel.setLayout(null);
final JLabel lblNewLabel = new JLabel("New label");
lblNewLabel.setBounds(0, 0, 46, 14);
panel.add(lblNewLabel);
btnNewButton.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent paramActionEvent) {
JPanel panel_1 = new JPanel();
//getContentPane().add(panel_1, BorderLayout.NORTH);
panel_1.setLayout(null);
JLabel imagelable = new JLabel(new ImageIcon("c:\\good.jpg"));
imagelable.setBounds(70, 5, 105, 65);
panel_1.add(imagelable);
JLabel lblNewLabel_4 = new JLabel("Up Label");
lblNewLabel_4.setBounds(5, 5, 65, 35);
panel_1.add(lblNewLabel_4);
JLabel lblNewLabel_2 = new JLabel("Down Label");
lblNewLabel_2.setBounds(5, 25, 65, 65);
panel_1.add(lblNewLabel_2);
lblNewLabel.setText(""+i);
panel_1.setBounds(5+170*i, 5, 170+170*i, 70);
panel.add(panel_1);
i++;
}
});
panel.setMinimumSize(new Dimension(995,150));
}
public static void main(String[]args)
{
DrawImages drawImages = new DrawImages();
drawImages.setVisible(true);
}
}
答案 0 :(得分:3)
问题在于声明:
panel_1.setLayout(null);
panel_1
没有任何首选尺寸,因此不会出现(或显示为小点)。
Swing旨在使用布局管理器。在这种特殊情况下,您可以使用GridLayout
。
答案 1 :(得分:0)
我同意Reimeus。只是为了测试你的代码,我用了
panel_1.setLayout(new FlowLayout());
我可以看到添加的面板没有在父面板上调用repaint()。
答案 2 :(得分:0)
感谢您的回答,但我的问题是我在每个圈子中添加了第三个参数:
panel_1.setBounds(5+170*i, 5, 170+170*i, 70);
所以我的面板越来越大(甚至比我的显示器还要大),所以正确的是:
panel_1.setBounds(5+170*i, 5, 170, 70);