gpt4 book ai didi

java - Swing:如何对齐 JButton

转载 作者:行者123 更新时间:2023-12-02 10:11:31 25 4
gpt4 key购买 nike

我一直在尝试对齐 JButton,并且在 google 上搜索了一些内容,但似乎都不起作用。我发现的所有代码都不会移动 JButton。我想对齐 JButton,使它们看起来像计算器的脸。这是我的代码:

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;


public class CalculatorUI extends JFrame
{
//Variables.
private JTextField text1;
private JButton button1;
private JButton button2;
private JButton button3;
private JButton button4;
private JButton button5;
private JButton button6;
private JButton button7;
private JButton button8;
private JButton button9;
private JButton button0;
private JPanel pane;

public CalculatorUI()
{
super ("Calculator");
setLayout(new FlowLayout());
text1 = new JTextField(20);
text1.setEditable(false);
add(text1);
button1 = new JButton("1");
button1.setAlignmentX(LEFT_ALIGNMENT);
add(button1);
button2 = new JButton("2");
add(button2);
button3 = new JButton("3");
add(button3);
button4 = new JButton("4");
add(button4);
button5 = new JButton("5");
add(button5);
button6 = new JButton("6");
add(button6);
button7 = new JButton("7");
add(button7);
button8 = new JButton("8");
add(button8);
button9 = new JButton("9");
add(button9);
button0 = new JButton("0");
add(button0);



theHandler handler = new theHandler();
text1.addActionListener(handler);
button1.addActionListener(handler);
button2.addActionListener(handler);
button3.addActionListener(handler);
button4.addActionListener(handler);
button5.addActionListener(handler);
button6.addActionListener(handler);
button7.addActionListener(handler);
button8.addActionListener(handler);
button9.addActionListener(handler);
button0.addActionListener(handler);

}
private class theHandler implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String string = "";


if(event.getSource() == text1)
{
string = String.format("Field1: %s", event.getActionCommand());
}
else if(event.getSource() == button1)
{
string = String.format("Field2: %s", event.getActionCommand());
}
else if(event.getSource() == button2)
{
string = String.format("Field3: %s", event.getActionCommand());
}
else if(event.getSource() == button3)
{
string = String.format("Pasword Field: %s", event.getActionCommand());
}

JOptionPane.showMessageDialog(null, string);
}
}


}

最佳答案

您需要找到合适的布局,而 FlowLayout 可能不是最佳选择。

对于此类事情,我在 GridBayLayout 方面运气很好。

http://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html

但我最终也为我遇到的一项独特任务编写了自己的布局管理器。并不是特别难。

事实上,如果您需要的只是网格中的按钮,那么简单的 GridLayout 就可以工作。也会更容易。

关于java - Swing:如何对齐 JButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10490080/

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