java - Creating button through class -
i new java , trying create button through class , has method arguments. when create 2 instances of class, shows 1 button i.e., latest one. tell me mistake have done here?
my class file
public class createbutton { int posx; int posy; int buttonwidth; int buttonheight; public void newbutton(int x, int y, int w, int h) { posx = x; posy = y; buttonwidth = w; buttonheight = h; jframe f = new jframe(); jbutton b = new jbutton("test"); b.setbounds(posx, posy, buttonwidth, buttonheight); f.add(b); f.setsize(400, 400); f.setlayout(null); f.setvisible(true); f.setdefaultcloseoperation(jframe.exit_on_close); } }
my file
class project { public static void main(string[] args) { createbutton mybutton1 = new createbutton(); createbutton mybutton2 = new createbutton(); mybutton1.newbutton(50, 200, 100, 50); mybutton2.newbutton(100, 250, 100, 50); } }
actually, code creates 2 buttons, jframe
windows above each other, can see one. move window, , have 2 buttons visible.
to add buttons same frame, need remove creation of jframe
createbutton()
method , add parameter function. create frame in main()
-method.
as others commented, name of class "nonstandard". better name buttonfactory
or uifactory
if plan create other widgets there well. anyway, consider createbutton()
method returns initialized button instead of adding jframe
you. way gain flexibility , can test created button's parameters in unit test more easily. if button automatically added frame, more complicated achieve.
import javax.swing.*; public class createbutton { public static class uifactory { public jbutton newbutton(int posx, int posy, int buttonwidth, int buttonheight) { jbutton b = new jbutton("test"); b.setbounds(posx, posy, buttonwidth, buttonheight); return b; } public jframe newframe(int width, int height) { jframe f = new jframe(); f.setsize(width, height); f.setlayout(null); f.setdefaultcloseoperation(jframe.exit_on_close); return f; } public jframe mainwindow() { jframe f = newframe(400, 400); f.add(newbutton(50, 200, 100, 50)); f.add(newbutton(100, 250, 100, 50)); return f; } } public static void main(string[] args) { uifactory ui = new uifactory(); jframe main = ui.mainwindow(); main.setvisible(true); jframe win2 = ui.newframe(150, 150); win2.setlocation(400, 400); jbutton b2; win2.add(b2 = ui.newbutton(50, 50, 100, 50)); b2.addactionlistener( e -> win2.setvisible(false) ); win2.setvisible(true); } }
Comments
Post a Comment