JTextArea is not getting added to frame - java

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

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.

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
Laying Out Components Within a Container
How to Use Text Areas
How to Use Scroll Panes
for more details

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

Related

Button that opens a new JFrame

I'm writing a program where I am supposed to have a title screen for a game, where you can click a 'play' button that opens a different window and simultaneously closes the other one. What I am attempting to do is utilize an ActionListener for a button that makes the current window invisible while simultaneously making a different window visible. I am having a hard time getting this to work and am encountering a lot of syntax and logical errors. I'm quite certain there is a better way to do this, so any pointers will be greatly appreciated. I am using swing. Disclaimer: beginner java level programmer lol :p
My first class includes this (does not include my imports):
public static void main(String[] args) {
//Creating the Frame
MyFrame menuFrame = new MyFrame();
// (here i have code for the frame in my actual program)
}
static class MyFrame extends JFrame {
MyFrame () {
this.setDefaultCloseOperation
(JFrame.EXIT_ON_CLOSE);
this.getContentPane().add(new JLabel(new ImageIcon("logo.png")));
this.pack();
this.setVisible(true);
new EightOff.returnHomeListener (this);
}
}
}
My other class that has the other frame being opened includes the following button and action listener where I am trying to reference my frame from GameMenu:
public class EightOff
{
private static JButton returnHome = new JButton("Return to Game Menu");
public static class returnHomeListener implements ActionListener {
public returnHomeListener(GameMenu.MyFrame myFrame) {
}
#Override
public void actionPerformed(ActionEvent e)
{
returnHomeListener (JFrame visibleFrame) {
visibleFrame.toSetVisible (true);
}
}
}
}
You should start by having a look at How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listener
The ActionListener should be registered to the button, so if can be notified when some action occurs, for example...
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JButton button = new JButton("Click me");
button.addActionListener(new TestActionListener());
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(button);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "I'd prfefer if you did't do that");
}
}
}
In order to make changes to a object, you first need a reference to that object. This is pretty basic, Java 101 kind of stuff and you should have a look at Passing Information to a Method or a Constructor for more details.
You should also have a read of the JavaDocs for JFrame to get a better understanding of what properties and functionality the class provides.
Having a look at How to Make Frames also wouldn't hurt.
I'd recommend having a look at How to use CardLayout instead of trying to hide/show windows, you'll have a better user experience generally.

Java Swing. Opening a new JPanel from a JButton and making the buttons pretty

