如何使JFormattedTextField浮动或与最左边对齐?

huangapple 未分类评论52阅读模式
英文:

How to get a JFormattedTextField to float or align to the far left?

问题

JFrame gridPrompt = new JFrame("选择网格大小");
JLabel labelOne = new JLabel("请在下方输入1-10之间的数字:");
JButton randomBtn = new JButton("随机");
JFormattedTextField rowsInput = new JFormattedTextField(NumberFormat.getNumberInstance());

// 将输入框设置为10列宽
rowsInput.setColumns(10);

gridPrompt.setLayout(new GridBagLayout());
GridBagConstraints layoutObj = new GridBagConstraints();
layoutObj.gridx = 0;
layoutObj.gridy = 0;
layoutObj.insets = new Insets(5, 5, 5, 5);
gridPrompt.add(labelOne, layoutObj);
		
layoutObj.gridx = 0;
layoutObj.gridy = 1;
layoutObj.insets = new Insets(5, 5, 5, 5);
====>>> rowsInput.setHorizontalAlignment(JTextField.LEFT); <<<======= 这行代码没有起作用
gridPrompt.add(rowsInput, layoutObj);

// 按钮配置
layoutObj.gridx = 0;
layoutObj.gridy = 2;
layoutObj.insets = new Insets(5, 5, 5, 5);
gridPrompt.add(randomBtn, layoutObj); <<<<======== 我也希望这个按钮靠左对齐
英文:

I'm making a GUI where there's a question on the top and a JFormattedTextField under it. The thing is that the input field starts in the center of the window; it looks very awkward. I want it to start from the far left. Here is the code, I bolded my attempt to fix it and I'm unsure why it doesn't work. I also want to align the button (randomBtn) to the left, it appears in the center.

JFrame gridPrompt = new JFrame(&quot;Select The Size of The Grid&quot;);
JLabel labelOne = new JLabel(&quot;Please Enter A Number Between 1-10 Below:&quot;);
JButton randomBtn = new JButton(&quot;Random&quot;);
JFormattedTextField rowsInput = new JFormattedTextField(NumberFormat.getNumberInstance());

//Makes the input box 10 columns wide
rowsInput.setColumns(10);

gridPrompt.setLayout(new GridBagLayout());
GridBagConstraints layoutObj = new GridBagConstraints();
layoutObj.gridx = 0;
layoutObj.gridy = 0;
layoutObj.insets = new Insets(5, 5, 5, 5);
gridPrompt.add(labelOne, layoutObj);
		
layoutObj.gridx = 0;
layoutObj.gridy = 1;
layoutObj.insets = new Insets(5, 5, 5, 5);
====&gt;&gt;&gt; rowsInput.setHorizontalAlignment(JTextField.LEFT); &lt;&lt;&lt;======= THIS LINE DOESNT DO ANYTHING
gridPrompt.add(rowsInput, layoutObj);

//Button configuration
layoutObj.gridx = 0;
layoutObj.gridy = 2;
layoutObj.insets = new Insets(5, 5, 5, 5);
gridPrompt.add(randomBtn, layoutObj); &lt;&lt;======== I WANT THIS TO FLOAT LEFT TOO

huangapple
  • 本文由 发表于 2020年5月4日 12:12:04
  • 转载请务必保留本文链接:https://java.coder-hub.com/61585055.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定