第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

按下按鈕時畫線 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條經(jīng)驗 獲得超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 是惰性的。在它必須或您要求它之前,它不會運行布局/繪制通道。這是一種優(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)


查看完整回答
反對 回復 2022-05-20
  • 1 回答
  • 0 關注
  • 104 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號