【问题标题】:Elements Alignment in Java AppletJava Applet 中的元素对齐
【发布时间】:2012-05-05 02:34:18
【问题描述】:

我正在尝试对齐 Java Applet 中的几个元素,但我做不到。请帮我。这是我的代码:

public class User extends JApplet implements ActionListener,ItemListener  {

             public int sentp,recievedp,corruptedp;
             public String stetus;
             public double energi,nodeid,en;
             TextField name,time,initene,ampco,acttran;
             Button rsbt,vlbt,insd ;
             Choice ch,ch2;
             public String patrn;
             public void init() {

                 this.setSize(800,600);

                 Label namep= new Label("\n\nEnter the No. of Nodes: ", Label.CENTER);

                 name = new TextField(5);
                 Label timep = new Label("\n\nEnter time of Simulation: ",Label.CENTER);
                 time = new TextField(5);    
                 Label initen  = new Label("\n\nInitial Energy Of Each Sensor Node:");
                 initene = new TextField("10^-4 Joules");
                 initene.setEditable(false);
                 Label ampcon = new Label("\n\nAmplifier Constant:");
                 ampco = new TextField("10^-12 Joules");
                 ampco.setEditable(false);
                 Label acttrans = new Label("\n\nEnergy Required To Activate Transmitter/Reciever:");
                 acttran = new TextField("50 ^ -9 Joules");
                 acttran.setEditable(false);
            Label chp = new Label("\n\nSelect Radio Model:",Label.CENTER);
               rsbt = new Button("Run The Simulation");

             ch= new Choice();

             ch.add("");
             ch.add("Gaussian RadioModel");
             ch.add("Rayleigh RadioModel");
             Label pat= new Label("\n\nDistribution Pattern");
             ch2= new Choice();
             ch2.add("");
             ch2.add("Rectangular Pattern");
             ch2.add("Linear Pattern");
             ch2.add("Random Pattern");

             vlbt=new Button("ViewLog");
             insd=new Button("Details of node");
           JPanel cp = new JPanel();
          this.add(cp);
             GridBagLayout gridb = new GridBagLayout();
             Container cont = getContentPane();
            cont.setLayout(gridb);
            add(cp);

            GroupLayout layout = new GroupLayout(cp);
         cp.setLayout(layout);


             layout.setAutoCreateGaps(true);
             layout.setAutoCreateContainerGaps(true);
     layout.setVerticalGroup(
       layout.createSequentialGroup()



       .addGroup(layout.createParallelGroup()
.addComponent(namep)
.addComponent(name)
.addComponent(rsbt))
.addGroup(layout.createSequentialGroup()
.addComponent(timep)
.addComponent(time)
.addComponent(vlbt))
.addGroup(layout.createSequentialGroup()
.addComponent(chp)
.addComponent(ch))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(pat)
.addComponent(ch2))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(initen)
.addComponent(initene))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(ampcon)
.addComponent(ampco))
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(acttrans)
.addComponent(acttran))
);


          rsbt.addActionListener(this);
          vlbt.addActionListener(this);
          insd.addActionListener(this);
          ch.addItemListener(this);   
            ch2.addItemListener(this); 
 }

