1 回答

TA貢獻1853條經(jīng)驗 獲得超6個贊
我立刻想到了一些問題:
你應該使用
paintComponent
,而不是paintComponents
(注意s
最后的),你在油漆鏈中的位置太高了。也不需要任何一種方法public
,類外的任何人都不應該調用它。Pane
不提供尺寸提示,因此它的“默認”尺寸為0x0
相反,它應該看起來更像......
public class Pane extends JPanel {
public Dimension getPreferredSize() {
return new Dimension(100, 40);
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.drawLine(0,20,100,20);
}
}
在添加組件時,Swing 是惰性的。在它必須或您要求它之前,它不會運行布局/繪制通道。這是一種優(yōu)化,因為您可以在需要執(zhí)行布局傳遞之前添加許多組件。
要請求布局通行證,請調用revalidate您已更新的頂級容器。作為一般經(jīng)驗法則,如果您致電revalidate,您也應該致電repaint請求新的油漆通道。
public class Fenetre extends JFrame {
public Fenetre(){
super("Test");
init();
//pack();
setSize(200,200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
private void init() {
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
JButton button = new JButton("Draw line");
button.addActionListener((e)->{
Pane s = new Pane();
panel.add(s);
panel.revalidate();
panel.repaint();
//s.repaint();
});
panel.setBackground(new Color(149,222,205));
add(button,BorderLayout.SOUTH);
add(panel,BorderLayout.CENTER);
}
public static void main(String[] args){
new Fenetre();
}
}
這至少應該讓你panel現(xiàn)在出現(xiàn)
添加回答
舉報