swing java: display jbutton and image separately on the screen -


hi im trying add button screen, when user clicks on button random dice picture displayed somewhere else on screen.

simple

this code how i've tried doing it... although cant seem buttons appear picture. either 1 or other. doing wrong?

any appreciated. im sure im using far code desired output.

ava.util.random;  import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.awt.image.bufferedimage; import javax.imageio.imageio;  class mycomponent extends jcomponent {   public void paint(graphics g) {      imageicon icon = new imageicon("dice1.png");     int x = 0;     int y = 0;     icon.painticon(this, g, x, y);   }  }   class dice extends panel {     bufferedimage image;     public dice(){          jframe frame = new jframe("test");         jpanel panel = new jpanel();           frame.add(panel);          jbutton button2 = new jbutton("roll die");         button2.addactionlistener(new actionlistener(){              public void actionperformed(actionevent e){                 //execute when button pressed                 random r= new random();                 system.out.println(r.nextint(6)+1);             }         });         panel.add(button2);          frame.add(new mycomponent());         frame.setvisible(true);         frame.setdefaultcloseoperation(jframe.exit_on_close);         frame.setsize(500,500);     }      public void paint(graphics g){         g.drawimage(image, 0, 0, 50,50, null);     }      public static void main(string[] args)     {     random r= new random();     system.out.println(r.nextint(6)+1);           new dice();      }    } 

the issue jframe's contentpane has borderlayout default , borderlayout adds components it's center area default. borderlayout supports 1 component in each of it's regions when add both yourjpanel , custom component frame, 1 acutally displayed. solution set jframe's contentpane use layout(flowlayout maybe?):

frame.getcontentpane().setlayout(new flowlayout()); 

or add 1 fo components region of borderlayout:

frame.getcontentpane.add(new mycomponent(), borderlayout.west); 

Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

android - layout with fragment and framelayout replaced by another fragment and framelayout -