I am trying to build a little program that has a main GUI with 2 buttons. One button closes the program, the other I want to open a new JPanel that will have text fields etc.
I would like to be able to make the buttons so they look like normal application buttons I guess, nice and square, equal size etc. etc., I am not sure how to do this though.
Also, I am unsure how to open a new JFrame from a button click.
GUI Code:
package practice;
public class UserInterface extends JFrame {
private JButton openReportSelection = new JButton("Open new Window");
private JButton closeButton = new JButton("Close Program");
private JButton getCloseButton() {
return closeButton;
}
private JButton getOpenReportSelection() {
return openReportSelection;
}
public UserInterface() {
mainInterface();
}
private void mainInterface() {
setTitle("Program Information Application");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel centerPanel = new JPanel(new GridLayout(0, 3));
centerPanel.add(openReportSelection);
centerPanel.add(closeButton);
getCloseButton().addActionListener(new Listener());
add(centerPanel, BorderLayout.CENTER);
setSize(1000, 200);
setVisible(true);
}
private void addReportPanel() {
JPanel reportPanel = createNewPanel();
getContentPane().add(reportPanel, BorderLayout.CENTER);
}
private JPanel createNewPanel() {
JPanel localJPanel = new JPanel();
localJPanel.setLayout(new FlowLayout());
return localJPanel;
}
}
ActionListener Class code:
package practice;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Listener implements ActionListener {
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
}
EDIT: I think opening a new JPanel would be the way to go rather than a JFrame. What would be the best way to do this from a Jbutton click?
Start by using a different layout manager, FlowLayout or GridBagLayout might work better
JPanel centerPanel = new JPanel(new FlowLayout());
centerPanel.add(openReportSelection);
centerPanel.add(closeButton);
These layouts will honour the preferred sizes of your buttons
As for opening another window, well, you've already create one, so the process is pretty much the same. Having said that, you might consider having a look at The Use of Multiple JFrames: Good or Bad Practice? before you commit yourself to far.
A better approach might be to use a JMenuBar and JMenuItems to act as the "open" and "exit" actions. Take a look at How to Use Menus then you could use a CardLayout to switch between views instead, for example
From a pure design perspective (I know it's only practice, but perfect practice makes perfect), I wouldn't extend anything from JFrame and instead would rely on building your main GUIs around something like JPanel instead.
This affords you the flexibility to decide how to use these components, as you could add them to frames, applets or other components...
If you want your buttons to have the native Look and Feel (L&F), add the following to your program:
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
Instead of opening another JFrame, you'll want to instead use a JDialog, typically with modality set.
In Java, you can only extend one class and therefore you should consider carefully whether it is appropriate or not to extend another class. You could ask yourself, "Am I actually extending the functionality of JFrame?" If the answer is no, then you actually want to use an instance variable.
Below is an example program from the above recommendations:
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class MyApplication {
private JFrame myframe; // instance variable of a JFrame
private JDialog mydialog;
public MyApplication() {
super();
myframe = new JFrame(); // instantiation
myframe.setSize(new Dimension(400, 75));
myframe.getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JButton btnNewWindow = new JButton("Open New Window");
btnNewWindow.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
mydialog = new JDialog();
mydialog.setSize(new Dimension(400,100));
mydialog.setTitle("I got you! You can't click on your JFrame now!");
mydialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL); // prevent user from doing something else
mydialog.setVisible(true);
}
});
myframe.getContentPane().add(btnNewWindow);
JButton btnCloseProgram = new JButton("Close Program :(");
btnCloseProgram.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
myframe.dispose();
}
});
myframe.getContentPane().add(btnCloseProgram);
myframe.setVisible(true);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException e1) {
e1.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new MyApplication();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
I am not sure from your question what do wou want to do. Do you want to open a new JFrame or do you want to add a JPanel to the existing frame.
To open a new JFrame using a button, create an instance of the JFrame in the actionPerformed method of the button. In your case it would look similar to this:
openReportSelection.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
JFrame frame = new JFrame();
// Do something with the frame
}
}
});
You're probably looking up to create and open a new JFrame. For this purpose, first you need to instantiate an object from JFrame Class. As an example, Let's instantiate a new JFrame with specific boundries.
JFrame testFrame = new testFrame();
verificationFrame.setBounds(400, 100, 250, 250);
Then you need to create your components like JButtons, Jlabels and so on, and next you should add them to your new testFrame object.
for example, let's create a Jlabel and add it testFrame:
JLabel testLbl = new JLabel("Ok");
testLbl.setBounds(319, 49, 200, 30);
testFrame.getContentPane().add(testLbl);
Now let's suppose you have a Jbutton which is named "jbutton" and by clicking it, a new JFrame object will be created and the Jlabel component will be added to it:
jButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
JFrame testFrame = new testFrame();
verificationFrame.setBounds(400, 100, 250, 250);
Label testLbl = new JLabel("Ok");
testLbl.setBounds(319, 49, 200, 30);
testFrame.getContentPane().add(testLbl);
}}});

JLayeredPane with a JDialog

