請問,爲什麼添加到JFrame時爲什麼JPanel等組件不可見?這裏是我的代碼:組件在JFrame中是不可見的
public class GUI{
static JPanel panel = new JPanel();
private void createAndShowGUI() {
final ImageIcon zielonaikona = new ImageIcon("kulazielona.png");
JFrame frame1 = new JFrame("MasterMind");
JRadioButton zielony = new JRadioButton(zielonaikona);
zielony.setSelected(true);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton akceptuj = new JButton("Akceptuj");
akceptuj.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
JLabel label2 = new JLabel(zielonaikona);
panel.add(label2);
}
});
BoxLayout layout = new BoxLayout(panel, BoxLayout.Y_AXIS);
panel.add(akceptuj);
panel.setLayout(layout);
panel.add(zielony);
JLabel label = new JLabel (zielonaikona);
panel.add(label);
frame1.getContentPane().add(panel);
frame1.getContentPane().add(akceptuj);
frame1.getContentPane().add(zielony);
frame1.setSize(200, 300);
frame1.setVisible(true);
}
public static void main(String[] args) {
GUI kk = new GUI();
kk.createAndShowGUI();
}
}
它也容易讓人糊塗添加組件到'JPanel'之間改變佈局。儘量不要那樣做。原始代碼可以簡化很多。 –
@reimeus OP「不應該」需要調用重新驗證和重繪,因爲它們不會將框架設置爲可見狀態,直到它們完成添加組件之後才進行重新驗證和重繪,這會進行很好的更改。 +1 – MadProgrammer
@MadProgrammer我指的是'ActionListener'中加入的'JLabel' ... :) – Reimeus