저는 현재 JButton의 배열을 가지고 있습니다. 두 JPanel에 고르게 배치하려고합니다. 따라서 배열에 8 개의 버튼이 있다면 왼쪽 열에는 4 개의 버튼이 있고 오른쪽 열에는 4 개의 버튼이 있습니다. 그러나 배열에 버튼이 7 개있는 경우 왼쪽 열에는 4 개의 버튼이 있고 오른쪽 열에는 3 개의 버튼이 있습니다.두 열 사이에서 동적으로 나누어 진 구성 요소를 추가하는 방법은 무엇입니까?
나는 그런 시나리오에 대한 기본적인 논리를 만들고, 내가 만든 코드에 논리 오류가 있는지 (아니면 이것을 더 잘 수행 할 수있는 방법이 있는지)보고 싶었다. 여기
코드 나는 샘플 코드가 잘 작동하는 것 같다public class SwingTest {
public static void main(String[] args) {
JFrame frame = new JFrame();
JButton b1 = new JButton();
b1.setText("Button1");
JButton b2 = new JButton();
b2.setText("Button2");
JButton b3 = new JButton();
b3.setText("Button3");
JButton b4 = new JButton();
b4.setText("Button4");
JButton b5 = new JButton();
b5.setText("Button5");
JButton b6 = new JButton();
b6.setText("Button6");
ArrayList<JButton> jButtonList = new ArrayList();
jButtonList.add(b1);
jButtonList.add(b2);
jButtonList.add(b3);
jButtonList.add(b4);
jButtonList.add(b5);
jButtonList.add(b6);
JPanel panel = new JPanel();
panel.setLayout(new java.awt.GridBagLayout());
double halfList = Math.ceil((jButtonList.size()/2.0));
int gridX = 0, gridY = 0;
for(int i = 0; i < jButtonList.size(); i++) {
GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints();
if(gridY == (int)halfList) {
gridX++;
gridY = 0;
}
gridBagConstraints.gridx = gridX;
gridBagConstraints.gridy = gridY;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(1, 0, 1, 0);
panel.add(jButtonList.get(i), gridBagConstraints);
gridY++;
}
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
을 마련했습니다,하지만 지금은 딸꾹질 수있는 경우가 될 것인가?
나는 현재 코드보다 덜 장황하다. - 테스트되었습니다! 그 코드는 실제로 훌륭한 일을했습니다. 정보 주셔서 감사합니다. 이 질문을 최고의 대답으로 표시하기 전에 내가 지금 거기에있는 논리에 문제가 있습니까? – WilliamShatner
내가 이것에 대해 확신 할 수없는 한가지는 행 대신 열로 단추를 추가하는 것입니다 (행이나 열로 추가 할 것인지 결정하지 않은 경우) – WilliamShatner
논리를 사용하면 FOR setLayout to panel.setLayout (새로운 GridLayout (0, 2)는 작동해야 함) – Roger