Unable to get java swing components

advertisements
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import java.awt.BorderLayout;

public class Fram {
    public static void main(String[] args) {
        JTextArea map;
        JButton btn;
        map= new JTextArea();
        btn= new JButton("hello");
        JFrame frame= new JFrame("jarvis");
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600,600);
        frame.setLayout(new BorderLayout());
        frame.add(map, BorderLayout.CENTER);
        frame.add(btn, BorderLayout.SOUTH);
    }
}

I am using this code to get a text area but I only get the frame without any textarea or button.


Your code works fine to me as well. You mentioned you can not see swing component I think the reason you are not seeing your text area as expected because that text area is occupying the complete space in the border layout so you are not able to discern if you have the text area. So I have added a JPanel and JscrollPane in your code to improve the behavior. I would also like to call setVisible as last method and as mention by Gilbert you you must start all Swing applications with a call to SwingUtilities invokeLater.

package stackOverFlow;

import java.awt.BorderLayout;

public class Frame implements Runnable {
    public static void main(final String[] args) {
        SwingUtilities.invokeLater(new Frame());
    }

    @Override
    public void run() {
        JTextArea map;
        JButton btn;
        JLabel lbl;
        map = new JTextArea(10, 50);
        final JScrollPane scrollPanel = new JScrollPane(map);
        btn = new JButton("hello");
        lbl = new JLabel("Text Area: ");
        final JPanel actionPanel = new JPanel(
                new FlowLayout(FlowLayout.LEADING));
        actionPanel.add(lbl);
        actionPanel.add(scrollPanel);
        final JFrame frame = new JFrame("jarvis");
        frame.setLayout(new BorderLayout());
        frame.add(actionPanel, BorderLayout.CENTER);
        frame.add(btn, BorderLayout.SOUTH);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 600);
        frame.setVisible(true);
    }
}

the output of program is