Adding JTextField to a JPanel and showing them - java

I'm building a little app using Java and Swing in NetBeans. Using NetBeans design window, I created a JFrame with a JPanel inside.
Now I want to dynamically add some jTextFields to the JPanel.
I wrote something like that:
Vector textFieldsVector = new Vector();
JTextField tf;
int i = 0;
while (i < 3) {
tf = new JTextField();
textFieldVector.add(tf);
myPanel.add(tf); //myPanel is the JPanel where I want to put the JTextFields
i++;
}
myPanel.validate();
myPanel.repaint();
But nothing happens: when I run the app, the JFrame shows with the JPanel inside, but the JTextFields don't.
I'm a total newbie in writing graphical Java apps, so I'm surely missing something very simple, but I can't see what.

In the Netbeans GUI, set the layout manager to something like GridLayout or FlowLayout (just for testing). You can do this by going to the GUI editor, clicking on your panel, and then right-clicking and selecting a layout.
Once you've changed to a different layout, go to the properties and alter the layout properties. For the GridLayout, you want to make sure you have 3 grid cells.
Instead of myPanel.validate(), try myPanel.revalidate().
The more canonical way to do this is to create a custom JPanel (without using the GUI editor) that sets its own layout manager, populates itself with components, etc. Then, in the Netbeans GUI editor, drag-and-drop that custom JPanel into the gui editor. Matisse is certainly capable of handling the runtime-modification of Swing components, but that's not the normal way to use it.

It's been a while since I've done some Swing but I think you'll need to recall pack() to tell the frame to relayout its components
EDIT: Yep, I knew it had been too long since I did Swing. I've knocked up the following code which works as expected though and adds the textfields...
JFrame frame = new JFrame("My Frame");
frame.setSize(640, 480);
JPanel panel = new JPanel();
panel.add(new JLabel("Hello"));
frame.add(panel);
frame.setLayout(new GridLayout());
frame.pack();
frame.setVisible(true);
Vector textFieldVector = new Vector();
JTextField tf;
int i = 0;
while (i < 3) {
tf = new JTextField();
textFieldVector.add(tf);
panel.add(tf); //myPanel is the JPanel where I want to put the JTextFields
i++;
}
panel.validate();
panel.repaint();

Your while loop is wrong. i never gets incremented so your window creation is in an endless loop and your CPU consumption should be at 100% until you abort the program. Also, the GUI should be completely non-responsive when you run your program.

The usual way to use GroupLayout is to add a component to a Group. GroupLayout keeps a reference to the Container it is responsible for (which makes sense). You shouldn't be adding the component to the panel without constraints.

Don't use GroupLayout with new (dynamically added) component. It won't show up.

Just use the .setVisible() method of JTextField:
JTextField tf = new JTextField() ;
tf.setVisible(true) ;
panel.add(tf) ;

Related

Setting component sizes inside Jpanels with Borderlayout

I have a project to copy the google sign-in GUI here . So far I'm still searching on what I'm gonna start with, but after some research I think it is possible on BorderLayout to do this. Im getting how it works by readjusting everything through borders, and I kind of like it because it is quite responsive compared to having null layout and coding every setBounds for each component.
I've been imagining using a background panel, a panel for the fill up form,
and creating panels for each pair of label and textfields to properly create the space and stacking (or nesting) them on top of the other. Our teacher just told us to snip out the image, she just wants if we know how to design something out of scratch. That and also saving the input into a text file.
However, I can't seem to grasp the concept of increasing the component size inside the borders to imitate the gaps between the text fields, like some sort of a padding between components? Using setSize doesnt work and so far my search only results into resizing borders, or perhaps I still have not entered the right searachable term for it?
Also, Ive been looking for another way and I think this project will also work using GridBaglayout. However many people say GridBagLayout is too complicated. What do you think would be easier?
In my experience almost every (99%) of the panels using GridBagLayout can be designed by using all other layouts. So, someone could say that GridBagLayout is optional
In your situation, avoiding the use of a GridBagLayout is easy. Take a look at the following code:
public class NoGridBagLayout extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new NoGridBagLayout().setVisible(true));
}
public NoGridBagLayout() {
super();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setExtendedState(MAXIMIZED_BOTH);
JPanel borderPanel = new JPanel(new BorderLayout());
borderPanel.setBorder(new TitledBorder("borderPanel - BorderLayout"));
JLabel label = new JLabel("Create a google account.");
label.setHorizontalAlignment(JLabel.CENTER);
label.setFont(label.getFont().deriveFont(25f));
borderPanel.add(label, BorderLayout.PAGE_START);
setContentPane(borderPanel);
JPanel gridPanel = new JPanel(new GridLayout(1, 2));
gridPanel.setBorder(new TitledBorder("gridPanel - GridLayout"));
getContentPane().add(gridPanel, BorderLayout.CENTER);
JPanel leftBoxedPanel = new JPanel(); // Fill it with panels using BoxLayout.X_AXIS
leftBoxedPanel.setLayout(new BoxLayout(leftBoxedPanel, BoxLayout.Y_AXIS));
leftBoxedPanel.setBorder(new TitledBorder("leftBoxedPanel - BoxLayout.Y_AXIS"));
gridPanel.add(leftBoxedPanel);
JPanel rightBoxedPanel = new JPanel(); // Fill it with panels using BoxLayout.X_AXIS
rightBoxedPanel.setLayout(new BoxLayout(rightBoxedPanel, BoxLayout.Y_AXIS));
rightBoxedPanel.setBorder(new TitledBorder("rightBoxedPanel - BoxLayout.Y_AXIS"));
gridPanel.add(rightBoxedPanel);
}
}
Preview:

