How can I resize a Swing text field? - java

I wrote the code below:
public class Information extends JFrame{
private JComboBox comboBox1;
private JComboBox comboBox2;
private JTextField textField[];
private JTextField jtextField;
private JLabel label[];
public Information()
{
setLayout(new flowlayout());
Box box = Box.createVerticalBox();
for(int i = 0; i < 20; i++)//textfield
{
textField = new JTextField[20];
box.add(Box.createRigidArea(new Dimension(5,5)));
textField[i] = new JTextField(2);
textField[i].setAlignmentX(2f);
textField[i].setAlignmentY(2f);
box.add(textField[i]);
}
for(int i = 0; i < 22; i++ )//lable
{
}
add(box);
}
}
I want that text field showed in my favorite size, but it fills the whole screen.
I used
textField[i].setAlignmentX(2f);
textField[i].setAlignmentY(2f);
and setcolum(), but it didn't resize the text field. How can I decrease my text fields' sizes?
I use from
setMaximumSize(new Dimension(80, 70));
setPreferredSize(new Dimension(50, 50));
their resize the textfield but change it's location but i don't want to change their
location.is there any manner than i change textfield position?
i use from setlocation but it didn't work!!.

use setPreferredSize()
also setMinimumSize(), setMaximumSize()

I believe you want to use setBounds which will take a width and height as parameters.

The setAlignment methods change the alignment of a component in its container, not the component's actual size. I think you're looking for JTextField's setColumns() method. There's always the inherited setSize() method, too.

Try setPreferredSize(), this (along with setMinimum/MaximumSize()) tend to be used by a lot of LayoutManagers including FlowLayout to appropriately size a container's components.
Also, as a side note, looks like you're re-creating your array of JTextAreas each iteration in that for loop, so only textField[19] would exist...

I think you want to Set a specific size for your textfield.
To do this :
Firstly set the layout as null using the object of Information class
information.setLayout(null);
And set the bounds of the JTextField using setBounds method :
textField.setBounds(0,0,100,100);

Related

Change JTextField height on Swing

I'm trying to fix the height of the "amountField" text field, but I can't.
I would like the height of amountField to have the same height as the JComboBox that it's above, so it looks better.
Right now, the JTextField looks very tall compared with the rest of design.
I've tried everything that I've read in this forum, but nothing seems to work.
I don't know if it's relevant, but this whole JPanel (WithdrawalScreen) is inside another JPanel with BorderLayout. This panel is the center part of it
Thanks
PictureHere
public class WithdrawalScreen extends JPanel {
Public JPanel init() {
this.setLayout(new GridLayout(0,1));
account = new JLabel("account");
accountSelect = new JComboBox(labels);
amount = new JLabel("amount");
amountField = new JTextField("");
submit = new JButton("SUBMIT");
this.add(account);
this.add(accountSelect);
this.add(amount);
this.add(amountField);
this.add(submit);
return this;
}
}
Try creating the Grid Layout with 5 rows and 1 column. I think the height is messed up because you are not setting the constructor arguments properly.
new GridLayout(5,1);
Grid layout will stretch the component and give the same size to all of its components. In order to keep the "default" size of each component, you can use BoxLayout with BoxLayout.Y_AXIS parameter in its constructor. Another way would be to use a dummy-nested JPanel with another layout. Let's say FlowLayout.
JTextField textField = new JTextField(10);
JPanel nestedPanel = new JPanel(new FlowLayout());
nestedPanel.add(textField);
gridLayoutPanel.add(nestedPanel);
JTextField will not be stretched. nestedPanel will be. Do some experiments yourself and you will find the way that fits your needs.
A link that will help you: A visoual guide to Layout Managers.

Java swing GUI absolute positioning

