Hi dude, below the codes have five JButton and I want to print out 4 JButton per row. I try to make the fifth JButton to the second row by using setLoaction method but it doesn't work. Is there any idea?
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Loc {
private JFrame frame = new JFrame();
private JPanel pnlItem = new JPanel();
private JPanel pnlMain = new JPanel();
ArrayList<JButton> btnsOpt = new ArrayList<JButton>();
//Constructor
public Loc() {
Container contentPane = frame.getContentPane();
contentPane.add(createMainPane());
frame.pack();
frame.setSize(800,600);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true);
}
public JPanel createMainPane() {
btnsOpt.add(new JButton("11111"));
btnsOpt.add(new JButton("2"));
btnsOpt.add(new JButton("3"));
btnsOpt.add(new JButton("4"));
btnsOpt.add(new JButton("5"));
int buttonWidth = 60;
int buttonHeight = 35;
int itemPerRow = 4;
int nextX = 10;
int nextY = 10;
for(int i=0; i<btnsOpt.size(); i++) {
btnsOpt.get(i).setLocation(new Point(nextX, nextY));
btnsOpt.get(i).setPreferredSize(new Dimension(buttonWidth, buttonHeight));
pnlItem.add(btnsOpt.get(i));
nextX = nextX + buttonWidth + 10;
if(i%itemPerRow == 0) {
if(i!=0) {
nextX = 0;
nextY = nextY + buttonHeight + 10;
}
}
System.out.println("nextX = "+nextX);
System.out.println("nextY = "+nextY);
}
pnlMain.add(pnlItem);
return pnlMain;
}
public static void main(String args[]) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Loc();
}
});
}
}