how to make a JScrollpane around a box layout

i am creating a software for my project and here is what i have done so far..
what i am trying to do is, i have a jpane witch is created using net beans and it is inside a scrollpane(witch is also add using netbeans) and dynamically i created set of jpanes and add those jpanes in to the jpane i created using netbean.now the scrollpane doesn't work..i cant figure out the reason please help me
this is what i did
int size=(int)jSpinner1.getValue();
a=new JPanel [size];
nameoftext=new JLabel[size];
name=new JTextField[size];
but =new JButton[size];
iamge=new JLabel[size];
jPanel1.removeAll();
for(int x=0;x<size;x++)
{
a[x]=new JPanel(new FlowLayout());
jPanel1.setLayout(new BoxLayout(jPanel1,BoxLayout.PAGE_AXIS));//this is the jpanel i created using netbeans
jPanel1.add(a[x]);
a[x].setVisible(true);
}
for(int x=0;x<size;x++)
{
nameoftext[x]=new JLabel("enter name");
nameoftext[x].setText("enter name");
name[x]=new JTextField();
name[x].setName("name"+String.valueOf(x));
name[x].setColumns(20);
a[x].add(nameoftext[x]).setVisible(true);
a[x].add(name[x]).setVisible(true);
}
and there is one more thing i have to drag the border of jframe to make these components visible.. how to add them instantly to the jframe without dragging the frame
When you add (or remove) components from a visible GUI you need to revalidate() the panel to invoke the layout manager so components can be given a proper size (and location), otherwise the size is (0, 0) and there is nothing to paint.
The basic code would be:
panel.add(...);
panel.revalidate();
panel.repaint();

Java netbeans autoresize textarea

I am using netbeans 7.0.1 to build a simple JFrame application
I am putting a textarea and a couple of buttons on using the gui builder
the buttons are on the same vertical level and the right hand button shifts right on resize of the window - that is fine but I would like the text area to do the same - i.e. resize to fit the relevant width of the window.
For the life of me I cannot see how this is done - I have looked around and I can find code for a hand coded app but not for netbeans gui builder
Update: Ah sorry, didn't read the full question, you really want to do it with netbeans.. :) Well, well, now you have this post how to do it hand-crafted aswell! :)
I wouldn't use an GUI builder for this task. It is easy to create such layout with FlowLayout and BorderLayout:
Screenshot was produced by this code:
public static void main(String... args) throws Exception {
JFrame frame = new JFrame("Test");
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
buttonPanel.add(new JButton("Hello"));
buttonPanel.add(new JButton("World!"));
frame.add(buttonPanel, BorderLayout.NORTH);
frame.add(new JTextArea("Hello World!"), BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 400);
frame.setVisible(true);
}
It's all about the layout you're using. I would personally use GridBagLayout, probably because I am accustomed to it. Basically, you should follow these steps:
Change the layout of the container which owns the textarea to GridBagLayout. You can do that by right-clicking on the container(being it the JFrame, a panel, whatever) and there you will see the Layout menu. It contains a GridBagLayout option.
In the component inspector select the JScrollPane that owns the JTextArea. Check out the "Layout" section in the properties tab. It contains the GridBagConstraints which command the layout behaviour of the JScrollPane and thus commands the JTextArea.
Play with the layout properties :). Basically you should set the X and Y weight to 1, and the Fill to "Both". This will tell the JScrollPane to fill any vertical and horizontal space there is on the Frame, and the X and Y weight will pull any other components as far as possible.
You can read more about GridBagLayout here: http://netbeans.org/kb/docs/java/gbcustomizer-basic.html
Learning GridBagLayout could take a couple of hours, getting used to it could take a couple of days, but it's worth learning. Just my 2 cents.

How can I make JFrame resize automatically to display all buttons

