按下按钮时画线 Swing

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);

    }

}


阿晨1998
浏览 117回答 1
1回答

墨色风雨

我立刻想到了一些问题:你应该使用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现在出现
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java