当我制作摇摆计算器并设置按钮时,每个按钮均匀分布但最后一个按钮总是占据整个屏幕,这是设置按钮的方法; < / p>
private void setupRelations() {
window.setJMenuBar(menuBar);
window.setLayout(new BorderLayout());
window.add(inputPanel, BorderLayout.NORTH);
window.add(buttonsPanel);
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
copyResult.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
StringSelection selection = new StringSelection(input.getText());
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(selection, null);
}
});
pasteInput.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String result = "";
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable contents = clipboard.getContents(null);
boolean hasTransferableText = (contents != null) &&
contents.isDataFlavorSupported(DataFlavor.stringFlavor);
if (hasTransferableText) {
try {
result = (String)contents.getTransferData(DataFlavor.stringFlavor);
} catch (UnsupportedFlavorException ex){
System.out.println(ex);
ex.printStackTrace();
} catch (IOException ex) {
System.out.println(ex);
ex.printStackTrace();
}
}
input.setText(result);
}
});
windowOperations.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
specialOperations.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
file.add(copyResult);
file.add(pasteInput);
file.add(exit);
windows.add(windowOperations);
windows.add(specialOperations);
menuBar.add(file);
menuBar.add(windows);
inputPanel.setLayout(new BorderLayout());
input.setEditable(false);
input.setText("sss");
input.setHorizontalAlignment(JTextField.CENTER);
input.setFont(font);
inputPanel.add(input);
buttonsPanel.setLayout(new BorderLayout());
buttonsPanel.setBounds(window.getX() + (75 - 65), window.getY() + 13, 500, 500);
int sLength = 65;
int padding = 75;
for(int i = 0; i < buttonNames[i].length; i++) {
for(int j = 0; j < buttonNames.length; j++) {
JButton button = new JButton(buttonNames[j][i]);
button.setBounds(buttonsPanel.getX() + i * padding,
buttonsPanel.getY() + j * padding, sLength, sLength);
button.addActionListener(getActionListener(i, j));
buttonsPanel.add(button);
}
}
}
getActionListener方法仅用于获取按钮的相应操作,有人可以帮助我吗?
答案 0 :(得分:2)
你的布局错误。在BorderLayout中,当您添加一个组件而不指定north,south,east或west时,将组件添加到中间,组件占用那里的所有空间。
通常对于计算器,您需要GridLayout:它将其可用空间划分为行和列中的相等大小区域,通常与计算器中的数字完全相同。
要将它们放入BorderLayout(假设您希望在数字按钮的一侧或另一侧需要其他内容),请在面板上设置GridLayout,将按钮放入其中,然后将该面板放入(中间的)(带有BorderLayout的组件。