【问题标题】:How to align my JTextField to center [closed]如何将我的 JTextField 对齐到中心 [关闭]
【发布时间】:2015-02-19 12:20:29
【问题描述】:

所以我有两个面板,第一个包含一个文本字段和标签:

public class Panel1 extends JFrame implements ActionListener {


//Common variables

    JTextField val;



public Component panel1() {

    // Panel 1 to add labels and textfields

    final JPanel order = new JPanel(new GridLayout(1, 5));{

      order.add(new JLabel("Current Value:", JLabel.CENTER));
      order.add(val = new JTextField(3));

另一个面板包含按钮:

     JPanel buttons = new JPanel();


      JButton add;
      buttons.add(add=new JButton("+"));
    add.setToolTipText("Pressing the button will find total cost");


      add.addActionListener(new ActionListener() 
      {
        @Override
        public void actionPerformed(ActionEvent e) 
        {
            // TODO Auto-generated method stub


        }

      });

      JButton sub;
      buttons.add(sub = new JButton("-"));
      sub.setToolTipText("Pressing the button will save the record to .csv file");

      sub.addActionListener(new ActionListener()
    {
        @Override
        public void actionPerformed(ActionEvent e) { 


            }   

        });



      JButton reset;
      buttons.add(reset=new JButton("Clear"));
    reset.setToolTipText("Pressing the button will clear data entered into the screen");

      reset.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub



        }   
        });

      JButton quit;
      buttons.add(quit= new JButton("Quit"));
    quit.setToolTipText("Pressing the button will close the window");

       quit.addActionListener(new ActionListener()
       {

    @Override
    public void actionPerformed(ActionEvent e) 
    {
        // TODO Auto-generated method stub
      System.exit(0);

    }


    });



    // Panel to combine rest of the panels to one
    JPanel main = new JPanel();
    main.setLayout(new GridBagLayout());
    main.add(order);
    main.add(buttons);

    return main;}
}
@Override
public void actionPerformed(ActionEvent arg0) {
    // TODO Auto-generated method stub

}


}

问题是我的文本字段未对齐。 SIS 与这样的按钮排成一行:

                _______    ________     ________    _______  
 Current Value:|_______|   |____+___|  |___-____|  |__reset|

我希望 Jtextfield(当前值)位于中间,而不是按钮。

【问题讨论】:

  • “问题是我的文本字段没有对齐” 真的吗?看来您应该排序的第一个问题是您的 SHIFT 键卡住了。 1) 为了尽快获得更好的帮助,请发布MCVE(最小完整可验证示例)或SSCCE(简短、自包含、正确示例)。 2) 使用逻辑一致的形式缩进代码行和块。 3) 源代码中的一个空白行是永远需要的。 { 之后或} 之前的空行通常也是多余的。

标签: java swing layout-manager


【解决方案1】:

使用另一个布局管理器。

尝试替换

JPanel order = new JPanel(new GridLayout(1, 5));

JPanel order = new JPanel(new FlowLayout());

【讨论】:

  • 它仍然以相同的方式显示
  • 阅读 Andrew Thompson 的评论并将 SSCCE 添加到问题中
猜你喜欢
  • 2012-07-18
  • 2016-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-23
  • 2010-12-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多