我在通过 JButton
绘制一条简单的线到 Frame
时遇到一些问题。
仅当我使用 JButton
执行此操作时才会出现此问题。
如果我直接使用Frame
内的JPanel
,一切都可以。
JFrame
:
import javax.swing.*;
import java.awt.*;
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);
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();
}
}
以及带有 paintComponents()
的 JPanel
:
import javax.swing.*;
import java.awt.*;
public class Pane extends JPanel {
public void paintComponents(Graphics g){
super.paintComponents(g);
g.drawLine(0,20,100,20);
}
}
最佳答案
我立即想到了许多问题:
- 您应该使用
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 是惰性的。它不会运行布局/绘制 channel ,除非它必须或您要求它运行。这是一种优化,因为您可以在需要执行布局过程之前添加许多组件。
要请求布局传递,请对已更新的顶级容器调用revalidate
。根据一般经验,如果您调用 revalidate
,您还应该调用 repaint
来请求新的绘制 channel 。
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();
}
}
这至少应该让您的面板
现在显示
关于java - 按下按钮时绘制线条 Swing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54335268/