gpt4 book ai didi

java - 我正在制作一个带有 swing 的计算器,但按钮都搞乱了

转载 作者:行者123 更新时间:2023-12-02 03:11:58 26 4
gpt4 key购买 nike

当我制作挥杆计算器并设置按钮时,每个按钮间隔均匀,但最后添加的按钮总是占据整个屏幕,这是设置按钮的方法;

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方法仅用于获取按钮对应的操作,有人可以帮助我吗?

最佳答案

您的布局错误。在 BorderLayout 中,当您添加组件而不指定北、南、东或西时,会将组件添加到中间,并且该组件会占据那里的所有空间。

通常对于计算器,您需要一个 GridLayout:它将可用空间划分为行和列中大小相等的区域,通常正是您想要的计算器中的数字。

要将它们放入 BorderLayout(假设您希望在数字按钮的一侧或另一侧放置其他内容),请在面板上设置 GridLayout,将按钮放入其中,然后将该面板放入 (中间的)(带有)BorderLayout 的组件。

关于java - 我正在制作一个带有 swing 的计算器,但按钮都搞乱了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40909253/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com