I know that absolute positioning is not recommended, but I need to show my labels randomly scattered as well as randomly changing their positions.
I have researched how to use setBounds but it doesn't seem to work. The following code shows the labels in a Flow Layout, and when I use setLayout(null) it shows a blank frame.
public class GUI extends JFrame{
device mobiles[];
device station;
JPanel pane= new JPanel();
public GUI()
{
setTitle("communication is Key");
setSize(1000, 1000);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pane.setBackground(Color.WHITE);
int x=0; int y=0;
mobiles= new device[10];
for (int i = 0; i < 10; i++) {
x=randInt();
y=randInt();
mobiles[i]= new device(1,x,y);
pane.add(mobiles[i]);
}
x=randInt();
y=randInt();
station = new device(0,x,y);
pane.add(station);
this.add(pane);
}
and this is class "devices" that extends JLabel
public class device extends JLabel{
ImageIcon mob = new ImageIcon("mob.png");
ImageIcon tow = new ImageIcon("tower.png");
public device(int num, int x, int y)
{ if(num==1)
this.setIcon(mob);
else this.setIcon(tow);
this.setBounds(x, y, 3, 7);
}
}
any help in finding out what the problem is, would be be appreciated.
The following code shows the labels in a Flow Layout, and when I use setLayout(null) it shows a blank frame.
The layout manager sets the size and location of the component.
If you don't use the layout manager, then you are responsible for set the size and location of each component.
Typically I would set the size to equal to the components preferred size.
Also, did you display the x/y value that are randomly generated? Maybe the values are larger than the size of the panel.
and when I use setLayout(null) it shows a blank frame.
What layout is set to null? The panel of the frame. Your code doesn't use the above method. Post the code that you use to cause the problem. We don't want to guess what you may or may not be doing.
thanks to #CasparNoree ... the answer suggested was to initialize the Japnel from the start:
JPanel pane = new JPanel(null);
When you set the layout to null you can set the bounds manually with coordinates.
JFrame jf = new JFrame();
JPanel p = new JPanel();
JButton jb = new JButton();
// this is where you make it so setting the bounds actually does something
p.setLayout(null);
jb.setBounds(100,100,100,100);
p.add(jb);
jf.add(p);
jf.setVisible(true);

Placing JTextFields in a JFrame of a Java GUI

I have:
public class BaseStationFrame1 extends JFrame
{
JButton activateButton;
JButton deactivateButton;
BaseStation bs;
JTextField networkIdField;
JTextField portField;
public BaseStationFrame1(BaseStation _bs){
bs = _bs;
setTitle("Base Station");
setSize(600,500);
setLocation(100,200);
setVisible(true);
activateButton = new JButton("Activate");
deactivateButton = new JButton("Deactivate");
Container content = this.getContentPane();
content.setBackground(Color.white);
content.setLayout(new FlowLayout());
content.add(activateButton);
content.add(deactivateButton);
networkIdField = new JTextField("networkId : "+ bs.getNetworkId());
networkIdField.setEditable(false);
content.add(networkIdField);
portField = new JTextField("portId : "+ bs.getPort());
portField.setEditable(false);
content.add(portField);}
}
My problem is that i don't want the two TextFields to appear on the right of Activate and Deactivate buttons but below them. How can i fix that?
Specify your layout manager, like this:
content.setLayout(new GridLayout(2,2));
That would use the Grid Layout Manager to establish a grid with 2 columns and 2 rows, that your components would then be placed in.
The layout manager you are currently using, FlowLayout, only adds contents onto the end of the current row. it will wrap around once it reaches the constrained edge of the pane, though.
You should also check the other layout managers here
You could alternatively use GridBagLayout , but you will have to specify a GridBagConstraints object you then add alongside the individual elements, like so:
content.add(networkIdField, gridConstraints);
see more on that in the linked tutorial.
can I suggest that you use a Null Layout for the parent component?
setLayout(null);
then use a setBounds(xPos,yPos, Width, Height);
to position the components on the panel etc?
Doing this will prevent Java's UI Manager to manage the components to the Frame, Panel etc.
That seems to be the easiest and less painful way.
Regards

Jlabel array not visible in netbeans while creating dynamically

I am not able to view the labels which are created dynamically.The code is as follows :
JLabel[] labels = new javax.swing.JLabel[cur.length];
for (int i = 0 ;i < cur.length; i++)
{
System.out.println("in");
labels[i] = new JLabel( cur[i] );
labels[i].setText(""+cur[i]);
jPanel1.add(labels[i]);
this.setVisible(true);
}
}
There can one or many of cause for your problem
1. Your JPanel may not be added to Container. Add it using getContentPane().add(jpanel1);
2. Your JLabel itself are not visible. Set their visible property to true.
3. Your JPanel is not having flowlayout but CardLayout and hence they might be visible in the back of other component. Assign the layout using jpanel1.setLayout(new FlowLayout())
4. Shift your this.setVisible(true) to outside loop.
What layout are you having for your jPanel object ? try changing its layout to say, FlowLayout. Give it layout in the beginning where you defined it and then use it in your loop.