I am unable to make any components apear on a JLayeredPane when adding it to a JDialog.
I have also been unable to find a web resource that shows this may be done in a reasonably sized block of code. Every sight iv looked at "claims" this can be done, and then shows a disgustingly long solution.
What i want is to take a JLayered pane add a Button and place a JLabel with an icon in it onto this pane aswell. In english i want a button with an icon stuck in the front of its text.
That is the awt Button as I have been unable to find a way of making a system looking swing JButton.
Edit: could you help me out with something a little more specific. I think I was a littile to vague in my post.
Button button = new Button("ok");
JDialog dialog = new JDialog(null,"Windows",Dialog.ModalityType.APPLICATION_MODAL);
dialog.getLayeredPane().add(button);
dialog.pack();
dialog.setVisible(true);
I don't seem to have any issues...
public class TestLayeredDialog {
public static void main(String[] args) {
new TestLayeredDialog();
}
public TestLayeredDialog() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JDialog dialog = new JDialog();
dialog.setModal(true);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setLayout(new BorderLayout());
dialog.add(new MyContent());
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
System.exit(0);
}
});
}
public class MyContent extends JLayeredPane {
public MyContent() {
JLabel label = new JLabel("Hello new world");
label.setSize(label.getPreferredSize());
label.setLocation(0, 0);
add(label);
Dimension size = getPreferredSize();
JButton button = new JButton("Click me");
button.setSize(button.getPreferredSize());
button.setLocation(size.width - button.getWidth(), size.height - button.getHeight());
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.getWindowAncestor(MyContent.this).dispose();
}
});
add(button);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
Remember, JLayeredPane DOES NOT have a layout manager. You become responsible for managing the size and position of the child components, that's the point.
Updated with new example
public class TestLayeredDialog {
public static void main(String[] args) {
new TestLayeredDialog();
}
public TestLayeredDialog() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JDialog dialog = new JDialog();
dialog.setModal(true);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setLayout(new BorderLayout());
JLabel label = new JLabel("Hello new world");
label.setSize(label.getPreferredSize());
label.setLocation(0, 0);
dialog.getLayeredPane().add(label, new Integer(1));
dialog.setSize(100, 100);
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
System.exit(0);
}
});
}
}
The layered pane of the JRootPane is responsible for (amongst other things) laying out the content pane and menu bar. It is also used (in some cases) to display things like popups.
Have a read through How to Use Root Panes
You can choose to put components in the root pane's layered pane. If
you do, then you should be aware that certain depths are defined to be
used for specific functions, and you should use the depths as
intended. Otherwise, your components might not play well with the
others. Here's a diagram that shows the functional layers and their
relationship:
Using this, means you are competing with components already on the screen.
Unless you have VERY good reason to be messing with this component, I would suggest you avoid it as 1- It's possible to be changed in the future (the layer position of the components) and 2- It may interfere with other components used by the Swing API
This example seems to work with the following lines added to the constructor:
this.addMouseListener(new MouseHandler(this));
this.add(new JLabel("Label"));
this.add(new JButton(UIManager.getIcon("html.pendingImage")));

Why does my JFrame stay empty, if I subclass JPanel and JFrame?

