如何将JTextField添加到具有JButton的Jpanel

时间:2013-11-18 07:32:12

标签: java swing jpanel jbutton jtextfield

我已经添加了JtextField行,但是在输出中只显示了按钮。我想念的是,请用java代码写清楚你的答案。谢谢!

 public JPanel createContentPane (){
JButton Button1
buttonPanel = new JPanel();
buttonPanel.setLayout(null);
buttonPanel.setLocation(10, 50);
buttonPanel.setSize(1370, 770);
totalGUI.add(buttonPanel);

    Button1 = new JButton("Button 1");
    Button1.setLocation(0, 0);
    Button1.setSize(120, 30);
    Button1.addActionListener(this);
    buttonPanel.add(Button1);

  JLabel l;
  l= new JLabel;
  JTextField a = new JTextField();
    a.setVisible(true);
    a.setLocation(1000,200);
    l.add(a);
}

这是main方法和createAndShowGUI

private  void createAndShowGUI() {


        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame("[=] JButton Scores! [=]");



        //Create and set up the content pane.
        ButtonExample_Extended demo = new ButtonExample_Extended();
        frame.setContentPane(demo.createContentPane());

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(1370, 770);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ButtonExample_Extended().createAndShowGUI();
            }
        });
    }

1 个答案:

答案 0 :(得分:2)

我认为你正在寻找类似的东西:

public JPanel createContentPane() {
    buttonPanel = new JPanel();
    buttonPanel.setLayout(null);
    buttonPanel.setLocation(10, 50);
    buttonPanel.setSize(1370, 770);

    JButton Button1 = new JButton("Button 1");
    Button1.setLocation(0, 0);
    Button1.setSize(120, 30);
    buttonPanel.add(Button1);

    JTextField a = new JTextField(20);
    a.setLocation(125, 0);
    a.setSize(120, 30);
    buttonPanel.add(a);

    return buttonPanel;
}

1)尝试使用LayoutManager代替buttonPanel.setLayout(null);setLocation()setSize()

2)此处a.setVisible(true);不是必需的,默认为true

3)您无需将JTextField添加到JLabel。将组件添加到容器,如JPanel

4)我建议你阅读swing tutorial about components

5)将来发布SSCCE