【问题讨论】:

  • 1) 该代码甚至无法编译 2) 当前的对齐方式是什么,期望的结果是什么(截图当然可以让事情更清楚) 3) 为什么使用 AWT 组件而不是 Swing 组件 4)请为您的变量使用自描述名称,以便您的代码变得可读。 acttranTextField 的事实并不简单(所有其他变量都相同)
  • 请提供您想要什么以及在哪里的视觉描述?除了JAppletSwing 没有任何关系:(
  • 请检查。我的小程序如上图所示。其中的元素未正确对齐。 java - 如何使用Java中的布局对齐它们?我尝试使用上述代码但没有得到它。我也要给旧的小程序代码吗?
  • 在屏幕截图中,它们是对齐的(水平方向),但显然不是您想要的对齐方式。请描述您想要实现的对齐方式(即使是 MS Paint 模型也会澄清问题)。另请查看Swing visual guide to layout managers,其中可能包含您想要的对齐示例
  • @Robin:我想将它们对齐,如下图所示。您想要我编写的代码以便您指出要进行的修改吗?

标签: java swing applet alignment layout-manager


【解决方案1】:

当你这么说时

JPanel cp = new JPanel();

这意味着您将自动获得FlowLayout。你可能想要different one

编辑:好的,我可以看到你在哪里给cpGroupLayout,但我看不到你在哪里pack()cp所在的窗口或调用setVisible()

编辑:但这对于小程序来说并不重要。

【讨论】:

    【解决方案2】:

    试试这个,对你有好处吗:

    import java.awt.*;
    import javax.swing.*;
    
    public class AppletLayout extends JApplet
    {
        private JTextField noNodeField;
        private JTextField timeSimField;
        private JTextField iniEngField;
        private JTextField ampConsField;
        private JTextField engReqField; 
    
        private JComboBox selModeCombo;
        private JComboBox distPattCombo;
    
        private JButton runSimButton;
        private JButton logButton;
        private JButton detailNodeButton;
    
        private String[] selectionModelString = {"", "Gaussian RadioModel"
                                                   , "Rayleigh RadioModel"};
    
        private String[] distPatternString = {"", "Rectangular Pattern"
                                                   , "Linear Pattern"
                                                   , "Random Pattern"}; 
    
    
        public void init()
        {
            try
            {
                SwingUtilities.invokeLater(new Runnable()
                {
                    public void run()
                    {
                        createAndDisplayGUI();
                    }
                });
            }
            catch(Exception e)
            {
                System.err.println("Unable to Create and Display GUI : " + e.getMessage());
                e.printStackTrace();
            }
        }
    
        private void createAndDisplayGUI()
        {
            JLabel noNodeLabel = new JLabel("Enter the No. of Nodes :", JLabel.LEFT);
            noNodeField = new JTextField(5);
    
            JLabel timeSimLabel = new JLabel("Enter time of Simulation :", JLabel.LEFT);
            timeSimField = new JTextField(5);
    
            JLabel iniEngLabel = new JLabel("Initial Energy Of Each Sensor Node :", JLabel.LEFT);
            iniEngField = new JTextField("10^-4 Joules");
    
            JLabel ampConsLabel = new JLabel("Amplifier Constant :", JLabel.LEFT);
            ampConsField = new JTextField("10^-12 Joules");
    
            JLabel engReqLabel = new JLabel("Energy Required To Activate Transmitter/Reciever :", JLabel.LEFT);
            engReqField = new JTextField("50 ^ -9 Joules");
    
            JLabel selModeLabel = new JLabel("Select Radio Model :", JLabel.LEFT);
            selModeCombo = new JComboBox(selectionModelString);
    
            JLabel distPattLabel = new JLabel("Distribution Pattern :", JLabel.LEFT);
            distPattCombo = new JComboBox(selectionModelString);
    
            runSimButton = new JButton("Run Simulation");
            logButton = new JButton("View Log");
            detailNodeButton = new JButton("Details of Node");
    
            JComponent contentPane = (JComponent) getContentPane();
    
            JPanel topPanel = new JPanel();
            topPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
            topPanel.setLayout(new GridLayout(0, 2));
            topPanel.add(noNodeLabel);
            topPanel.add(noNodeField);
            topPanel.add(timeSimLabel);
            topPanel.add(timeSimField);
            topPanel.add(iniEngLabel);
            topPanel.add(iniEngField);
            topPanel.add(ampConsLabel);
            topPanel.add(ampConsField);
            topPanel.add(engReqLabel);
            topPanel.add(engReqField);
            topPanel.add(selModeLabel);
            topPanel.add(selModeCombo);
            topPanel.add(distPattLabel);
            topPanel.add(distPattCombo);
            JPanel buttonPanel = new JPanel();
            buttonPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
            //buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));
            buttonPanel.setLayout(new GridLayout(0, 1, 5, 5));
            buttonPanel.add(runSimButton);
            buttonPanel.add(logButton);
            buttonPanel.add(detailNodeButton);
    
            JPanel mainPanel = new JPanel();
            mainPanel.setLayout(new BorderLayout(5, 5));
            mainPanel.add(topPanel, BorderLayout.CENTER);
            mainPanel.add(buttonPanel, BorderLayout.LINE_END);
    
            contentPane.add(mainPanel, BorderLayout.PAGE_START);
    
            setSize(1000, 600);
        }
    }
    

    这是输出:

    【讨论】:

    • 非常感谢。我想要这个。再次感谢您的回复和关心。
    • 非常欢迎你,很高兴这个例子对你有所帮助,保持微笑:-)
    • 非常感谢。请再来一个:因为 topPanel 中的每一行(JLabel 和 JTextField)都非常接近。如您所示,我尝试使用 setBorder() 方法为每个标签和 TextField 添加行之间的顶部和底部填充。但我没有得到。有没有其他方法可以实现它?
    • 只需将此行 topPanel.setLayout(new GridLayout(0, 2)); 更改为此 topPanel.setLayout(new GridLayout(0, 2, 15, 15)); 或提供除 15 以外的任何内容,就可以了,你想要什么,看起来 :-) 。我希望这就是你所指的:-)
    • @Doug : Content Pane 基本上是一个Container,它作为顶级容器上的panes 之一存在,更多信息可以在Top-level Container Tutorials 中找到。 getContentPane() 只返回顶级容器的 Container 对象,即 JFrame/JWindow/JDialog。将各种组件添加到JPanel,然后将此JPanel 设置为顶级容器的内容窗格是一个很好的做法,而不是像我在此示例中那样做。我只是修改了一点OP的代码
    【解决方案3】:

    您当前的代码看起来很像您正在使用某种 GUI 构建器工具来生成最终布局。

    为了最大限度地控制,构建组件并将它们添加到面板中。如果您希望使用代码中所示的 GridBagLayout,请遵循如下所示的序列构造

    JPanel p1 = new JPanel(new GridBagLayout());
    GridBagConstraints cs = new GridBagConstraints();
        cs.fill = GridBagConstraints.HORIZONTAL;
        lblUsername = new JLabel("Name: ");
        cs.gridx = 0;
        cs.gridy = 0;
        cs.gridwidth = 1;
        p1.add(lblUsername, cs);
    
        txtUsername = new JTextField("", 20);
        cs.gridx = 1;
        cs.gridy = 0;
        cs.gridwidth = 2;
        p1.add(txtUsername, cs);
       ...
       add(cp);
    

    或者使用 BorderLayout 或 FlowLayout 将组件保存在面板上:

    JPanel p1 = new JPanel(new BorderLayout());
    p1.add(lblUsername, BorderLaout.EAST);
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-11
      • 2016-02-01
      • 2014-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多