我一直在尝试对齐 JButton,并且一直在谷歌搜索一些东西,但似乎没有任何效果。我发现的所有代码都不会移动 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);
}
}
}