添加选项卡,标签和文本框

时间:2011-03-09 12:22:38

标签: java

  

可能重复:
  Adding label and text box control to GUI

有人可以帮我在java中编写一个小代码,插入一个标签,并在该标签中添加一个标签和一个文本框。我已经阅读了很多关于这方面的信息并且一遍又一遍地尝试但是无法弄清楚。我实际上需要它用于multilpe选项卡,标签和文本框,但如果有人可以帮助我开始,我想我可以将其应用到我需要做的事情来创建更多。

非常感谢

1 个答案:

答案 0 :(得分:1)

这是我为了记住如何使用gridbaglayout而实现的示例.. :)

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

public class FrmTabbedPane  extends JFrame{

    public FrmTabbedPane() {
        createGui();
    }

    private void createGui() {
        JTabbedPane tabbedPane = new JTabbedPane();
        tabbedPane.addTab("Tab1", createPanel());
        tabbedPane.addTab("Tab2", createPanel());
        add(tabbedPane);


    }

    private JPanel createPanel() {
        JPanel panel = new JPanel(new GridBagLayout());
        addLabelTextField(panel,1);
        addLabelTextField(panel,2);
        addLabelTextField(panel,3);

        return panel;
    }

    private void addLabelTextField(JPanel panel,int row) {
        GridBagConstraints c = new GridBagConstraints();
        c.gridy = row;
        c.gridx = 0;
        c.insets = new Insets(1, 5, 1, 10);
              c.weightx=0.3;  
        JLabel label1 = new JLabel("Label");
        panel.add(label1,c);
        JTextField txtField1 = new JTextField();
        c.gridx = 1;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.weightx = 0.7;
        panel.add(txtField1,c);
    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                FrmTabbedPane frm = new FrmTabbedPane();
                frm.setLocationByPlatform(true);

                frm.setSize(500, 300);
                frm.setVisible(true);

            }

        });
    }
}