How can I add a button to paintComponent panel in java?

孤者浪人 提交于 2020-06-23 18:36:13

问题


The app is an option menu which shows a drawing depending on which button the user presses. I have a container panel with a CardLayout which manages the other panels. I want to show the drawing in my paintComponent Panel, but I also want a button at the bottom of the screen so the user can go back to the main menu.

I tried adding it like this but the button didn't appear:

CardLayout c1 = new CardLayoutl;

JPanel cont1 = new JPanel();

cont1.setLayout(c1);

JPanel panel1 = new JPanel();

panel1.setLayout(new GridBagLayout());

Draw d1 = new Draw(); //JPanel with paintComponent made in separate class    

GridBagConstraints c = new GridBagConstraints();

JButton b1 = new JButton("digrafo");

JButton back = new JButton("back");
c.anchor = GridBagConstraints.FIRST_LINE_START;
c.gridx = 0;
c.gridy = 0;
panel1.add(b1, c);

d1.add(back);    

cont1.add(panel1, "1");
cont1.add(d1, "2");
c1.show(cont1, "1");


b1.addActionListener(new ActionListener(){

        public void actionPerformed(ActionEvent e) {

            // TODO Auto-generated method stub

            c1.show(cont1, "2");

        }
back.addActionListener(new ActionListener(){

        public void actionPerformed(ActionEvent e) {

            // TODO Auto-generated method stub

            c1.show(cont1, "1");

        }

//Draw class
public class Draw extends JPanel{

public void paintComponent(Graphics g){


    super.paintComponent(g);
    this.setBackground(Color.BLACK);

    Graphics2D g2D = (Graphics2D) g;

    g2D.setColor(Color.MAGENTA);
    g2D.fillRect(10, 10, 32, 32);



}





}

来源:https://stackoverflow.com/questions/62318937/how-can-i-add-a-button-to-paintcomponent-panel-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!