I'm trying to write custom JFrame and JPanel for my Java application. Currently, I just want to have a JPanel with a start button in the very middle of the screen. So, here's the code I have:
package gui;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
#SuppressWarnings("serial")
public class SubitizingFrame extends JFrame implements KeyListener {
public SubitizingFrame() {
super("Subitizing");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addKeyListener(this);
add(new LaunchPanel());
pack();
setVisible(true);
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_F5)
System.out.println("F5 pressed");
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
}
and here is my panel:
package gui;
import instructions.Settings;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class LaunchPanel extends JPanel implements ActionListener {
private JButton startButton;
public LaunchPanel() {
int width = Settings.getScreenSizeX(), height = Settings.getScreenSizeY();
setPreferredSize(new Dimension(width, height));
setLayout(null);
startButton = new JButton("Start");
startButton.setLocation((width/2) - (startButton.getWidth()/2), (height/2) - (startButton.getHeight()/2));
add(startButton);
}
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
But when the application launches, I don't see anything. Just a big gray screen.
Do not use a null layout. If you simply use the default layout manager of JPanel (i.e. FlowLayout), the JButton with "automagically" be placed in the center. Also, in order to place the JFrame in the middle of the screen, invoke setLocationRelativeTo(null).
Since it's hard to tell what you mean by "screen", this example shows how you center a JButton in a JPanel in a JFrame, that is then centered on the monitor.
public final class CenterComponentsDemo {
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI(){
final JFrame frame = new JFrame("Center Components Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ButtonPane());
frame.setSize(new Dimension(300, 100)); // Done for demo
//frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static class ButtonPane extends JPanel{
public ButtonPane(){
super();
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
setBackground(Color.PINK);
final JButton button = new JButton("Start");
button.setAlignmentX(Component.CENTER_ALIGNMENT);
add(Box.createVerticalGlue());
add(button);
add(Box.createVerticalGlue());
}
}
}
Recommendations:
Avoid using null layout as this makes your app difficult to upgrade and maintain and makes it potentially very ugly or even non-usable on boxes with different OS's or screen resolutions.
If you have your JPanel use a GridBagLayout and add a single component to it without using GridBagConstraints, it will be placed in the center of the JPanel.
You almost never have to or should extend JFrame and only infrequently need to extend JPanel. Usually it's better to enhance your GUI classes through composition rather than inheritance.
Avoid having your "view" or gui classes implement your listener interfaces. This is OK for "toy" programs, but as soon as your application gains any appreciable size or complexity, this gets hard to maintain.
If you don't use any LayoutManager (which btw you probably should), then you'll need to set the size of the panel as well (along with its position).
Although we strongly recommend that you use layout managers, you can perform layout without them. By setting a container's layout property to null, you make the container use no layout manager. With this strategy, called absolute positioning, you must specify the size and position of every component within that container. One drawback of absolute positioning is that it does not adjust well when the top-level container is resized. It also does not adjust well to differences between users and systems, such as different font sizes and locales.
From: http://download.oracle.com/javase/tutorial/uiswing/layout/using.html
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class LaunchPanel extends JPanel {
private JButton startButton;
public LaunchPanel() {
int width = 200, height = 100;
setPreferredSize(new Dimension(width, height));
setLayout(new GridBagLayout());
startButton = new JButton("Start");
add(startButton);
setBorder( new LineBorder(Color.RED, 2));
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showMessageDialog(null, new LaunchPanel());
}
});
}
}
addKeyListener(this);
Don't use KeyListeners. Swing was designed to be used with Key Bindings. Read the section from the Swing tutorial on How to Use Key Bindings for more information.
The tutorial also has a section on Using Layout Manager which you should read. You should not create GUI's with a null layout.

Dynamically Resize a JScrollPane?

