Java 如何在GridBagLayout单元格内左对齐或右对齐?

Java 如何在GridBagLayout单元格内左对齐或右对齐?,java,swing,gridbaglayout,alignment,Java,Swing,Gridbaglayout,Alignment,我看到,GridBagLayout在单元格中以中心对齐的方式定位子元素。如何左对齐或右对齐 更新 构建代码(我知道我可以重用c) 当使用GridBagLayout以表格形式显示JLabel:JTextField时,我希望有一种方法可以根据x,y位置为我生成GridBagConstraints。例如: private GridBagConstraints createGbc(int x, int y) { GridBagConstraints gbc = new GridBagC

我看到,
GridBagLayout
在单元格中以中心对齐的方式定位子元素。如何左对齐或右对齐

更新

构建代码(我知道我可以重用
c


当使用GridBagLayout以表格形式显示JLabel:JTextField时,我希望有一种方法可以根据x,y位置为我生成GridBagConstraints。例如:

   private GridBagConstraints createGbc(int x, int y) {
      GridBagConstraints gbc = new GridBagConstraints();
      gbc.gridx = x;
      gbc.gridy = y;
      gbc.gridwidth = 1;
      gbc.gridheight = 1;

      gbc.anchor = (x == 0) ? GridBagConstraints.WEST : GridBagConstraints.EAST;
      gbc.fill = (x == 0) ? GridBagConstraints.BOTH
            : GridBagConstraints.HORIZONTAL;

      gbc.insets = (x == 0) ? WEST_INSETS : EAST_INSETS;
      gbc.weightx = (x == 0) ? 0.1 : 1.0;
      gbc.weighty = 1.0;
      return gbc;
   }
以下代码生成的GUI如下所示:

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.HashMap;
import java.util.Map;

import javax.swing.*;

public class GridBagEg {
   private static void createAndShowGui() {
      PlayerEditorPanel playerEditorPane = new PlayerEditorPanel();

      int result = JOptionPane.showConfirmDialog(null, playerEditorPane,
            "Edit Player", JOptionPane.OK_CANCEL_OPTION,
            JOptionPane.PLAIN_MESSAGE);
      if (result == JOptionPane.OK_OPTION) {
         // TODO: do something with info

         for (PlayerEditorPanel.FieldTitle fieldTitle : 
            PlayerEditorPanel.FieldTitle.values()) {
            System.out.printf("%10s: %s%n", fieldTitle.getTitle(),
                  playerEditorPane.getFieldText(fieldTitle));
         }
      }
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

@SuppressWarnings("serial")
class PlayerEditorPanel extends JPanel {
   enum FieldTitle {
      NAME("Name"), SPEED("Speed"), STRENGTH("Strength");
      private String title;

      private FieldTitle(String title) {
         this.title = title;
      }

      public String getTitle() {
         return title;
      }
   };

   private static final Insets WEST_INSETS = new Insets(5, 0, 5, 5);
   private static final Insets EAST_INSETS = new Insets(5, 5, 5, 0);
   private Map<FieldTitle, JTextField> fieldMap = new HashMap<FieldTitle, JTextField>();

   public PlayerEditorPanel() {
      setLayout(new GridBagLayout());
      setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createTitledBorder("Player Editor"),
            BorderFactory.createEmptyBorder(5, 5, 5, 5)));
      GridBagConstraints gbc;
      for (int i = 0; i < FieldTitle.values().length; i++) {
         FieldTitle fieldTitle = FieldTitle.values()[i];
         gbc = createGbc(0, i);
         add(new JLabel(fieldTitle.getTitle() + ":", JLabel.LEFT), gbc);
         gbc = createGbc(1, i);
         JTextField textField = new JTextField(10);
         add(textField, gbc);

         fieldMap.put(fieldTitle, textField);
      }
   }

   private GridBagConstraints createGbc(int x, int y) {
      GridBagConstraints gbc = new GridBagConstraints();
      gbc.gridx = x;
      gbc.gridy = y;
      gbc.gridwidth = 1;
      gbc.gridheight = 1;

      gbc.anchor = (x == 0) ? GridBagConstraints.WEST : GridBagConstraints.EAST;
      gbc.fill = (x == 0) ? GridBagConstraints.BOTH
            : GridBagConstraints.HORIZONTAL;

      gbc.insets = (x == 0) ? WEST_INSETS : EAST_INSETS;
      gbc.weightx = (x == 0) ? 0.1 : 1.0;
      gbc.weighty = 1.0;
      return gbc;
   }

   public String getFieldText(FieldTitle fieldTitle) {
      return fieldMap.get(fieldTitle).getText();
   }

}

导入java.awt.gridbag约束;
导入java.awt.GridBagLayout;
导入java.awt.Insets;
导入java.util.HashMap;
导入java.util.Map;
导入javax.swing.*;
公共课{
私有静态void createAndShowGui(){
PlayerEditorPanel playerEditorPane=新的PlayerEditorPanel();
int result=JOptionPane.showConfirmDialog(null,playerEditorPane,
“编辑播放器”,JOptionPane.OK\u取消\u选项,
JOptionPane.普通消息);
if(result==JOptionPane.OK\u选项){
//TODO:用信息做点什么
对于(PlayerEditorPanel.FieldTitle字段标题:
PlayerEditorPanel.FieldTitle.values()){
System.out.printf(“%10s:%s%n”,fieldTitle.getTitle(),
playerEditorPane.getFieldText(fieldTitle));
}
}
}
公共静态void main(字符串[]args){
SwingUtilities.invokeLater(新的Runnable(){
公开募捐{
createAndShowGui();
}
});
}
}
@抑制警告(“串行”)
类PlayerEditorPanel扩展了JPanel{
枚举字段标题{
名称(“名称”)、速度(“速度”)、强度(“强度”);
私有字符串标题;
私有字段标题(字符串标题){
this.title=标题;
}
公共字符串getTitle(){
返回标题;
}
};
私人静态最终插图西侧插图=新插图(5,0,5,5);
私有静态最终插图东_插图=新插图(5,5,5,0);
private Map fieldMap=new HashMap();
公共电视台{
setLayout(新的GridBagLayout());
SetBordOrder(BorderFactory.createCompoundBorder(
CreateTitleBorder(“播放器编辑器”),
createEmptyByOrder(5,5,5,5));
gridbaggbc;
对于(int i=0;i
在本例中,我在JOptionPane中显示JPanel,但它也可以很容易地显示在JFrame、JApplet、JDialog或…

public class DimsPanel extends JPanel
{
    public static void main(String[] args){
        JFrame main = new JFrame("Dims");
        JPanel myPanel = new DimsPanel();
        main.setContentPane(myPanel);
        main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        main.setSize(400, 400);
        main.setLocationRelativeTo(null);
        main.setVisible(true);
    }

    JButton ok_button = new JButton("OK"), cancel_button = new JButton("Cancel");
    JLabel inputSource_label = new JLabel("Input source:"), 
                output_label = new JLabel("Output:");
    JComboBox inputSource_combo = new JComboBox(new String[]{"A", "B", "C"}), 
                output_combo = new JComboBox(new String[]{"A", "B", "C"});

    public DimsPanel(){
        super(new BorderLayout());
        Box main = new Box(BoxLayout.Y_AXIS);

        Dimension labelsWidth = new Dimension(100, 0);
        JPanel inputPanel = new JPanel(new BorderLayout()); 
        inputSource_label.setPreferredSize(labelsWidth);
        inputPanel.add(inputSource_label, BorderLayout.WEST);
        inputPanel.add(inputSource_combo);

        JPanel outputPanel = new JPanel(new BorderLayout()); 
        output_label.setPreferredSize(labelsWidth);
        outputPanel.add(output_label, BorderLayout.WEST);
        outputPanel.add(output_combo);
        // button panel
        JPanel button_panel = new JPanel();
        button_panel.add(ok_button);
        button_panel.add(cancel_button);

        main.add(inputPanel);
        main.add(outputPanel);

        add(main, BorderLayout.NORTH);
        add(button_panel);
    }
}
你可以跑过去看看。调整大小就像一个符咒,布局代码只有18行。
唯一的缺点是需要手动指定标签的宽度。如果您真的不想在代码中看到setPreferredSize(),那么请随意使用GridBag。但我个人更喜欢这段代码。

看看GridBagLayout教程。存在控制此行为的GridBagConstraints,特别是锚点字段。你试过这个吗?它没有起作用吗?如果没有,请显示代码,否则我们不知道你做错了什么。哦,不,又是GridBag。为什么人们使用为计算机化Swing构建器设计的布局管理器?您可以注意到,当您使用GridBag时,代码变得非常长且不可读,到处都是常量。因此,您可以尝试使用边框、框和流布局构建面板层次结构,而不是GridBag。您将获得10%的代码长度,行为将变得清晰。@Hovercraft,对不起,我不够专心。@Jakub我每个控件有3行代码;使用面板时,我会有额外的线条来创建子面板。我的乳头会小心地爆炸,以添加缺少的PlayerEditorPanel()代码,这样我的乳头也可以这样做?漂亮地对齐,我说不出话来(拍手)。
public class DimsPanel extends JPanel
{
    public static void main(String[] args){
        JFrame main = new JFrame("Dims");
        JPanel myPanel = new DimsPanel();
        main.setContentPane(myPanel);
        main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        main.setSize(400, 400);
        main.setLocationRelativeTo(null);
        main.setVisible(true);
    }

    JButton ok_button = new JButton("OK"), cancel_button = new JButton("Cancel");
    JLabel inputSource_label = new JLabel("Input source:"), 
                output_label = new JLabel("Output:");
    JComboBox inputSource_combo = new JComboBox(new String[]{"A", "B", "C"}), 
                output_combo = new JComboBox(new String[]{"A", "B", "C"});

    public DimsPanel(){
        super(new BorderLayout());
        Box main = new Box(BoxLayout.Y_AXIS);

        Dimension labelsWidth = new Dimension(100, 0);
        JPanel inputPanel = new JPanel(new BorderLayout()); 
        inputSource_label.setPreferredSize(labelsWidth);
        inputPanel.add(inputSource_label, BorderLayout.WEST);
        inputPanel.add(inputSource_combo);

        JPanel outputPanel = new JPanel(new BorderLayout()); 
        output_label.setPreferredSize(labelsWidth);
        outputPanel.add(output_label, BorderLayout.WEST);
        outputPanel.add(output_combo);
        // button panel
        JPanel button_panel = new JPanel();
        button_panel.add(ok_button);
        button_panel.add(cancel_button);

        main.add(inputPanel);
        main.add(outputPanel);

        add(main, BorderLayout.NORTH);
        add(button_panel);
    }
}