JList with JScrollPane and prototype cell value wraps element names (replaces with dots instead of showing horizontal scrollbar), why?

I've got a Jlist inside a JScrollPane and I've set a prototype value so that it doesn't have to calculate the width for big lists, but just uses this default width.
Now, the problem is that the Jlist is for some reason replacing the end of an element with dots (...) so that a horizontal scrollbar will never be shown.
How do I disable with "wrapping"? So that long elements are not being replaced with dots if they are wider than the Jlist's width?
I've reproduced the issue in a small example application. Please run it if you don't understand what I mean:
import javax.swing.*;
import java.awt.*;
public class Test
{
//window
private static final int windowWidth = 450;
private static final int windowHeight = 500;
//components
private JFrame frame;
private JList classesList;
private DefaultListModel classesListModel;
public Test()
{
load();
}
private void load()
{
//create window
frame = new JFrame("Test");
frame.setSize(windowWidth, windowHeight);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setUndecorated(true);
frame.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
//classes list
classesListModel = new DefaultListModel();
classesList = new JList(classesListModel);
classesList.setPrototypeCellValue("prototype value");
classesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
classesList.setVisibleRowCount(20);
JScrollPane scrollClasses = new JScrollPane(classesList, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
for (int i = 0; i < 200; i++)
{
classesListModel.addElement("this is a long string, does not fit in width");
}
//panel
JPanel drawingArea = new JPanel();
drawingArea.setBackground(Color.white);
drawingArea.add(scrollClasses);
frame.add(drawingArea);
//set visible
frame.setVisible(true);
}
}
Even if you force horizontal scrollbar, you still won't be able to scroll because the element is actually not wider than the width because of the dot (...) wrapping.
Thanks in advance.
Scrollbars appear automatically when the preferred size of the component added to the scrollpane is greater than the size of the scrollpane.
By using the setPrototypeCellValue(...) method you are affecting the way the list calculates its preferred size, which means you are responsible for providing the proper value that ensures the strings will not be truncated.
So the simple solution is not not use that method, but in addition you will need to set the preferred size of the scrollpane to be whatever you want. Then the horizontal scrollbars will appear if required.
My answer to that question is that first find the longest element in the list then use
setPrototype method on that elements
When you call classesList.setPrototypeCellValue("prototype value") you are telling the JList classesList to limit its maximum width to the length of the string "prototype value". (See javadocs)
Then later on when you populate the list with the strings "this is a long string, does not fit in width", no wonder it does not fit in the width! Because the width of the prototype you gave it is smaller than the width of the string you are filling the list with.
The JScrollPane will automatically show the scrollbars and you usually don't need to adjust their behavior. The JList will also automatically adjust its width to try and show the maximum width item in the list. The problem occurs when you tell the JList to fix its width by calling the setPrototypeCellValue().
If you comment out
classesList.setPrototypeCellValue("prototype value");
or replace it with
classesList.setPrototypeCellValue("this is a long string, does not fit in width");
then it will function as you expected it to.

Categories