I need some advice on which Swing Components to choose in order to achieve the following:
I have something like a "table" structure, that every time that I click the "Add" button, another "row" should be inserted on the "table". Each row is composed of 2 JTextField. The problem I am having with the GridLayout (the layout used in the pictures below) is that if I add another row, then the heights of the text fields will be shortened and I don't want that (picture on the right), I want to preserve the same height for every row.
What I would like to happen is to have the extra row appear below the last one, so that I could use the JScrollPane and scroll to see it.
Should I use another layout rather than the GridLayout? Maybe the AbsoluteLayout or even using the Table Component?
Thanks.
I would use a JTable and set the row height to whatever you desire. For example:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class TableEg {
private static final int ROW_HEIGHT = 40;
private static final String[] TABLE_COLUMNS = {"Foo", "Bar"};
private static void createAndShowGui() {
final DefaultTableModel tableModel = new DefaultTableModel(TABLE_COLUMNS, 2);
JTable table = new JTable(tableModel );
table.setRowHeight(ROW_HEIGHT);
JScrollPane scrollpane = new JScrollPane(table);
JButton addRowBtn = new JButton(new AbstractAction("Add Row") {
#Override
public void actionPerformed(ActionEvent arg0) {
tableModel.addRow(new String[]{"", ""});
}
});
JPanel btnPanel = new JPanel();
btnPanel.add(addRowBtn);
JFrame frame = new JFrame("TableEg");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(scrollpane, BorderLayout.CENTER);
frame.getContentPane().add(btnPanel, BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Let's say that you add your JTextField in a Jpanel, and you Jpanel in a JScrollPane. Now you would set a preferredSize for you JScrollPane (since you want a fixed displayable area), but you modify the height of the JPanel dinamically based in the amount of JTextField you are placing at that time.
In other words, if you have 2 JTextField in a Jpanel set with GridLayout of 2 columns; you JTextField would take the entire height of the Jpanel; but if you include 2 more they would have to make room for this two and therefore shortening.
Notice that you have 2 rows in a JPanel set to "100" height each row would use "50". if you add another row but also modify the height of the JPanel to "150" each JTextField would still take "50" pixels.
I am a newbie, and it is a possibility that i am not 100% right; if that it is the case "Sorry". I just wanted help.
Try this....
JScrollPane scroll = new JScrollPane(Your_Table);
This will make your table to scroll....
Related
I'm writing an app, that needs some kind of one-row JList to store formula objects. I first tried with just buttons as objects with text on them, but it was not good. Then I made one-row JList but all it's cells have the same width, and it looks like this
(a scrollable area). So "<" will have the same width as others and it looks bad.
Is there a way to force list cells to use their real width? Or there is any cool container that just can store objects(just text) with scrolling over them?
With buttons it looks like
How about you use the JTable which you can configure it to have a single row?
Example Code:
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class JTableTest {
JFrame f;
JTable j;
JTableTest()
{
f = new JFrame();
f.setTitle("JTable Example");
String[][] data = {
{ "F=ma", "e=mc^2", "a^2=b^2+c^2" }
};
String[] columnNames = { "Newton", "Einstein", "Pythagoras" };
j = new JTable(data, columnNames);
j.setBounds(30, 40, 200, 300); //Position x,y & Size of JTable height,width
JScrollPane sp = new JScrollPane(j);
f.add(sp);
f.setSize(500, 200);
f.setVisible(true);
}
public static void main(String[] args)
{
new JTableTest();
}
}
By default, the width of JTable cells are fixed. You can change them, however, using:
j.getColumnModel().getColumn(0).setPreferredWidth(5); //Set Width=5 for first column
I'm trying to add this JTextArea with a JScrollPane (with vertical but not horizontal scrollbar) to my frame but the result is just a grey area with a scrollbar on the right... I'm probably doing something really dumb but i've done that same exact thing to a JPanel and it worked
public class Chats {
public static int height = 600;
public static int length = 400;
public static void init(String me, String you){
JFrame frame = new JFrame ("Chat");
frame.setSize(larguraframe, alturaframe);
frame.setLocation(620, 100);
frame.setResizable(false);
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
JTextArea chat = new JTextArea();
chat.setColumns(10);
chat.setLineWrap(true);
chat.setWrapStyleWord(true);
JScrollPane scrollpane = new JScrollPane(chat, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER;
scrollpane.setBounds(length/8 - 27, height/9 + 27, 350, 380);
chat.setPreferredSize(new Dimension(lenght-15, 7*height/8-27));
frame.add(chat);
frame.add(scrollpane);
frame.setVisible(true);
}
}
I don't mind changing my frame's Layout but i really want one that allows me to put stuff exactly where i want it. Thanks
EDIT
Okay it now shows on my frame but the TextArea is still not resizable. When i write something in it using a JTextfield and a JButton with a Listener that appends the JTextfield's text to the JTextArea and then sets the text in the JTextField to "" it only accepts up to a certain ammount of lines. After that it just looks the same.
I know that you've already "accepted" an answer, but I feel that I'd be remiss if I didn't give an answer that gave important points, ones that in the long run would allow you to create a better and more robust (i.e., a more easily debuggable, modifiable, and enhanceable) application.
Again,
Never set a JTextArea's preferredSize, as this will create a JTextArea whose size is inflexibly set that will not add additional lines when needed. Instead set the JTextArea's row and column properties.
While null layouts and setBounds() might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.
Better to use a JPanel, or more often multiple nested JPanels, each using its own layout manager that allow you to more simply create agile and powerful complex yet beautiful GUI's.
When using layout managers, you'll want to pack() your JFrame after adding all components so that all layout managers will do their jobs and layout components appropriately.
I've an example program below I show,
a title JLabel with large centered text
a JTextArea, called chatViewArea, of specified row and column size held within a JScrollPane and that is for viewing the chat. It is non-focusable so that the user cannot directly interact with it.
Another JTextArea, called textEntryArea, for entering text. You could use a simple JTextField for this and give it an ActionListener so that it responds to the enter key, however if you want a multi-lined text component that acts similar, you'll need to change the key bindings for the JTextArea's enter key. I've done that here so that the enter key "submits" the text held within the textEntryArea JTextArea, and the control-enter key combination acts the same as the enter key used to -- creating a new line.
The main JPanel uses simply a BorderLayout to allow placement of the title at the top, the chat view JTextArea in the center and the text entry JTextArea at the bottom. Note that if you needed to see more components, such as a JList showing other chatters, this can be done by nesting JPanels and using more layouts if need be.
For example:
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class Chat2 extends JPanel {
private static final int ROWS = 25; // rows in the chat view JTextArea
private static final int COLS = 40; // columns in the chat view JTextArea
// and text entry area
private static final int ENTRY_ROWS = 4; // rows in the text entry JTextArea
private static final int BL_HGAP = 10; // horizontal gap for our
// BorderLayout
private static final int BL_VGAP = 5; // vertical gap for our BorderLayout
private static final int EB_GAP = 15; // gap for empty border that goes
// around entire app
private static final String TITLE_TEXT = "My Chat Application";
private static final float TITLE_POINTS = 32f; // size of the title jlabel
// text
private JTextArea chatViewArea = new JTextArea(ROWS, COLS);
private JTextArea textEntryArea = new JTextArea(ENTRY_ROWS, COLS);
public Chat2() {
// label to display the title in bold large text
JLabel titleLabel = new JLabel(TITLE_TEXT, SwingConstants.CENTER);
titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, TITLE_POINTS));
// set up the chat view JTextArea to have word wrap
// and to not be focusable
chatViewArea.setWrapStyleWord(true);
chatViewArea.setLineWrap(true);
chatViewArea.setFocusable(false);
// add it to a JScrollPane, and give the scrollpane vertical scrollbars
JScrollPane viewScrollPane = new JScrollPane(chatViewArea);
viewScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
// set up the text entry JTextArea
textEntryArea.setWrapStyleWord(true);
textEntryArea.setLineWrap(true);
// key bindings so that control-enter will act as enter and the enter key will "submit"
// the user input to the chat window and the chat server
// will allow us to use a multilined text entry area if desired instead
// of a single lined JTextField
setEnterKeyBinding(textEntryArea);
JScrollPane entryScrollPane = new JScrollPane(textEntryArea);
entryScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
// add an empty border around entire application
setBorder(BorderFactory.createEmptyBorder(EB_GAP, EB_GAP, EB_GAP, EB_GAP));
// make the main layout a BorderLayout
setLayout(new BorderLayout(BL_HGAP, BL_VGAP));
// add our components to the GUI
add(titleLabel, BorderLayout.PAGE_START);
add(viewScrollPane, BorderLayout.CENTER);
add(entryScrollPane, BorderLayout.PAGE_END);
}
// Again, use key bindings so that control-enter JTextArea will act as enter key
// and the enter key will "submit" the user input to the chat window and the chat server.
// When ctrl-enter is pushed the Action originally bound to the enter key will be called
// and when enter is pushed a new Action, the EnterKeyAction, will be called
private void setEnterKeyBinding(JTextArea textArea) {
int condition = JComponent.WHEN_FOCUSED; // only for focused entry key
InputMap inputMap = textArea.getInputMap(condition);
ActionMap actionMap = textArea.getActionMap();
KeyStroke entryKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
KeyStroke ctrlEntryKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.CTRL_DOWN_MASK);
// first give ctrl-enter the action held by enter
Object entryKey = inputMap.get(entryKeyStroke);
Action entryAction = actionMap.get(entryKey);
inputMap.put(ctrlEntryKeyStroke, ctrlEntryKeyStroke.toString());
actionMap.put(ctrlEntryKeyStroke.toString(), entryAction);
// now give enter key a new Action
EnterKeyAction enterKeyAction = new EnterKeyAction();
inputMap.put(entryKeyStroke, entryKeyStroke.toString());
actionMap.put(entryKeyStroke.toString(), enterKeyAction);
}
public void appendToChatArea(final String text) {
if (SwingUtilities.isEventDispatchThread()) {
chatViewArea.append(text + "\n");
} else {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
chatViewArea.append(text + "\n");
}
});
}
}
private class EnterKeyAction extends AbstractAction {
#Override
public void actionPerformed(ActionEvent e) {
String text = textEntryArea.getText();
textEntryArea.setText("");
chatViewArea.append("User: " + text + "\n");
// TODO send text to the chat server!
}
}
private static void createAndShowGui() {
Chat2 mainPanel = new Chat2();
JFrame frame = new JFrame("My Chat Window");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
// pack the JFrame so that it will size itself to its components
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Try setting a layout like this:
frame.setLayout(new BorderLayout());
And adding the scrollpane to the center:
frame.add(scrollpane, BorderLayout.CENTER);
Also remove the line pointed by Jire in his answer.
You don't need to add chat because it is adapted by scrollPane.
Remove this line: frame.add(chat);
Add
chat.setBounds(length/8 - 27, height/9 + 27, 330, 360);
And see the magic happen... but do tweek the arguments here in order to get the right dimensions.
For resizable frame just do frame.setResizable(true); instead of frame.setResizable(false);
I am trying to put a text area onto a dialog box using Java Swing. I have a problem of setting the size of this JTextArea. The width of the text area is always equal to the whole width of the window and stretches with the window if I resize it.
private void arrangeComponents() {
JTextArea textArea = new JTextArea();
JPanel outerPanel = new JPanel();
outerPanel.setLayout(new BoxLayout(outerPanel, BoxLayout.PAGE_AXIS));
JScrollPane scrollPane = new JScrollPane(textArea);
outerPanel.add(scrollPane, BorderLayout.CENTER);
Container contentPane = getContentPane();
contentPane.add(outerPanel, BorderLayout.CENTER);
}
I want the JTextArea to be horizontally aligned to the centre of the window and does not change its size.
What did I do wrong?
Use the JTextArea(int rows, int columns) constructor that specifies rows and columns, as shown here, and don't neglect to pack() the enclosing Window.
outerPanel.add(scrollPane, BorderLayout.CENTER);
A BoxLayout doesn't take constraints, so the BorderLayout.CENTER is unnecessary.
The problem is that a BoxLayout respects the maximum size of the component which for a scrollpane is set very large.
Instead of using a BoxLayout, just use a panel with a FlowLayout.
Run the example below to see what you are currently doing. Then comment out the setLayout(...) statement and run again. By default the panel uses a FlowLayout so you will get what you want.
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class SSCCE extends JPanel
{
public SSCCE()
{
setLayout( new BoxLayout(this, BoxLayout.PAGE_AXIS));
JTextArea textArea = new JTextArea(5, 30);
JScrollPane scrollPane = new JScrollPane(textArea);
//scrollPane.setMaximumSize( scrollPane.getPreferredSize() );
add(scrollPane);
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new SSCCE() );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
Or if you really want to keep the BoxLayout then leave keep the setLayout(...) statement and then set the maximum size equal to the preffered size. Many people will say you should never invoke a "setXXX()" method directly and instead you should override the setMaximumSize() method of the scrollpane to just return the preferred size.
Note, when testing these two solutions make sure you make the window smaller than the scrollpane to see how each layout works differently.
i found this from a simple coding site. This code sample may be useful for you.
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class JTextAreaTest {
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("JTextArea Test");
frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String text = "A JTextArea object represents a multiline area for displaying text. "
+ "You can change the number of lines that can be displayed at a time, "
+ "as well as the number of columns. You can wrap lines and words too. "
+ "You can also put your JTextArea in a JScrollPane to make it scrollable.";
JTextArea textAreal = new JTextArea(text, 5, 10);
textAreal.setPreferredSize(new Dimension(100, 100));
JTextArea textArea2 = new JTextArea(text, 5, 10);
textArea2.setPreferredSize(new Dimension(100, 100));
JScrollPane scrollPane = new JScrollPane(textArea2,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
textAreal.setLineWrap(true);
textArea2.setLineWrap(true);
frame.add(textAreal);
frame.add(scrollPane);
frame.pack();
frame.setVisible(true);
}
}
Just call that method for ur text area: setLineWrap(true);
If JTextArea is initializated
JTextArea text = new JTextArea(int rows, int columns)
you just call the method text.setLineWrap(true)
then text'size is fixed.
If I add a JTable to a JPanel and then add that JPanel to a JScrollPane, whenever that JTable gains focus, the scroll pane automatically scrolls to the very bottom, which is bad.
I have many reasons for doing it like this, so I'm hoping for some kind solution to stop this auto-scrolling.
OH, and here's the kicker...It only seems to happen when running the app through JNLP/WebStart, and it does NOT do it in Eclipse, which is even more frustrating.
Here's a quick example that if you launch through JLNP, click the text field, click the table, then it auto-scrolls to the bottom:
import java.awt.*;
import javax.swing.*;
public class ScrollDemo extends JPanel{
private static final long serialVersionUID = 1L;
public ScrollDemo()
{
this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
JTable table = new JTable(100,6);
this.add(new JTextField());
JPanel panel = new JPanel();
panel.add(table);
JScrollPane scroll = new JScrollPane(panel);
this.add(scroll);
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
*/
private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("ScrollDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create and set up the content pane.
JComponent newContentPane = new ScrollDemo();
newContentPane.setOpaque(true); // content panes must be opaque
frame.setContentPane(newContentPane);
frame.setPreferredSize(new Dimension(500, 500));
// Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
I am unable to reproduce the problem, but I can offer a few observations:
The frame's add() method forwards the component to the contentPane automatically.
Instead of setting the frame's preferred size, use setPreferredScrollableViewportSize() on the table.
If the unwanted scrolling is due to updating the table's model, see this example of how to temporarily suspend scrolling.
Kudos for using the event dispatch thread.
Addendum: The nested panel having a (default) FlowLayout is superfluous.
import java.awt.*;
import javax.swing.*;
/** #see https://stackoverflow.com/questions/8319388 */
public class ScrollDemo extends JPanel {
public ScrollDemo() {
this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
JTable table = new JTable(100, 6);
table.setPreferredScrollableViewportSize(new Dimension(320, 240));
this.add(new JTextField());
this.add(new JScrollPane(table));
}
private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("ScrollDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create and set up the content pane.
frame.add(new ScrollDemo());
frame.pack();
// Display the window.
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
}
Just in case anyone cares, the problem was that the eclipse launcher and the JNLP launcher for the app had a different KeyboardFocusManager, and the JNLP one had some quirks.
I was unaware of a custom KeyboardFocusManager being added on the JLNP side, but at least it explains things.
Thanks everyone.
I have had auto scrolling issue on JTables when I place them on an intermediary JPanel instead of placing them directly as the JScrollPane's viewport. In those cases, removing the extraneous panel and putting the table directly on the scrollpane has solved my issues.
Well, I ended up having to rework how I was adding my objects to the scroll pane to avoid this issue. Specifically, if the table is going to be taller than the viewport height, then I just have to add the table directly to the scrollpane then change how I was using the intermediary panel.
Thanks to everyone for your input!
According to this, to change the selection for your JTable you need to change the selection model. Try using the following to set the selected item to the very first one.
ListSelectionModel selectionModel = table.getSelectionModel();
selectionModel.setSelectionInterval(start, end);
See if that gives the focus to the top of the JTable?
EDIT: I have not done this before, so not sure what start and end will need to be, try 0,0 or 0,1 maybe?
I am just trying to add a vertical scroll bar to my TextField and TextArea.
I am using a ScrollPane and it should create avertical/horizontal scroll bar by default.
Problem:
I need a vertical scroll bar to see the data which is not visible.
In the start a vertical scrollbar appears but when the data increases the vertical scrollbar changes to a horizontal scroll bar.
Also the TextField disappears and only a horizontal scrollbar appears in its place.
I guess it is because how I have set the bounds but I tried changing the bounds and it ends up completely doing away with the TextField.
My code snippet:
public JTextField inputField = new JTextField();
public JTextArea talkArea = new JTextArea();
public JScrollPane inputFieldScroll = new JScrollPane(inputField);
public JScrollPane talkAreaScroll = new JScrollPane(talkArea);
talkArea.setEditable(false);
talkArea.setBackground(Color.white);
talkAreaScroll.setBounds(new Rectangle(TALK_LEFT, TALK_TOP, TALK_WIDTH, TALK_HEIGHT));
this.getContentPane().add(talkAreaScroll, null);
//set input area
inputField.setBackground(Color.white);
inputField.setBounds(new Rectangle(INPUT_LEFT, INPUT_TOP, INPUT_WIDTH, INPUT_HEIGHT));
inputFieldScroll.setVerticalScrollBar(new JScrollBar());
inputFieldScroll.setBounds(new Rectangle(INPUT_LEFT, INPUT_TOP, INPUT_WIDTH, INPUT_HEIGHT));
Question:
Is there some parameter I need to set so that it remains a vertical scroll bar?
Why does the input scroll bar occupy the whole inputfield when the data becomes a huge line? It appears as a proper vertical scrollbar in the start.
Any advice appreciated.
Thanks
Below is a small compilable code snippet I mentioned above. I agree with camickr that you should not be using absolute positioning but rather use the layout managers. If you absolutely need to have a horizontal scrollbar for the JTextField, then one way to get it to work is to have it show up always, using the JScrollPane constructor that allows for this. i.e,
JScrollPane inputPane = new JScrollPane(inputField, JScrollPane.VERTICAL_SCROLLBAR_NEVER,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
For e.g.,
import java.awt.*;
import javax.swing.*;
public class FuSwing1b extends JPanel {
private static final int TA_ROWS = 25;
private static final int TA_COLS = 60;
private JTextField inputField = new JTextField();
private JTextArea talkArea = new JTextArea(TA_ROWS, TA_COLS);
public FuSwing1b() {
talkArea.setEditable(false);
talkArea.setFocusable(false);
talkArea.setBackground(Color.white);
//talkArea.setPreferredSize(new Dimension(TALK_WIDTH, TALK_HEIGHT));
JScrollPane talkPane = new JScrollPane(talkArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
JScrollPane inputPane = new JScrollPane(inputField, JScrollPane.VERTICAL_SCROLLBAR_NEVER,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
int gap = 10;
setLayout(new BorderLayout(gap, gap));
add(talkPane, BorderLayout.CENTER);
add(inputPane, BorderLayout.SOUTH);
setBorder(BorderFactory.createEmptyBorder(gap , gap, gap, gap));
}
private static void createAndShowUI() {
JFrame frame = new JFrame("FuSwing1b");
frame.getContentPane().add(new FuSwing1b());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
Don't play with the bounds. Use a layout manager and you won't have to worry about this.
When you create the text field use something like:
JTextField textField = new JTextField(10);
This will create a text field that will hold a minimum of 10 characters. If the number of characters exceeds the display width of the text field the use can see the remaining characters by using the right/left arrow keys. That is the normal UI used by all applications I have ever seen. Don't try to create your own UI by using a horizontal scrollbar. Users are not accustomed to that.
for the text area you can create it using:
JTextArea textArea = new JTextArea(5, 30);
JScrollPane scrollPane = new JScrollPane( textArea );
to create a text area with 5 rows and approximately 30 character per row.
Now add the text field and the scrollpane to your frame "using layout managers" and then pack the frame. The layout managers will determine the best size for the compoents. Scrollbars will automatically appear on the text area as you add text to it and the text exceeds 5 lines.