I Have two files. One extends JFrame, and another Extends JPanel.
Whenever I change the size of the frame, whether it be maximizing, dragging, whatever, i want the ScrollPane to fit itself to the current size of the frame.
There's more to it, there's a top menubar and a bottom bar as well, but i left those out for simplicity.
Essentially, i want it to work like notepad.
right now, I use a ComponentListener on the frame that calls a setSize method in the the other class.
The setSize method is just:
public void resize(int x, int y)
{
textA.setPreferredSize(new Dimension(x, y-50));
areaScrollPane.setPreferredSize(new Dimension(x,y-50));
}
also, for reference:
public void componentResized(ComponentEvent e)
{
textA.resize(panel.getWidth(),panel.getHeight());
}
FYI, it extends JPanel because of the way I add it to the frame:
panel = (JPanel) this.getContentPane();
panel.setLayout(new BorderLayout());
panel.add(textA, BorderLayout.CENTER);
so what's the best way to do this?
Thanks!
Edit: Here's the scrollpane file. It's called textA in my main.
public class TextArea extends JPanel
{
JTextArea textA=new JTextArea(500,500);
JScrollPane areaScrollPane = new JScrollPane(textA);
Toolkit toolkit = Toolkit.getDefaultToolkit ();
Dimension dim = toolkit.getScreenSize();
Dimension dim2=(new Dimension((int)(dim.getWidth()),(int)(dim.getHeight()-120)));
public TextArea()
{
//textA.setLineWrap(true);
//textA.setWrapStyleWord(true);
textA.setEditable(true);
textA.setForeground(Color.WHITE);
textA.setBackground(Color.DARK_GRAY);
this.setFont(null);
areaScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
areaScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
areaScrollPane.setMinimumSize(new Dimension(300,300));
areaScrollPane.setSize(new Dimension(800,800));
textA.setPreferredSize(dim2);
areaScrollPane.setPreferredSize(dim2);
areaScrollPane.setMaximumSize(dim2);
add(areaScrollPane);
}
#Override
public void resize(int x, int y)
{
textA.setPreferredSize(new Dimension(x, y-50));
areaScrollPane.setPreferredSize(new Dimension(x,y-50));
}
}
and the main:
public class JEdit extends JFrame implements ComponentListener
{
TextArea textA=new TextArea();
JPanel panel;
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
JEdit run=new JEdit();
}
public JEdit()
{
setTitle("JEdit");
setLayout(new BorderLayout());
setSize(1100, 1000);
this.setMinimumSize(new Dimension(100,100));
//setBackground(Color.BLACK);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
System.out.println("error1");
} catch (InstantiationException ex) {
System.out.println("error2");
} catch (IllegalAccessException ex) {
System.out.println("error3");
} catch (UnsupportedLookAndFeelException ex) {
System.out.println("error4");
}
panel = (JPanel) this.getContentPane();
panel.setLayout(new BorderLayout());
//TopBar top=new TopBar();
// PositionBar posB=new PositionBar();
panel.add(textA, BorderLayout.CENTER);
// add(top,BorderLayout.NORTH);
// add(posB,BorderLayout.SOUTH);
addComponentListener(this);
setVisible(true);
}
public void componentResized(ComponentEvent e)
{
textA.resize(panel.getWidth(),panel.getHeight());
}
public void componentMoved(ComponentEvent e) {
textA.resize(panel.getWidth(),panel.getHeight());
}
public void componentShown(ComponentEvent e) {
textA.resize(panel.getWidth(),panel.getHeight());
}
public void componentHidden(ComponentEvent e) {
textA.resize(panel.getWidth(),panel.getHeight());
}
}
Regarding the code you've posted, for one get rid of all calls to setSize -- these are generally not honored when using layout managers and get rid of all of your ComponentListener stuff as it's superfluous since you are using layout managers to resize things. The biggest problem I see though is that your allow your TextArea JPanel to use its default layout, which is FlowLayout, and doing so will prevent the JScrollPane that it holds from resizing. Give this class a BorderLayout (or better simply return a JScrollPane from the class), and you're set. e.g. with quick modifications and with renaming of classes to prevent clashes with the standard Java classes,
import java.awt.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class JEdit2 extends JFrame {
TextArea2 textA = new TextArea2();
JPanel panel;
public static void main(String[] args) {
new JEdit2();
}
public JEdit2() {
setTitle("JEdit 2");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = (JPanel) this.getContentPane();
panel.add(textA, BorderLayout.CENTER);
pack(); //!! added
setLocationRelativeTo(null);
setVisible(true);
}
}
#SuppressWarnings("serial")
class TextArea2 extends JPanel {
JTextArea textA = new JTextArea(500, 500); // !! this is one friggin' huge JTextArea!
JScrollPane areaScrollPane = new JScrollPane(textA);
public TextArea2() {
textA.setEditable(true);
textA.setForeground(Color.WHITE);
textA.setBackground(Color.DARK_GRAY);
this.setFont(null);
setLayout(new BorderLayout()); //!! added
add(areaScrollPane, BorderLayout.CENTER);
}
}
By default a JFrame uses a BorderLayout (so there is no need to reset it). All you need to do is add the JScrollPane to the CENTER of the BorderLayout and it will resize automatically.
And the basic code would be:
JTextArea textArea = new JTextArea(...);
JScrollPane scrollPane = new JScrollPane();
frame.add(scrollPane, BorderLayout.CENTER);
I'm not sure why you are adding the text area to the center.
There is no need to use setPreferredSize() on any component or use a listener on any component.
If you need more help then you need to post a SSCCE.

Categories

Resources