Reputation:
I am unable to understand why JTextArea is not getting displayed with my code. This is the first time i am using FocusAdapter class in a swing program.
Here is the code.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Focus extends FocusAdapter
{
JFrame f;
JTextArea jt;
Focus()
{
f=new JFrame("focus");
jt=new JTextArea(50,50);
jt.addFocusListener(this);
jt.setFont(new Font("varinda",Font.PLAIN,15));
f.setSize(550,550);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void focusGained(FocusEvent fe)
{
jt.setText("focusgained");
}
public static void main(String s[])
{
new Focus();
}
}
Upvotes: 0
Views: 34
Reputation: 347204
Avoid using null
layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify
The basic answer to you question is, you need to actually add the JTextArea
to displable container, in this, your JFrame
, for example...
public class Focus extends FocusAdapter
{
JFrame f;
JTextArea jt;
Focus()
{
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
jt=new JTextArea(50,50);
jt.addFocusListener(this);
jt.setFont(new Font("varinda",Font.PLAIN,15));
f = new JFrame("Testing");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new JScrollPane(jt));
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
});
}
public void focusGained(FocusEvent fe)
{
jt.setText("focusgained");
}
public static void main(String s[])
{
new Focus();
}
}
Have a look at
for more details
Upvotes: 2
Reputation: 414
You have not added the JTextArea to your JFrame. This is why it' not added. ;)
You can do so by:
f.add(jt);
f.setSize(500,500);
or:
f.add(new JScrollPane(jt) );
Upvotes: 0
Reputation: 17454
am unable to understand why JTextArea is not getting displayed with my code. This is the first time i am using FocusAdapter class in a swing program.
It was because you set the layout of the JFrame to null and I don't see you adding the JTextField to your JFrame.
You may do this:
f.add(jt);
jt.setBounds(x, y, width, height); //Give int values for x, y, width, height
Last but not least, try to use a layout for your JFrame and you can consider adding a JPanel to the JFrame instead of adding components directly into the JFrame.
Upvotes: 2