如何在JTextFrame中强制文本正确对齐?



我试图使我的文本字段右对齐,但我不太确定如何使它们在JTextField右对齐。我读到可以使Jtextfield正确对齐,但我就是找不到正确的语法。

目前是左对齐的

 import java.awt.*;
 import java.awt.event.*;
 import javax.swing.*;
 import javax.swing.border.TitledBorder;
public class RecursivePowerCalculator extends JFrame {
//text fields for base, exponent, and power. 
private JTextField jtfBase = new JTextField();
private JTextField jtfExponent = new JTextField();
private JTextField jtfPower = new JTextField();
//button to press called calcuate
private JButton jbtCalculate = new JButton("Calculate");
//constructor
public RecursivePowerCalculator(){
    jtfPower.setEditable(false);
    JPanel p1 = new JPanel(new GridLayout(3,2));
    p1.add(new JLabel("Base"));
    p1.add(jtfBase);
    p1.add(new JLabel("Exponent"));
    p1.add(jtfExponent);
    p1.add(new JLabel("Power"));
    p1.add(jtfPower);
    JPanel p2 =new JPanel(new FlowLayout(FlowLayout.CENTER));
    p2.add(jbtCalculate);
    //add the panels to the frame
    add(p1, BorderLayout.CENTER);
    add(p2, BorderLayout.SOUTH);
    jbtCalculate.addActionListener(new ButtonListener());
 }
private class ButtonListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e){
        //get values from text fields
        double base = Double.parseDouble(jtfBase.getText());
        double exponent = Double.parseDouble(jtfExponent.getText());
       String pNum = "" + (power(base, exponent));
        jtfPower.setText(pNum);
 }
    private double power(double x, double y){
     if ( y == 0)
         return 1.0;
     else
        return power(x,y - 1) * x;
        }
     }
 }

使用jtfPower.setHorizontalAlignment(JTextField.RIGHT);看到javadoc。

相关内容

  • 没有找到相关文章

最新更新