I have a simple swing application which consists of a JLabel and three buttons. The three buttons are in their own JPanel which is in a JFrame along with the JLabel. The JPanel uses flowlayout manager to arrange the buttons horizontally and the JFrame uses the BorderLayout manager to arrange the JLabel and JPanel vertically.
My problem is when I launch the application, during the course of use the text on one of the buttons changes which increases its width. However, the window doesn't resize to accomdate this and one of the buttons disappears. I thought about calling pack() again, but the JFrame is a local variable in my constructor, also, I shouldn't have to tell my program to resize, right? I haven't been able to find anything on google or here to help me but there must be a simple solution, what am I missing? Code is below.
playButton = new JButton("Play");
pauseButton = new JButton("Pause");
stopButton = new JButton("Stop");
curTrackLabel = new JLabel("No Track Selected");
JFrame myFrame = new JFrame("MediaPlayer");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setTitle("MediaPlayer");
myFrame.setLocation(400,300);
JPanel topPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
myFrame.add(topPanel);
JPanel buttonPanel = new JPanel(new FlowLayout());
buttonPanel.add(playButton);
buttonPanel.add(pauseButton);
buttonPanel.add(stopButton);
topPanel.add(buttonPanel, BorderLayout.CENTER);
topPanel.add(curTrackLabel, BorderLayout.NORTH);
playButton.addActionListener(new playButtonHandler());
pauseButton.addActionListener(new pauseButtonHandler());
stopButton.addActionListener(new stopButtonHandler());
myFrame.pack();
myFrame.setVisible(true);
Maybe try
((JFrame)myButton.getTopLevelAncestor()).pack();
Where myButton is the button whose text is modified during execution.
As with learning any GUI software, experimentation is best. Try messing with BorderLayouts with nested JPanels.
Ultimately, you use JPanel with a BorderLayout (Flow Layout is OK but really when resizing the window, it epically fails). See http://download.oracle.com/javase/tutorial/uiswing/layout/border.html to learn more about BorderLayouts.
Now for your layout scheme it should be something along the lines of:
Top Level Container: JFrame
JFrame contains a JPanel (Call this
JPanel 1) with a BorderLayout.
The three buttons should be in a
SEPARATE jPanel (JPanel 2). JPanel
1 should add the three buttons as
BorderLayout.CENTER. In this way,
the window will resize if the button
changes its width and/or hright.
The JLabel should be added as
BorderLayout.LINE_START.
The tutorial at: http://download.oracle.com/javase/tutorial/uiswing/layout/border.html should help you with this. But in general, use the following:
Use JPanel and nest JPanels as necessary
BorderLayout.CENTER will accomodate size changes---this is the key! (Experiment with this)
JFrame should only be used as a top level container (for more complex GUIs, this is true).
If you require more flexibility, check out JGoodies: http://www.jgoodies.com/ . This is more along the lines of creating forms.

JFrame is not acting as expected!

This is my first time using a JFrame. I can't get the window to display the text areas I've nested inside the JFrame. I am trying to get the text field with my name in it to display above the tabulated results, which I have omitted the formatting for until I can get the JFrame to work.
public void printResults(String[] names, int[] temp, int[][] scores, float[] averages, char[] letters){
JTextArea outarea= new JTextArea(5,20);
JTextArea name = new JTextArea(5,20);
Font font = new Font("Tahoma", Font.BOLD, 48);
name.setFont(font);
name.setText("Made By Durka Durka");
JFrame window = new JFrame();
window.getContentPane().add(name);
window.getContentPane().add(outarea);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.pack();
window.getContentPane().setVisible(true)
String out = "foo";
outarea.setText(out);
//JOptionPane.showMessageDialog(null,window);
}
The probable reason why the JFrame is not appearing is because of this line:
window.getContentPane().setVisible(true)
The above line is setting the visibility of the Container to which the JTextAreas have been added, but does not control the visibility of the JFrame itself -- therefore, the JFrame itself is not being displayed.
(To be more precise, the JFrame.getContentPane method returns a Container, so the above code is actually calling the Containter's setVisible method.)
Try the following instead:
window.setVisible(true);
This will set the visibility of the JFrame itself to be visible.
Also, as the other answers have suggested, try using Layout Managers to control the locations of where the components should be displayed. The following are links to using two of the several Layout Managers which could be used to layout components.
How to Use BorderLayout
How to Use GridLayout
You should use some of the layout managers. This link should help you:
http://java.sun.com/docs/books/tutorial/uiswing/layout/using.html
The standard java layout managers are sometimes really hard to handle. Maybe you should also look into the JGoodies: http://www.jgoodies.com/ "Framework". It is easier to use and you realize that even a java gui can look nice..
First things first - are you calling printResults on the Event Dispatch Thread using SwingUtilities.invokeLater(Runnable runnable); or SwingUtilities.invokeAndWait(Runnable runnable);? Remember that you need to do all GUI work on the EDT.
If so, try this:
JFrame window = new JFrame();
// CHANGES HERE
window.getContentPane().setLayout(new BorderLayout();
window.getContentPane().add(name, BorderLayout.NORTH);
window.getContentPane().add(outarea, BorderLayout.CENTER);
// END CHANGES

Categories

Resources