Search code examples
javaswingjpaneljbuttonjtextfield

how add JTextField to Jpanel which have JButton


I have add JtextField line , but in the output only button shows. what i have miss , please write your answer with java code for clearence. Thanks!

 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);
}

This is the main method and 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();
            }
        });
    }

Solution

  • I think you are looking for somthing like that:

    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) Try to use LayoutManager instead of buttonPanel.setLayout(null);, setLocation(), setSize().

    2) a.setVisible(true); here is not necessary, it's by default true.

    3) You needn't to add your JTextField to JLabel. Add components to container like JPanel.

    4)I recommend you to read swing tutorial about components

    5) Post a SSCCE in future.