为了账号安全,请及时绑定邮箱和手机立即绑定

按下按钮时画线 Swing

按下按钮时画线 Swing

阿晨1998 2022-05-20 19:25:23
Frame我在通过 a画一条简单的线时遇到了一些问题JButton。仅当我使用JButton. 如果我直接使用JPanel里面的Frame,一切都OK。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();    }}并且JPanel与paintComponents():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);    }}
查看完整描述

1 回答

?
墨色风雨

TA贡献1853条经验 获得超6个赞

我立刻想到了一些问题:

  1. 你应该使用paintComponent,而不是paintComponents(注意s最后的),你在油漆链中的位置太高了。也不需要任何一种方法public,类外的任何人都不应该调用它。

  2. 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现在出现


查看完整回答
反对 回复 2022-05-20
  • 1 回答
  • 0 关注
  • 116 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号