1 回答

TA贡献1853条经验 获得超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 是惰性的。在它必须或您要求它之前,它不会运行布局/绘制通道。这是一种优化,因为您可以在需要执行布局传递之前添加许多组件。
要请求布局通行证,请调用revalidate您已更新的顶级容器。作为一般经验法则,如果您致电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现在出现
添加回答
举报