setBounds is not working on TextField in Java - java

I want to add two text fields in the panel. The layout of the panel is a Grid Layout.
I add setBounds for the height and width of the text field but setBounds is not working properly.
This is my code...
import java.awt.*;
import javax.swing.*;
class gui1
{
public static void main(String[] args)
{
JFrame frm = new JFrame();
JPanel pan = new JPanel();
Button btn = new Button("SUBMIT");
TextField txt1 = new TextField();
TextField txt2 = new TextField();
Label lbl = new Label("LOGIN FORM");
txt1.setBounds(20,20,100,200);
txt2.setBounds(20,20,200,300);
frm.setLayout(new BorderLayout());
pan.setLayout(new GridLayout(1,2));
pan.add(txt1);
pan.add(txt2);
frm.add(pan,BorderLayout.CENTER);
frm.add(lbl,BorderLayout.NORTH);
frm.setSize(800,500);
frm.setVisible(true);
frm.setDefaultCloseOperation(frm.EXIT_ON_CLOSE);
}
}

The layout manager will reset or ignore manually set values depending on the manager. Don't set UI bounds/size manually. We have layout managers for a reason; use them. As a general rule, if you're putting layouts inside of other layouts, you're doing it wrong. You can likely do what you want by using a different manager. I would suggest using GridBagLayout. It's a little more complicated to use, but you'll get better results in the long run.

Related

setting location of JTextArea not working

I cannot figure out how to set the location of the text area. Here is my code. Not sure what is not working, obviously JTextArea is not as simple as setting the location like a button.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class BackgroundImageJFrame extends JFrame {
JButton b1;
JLabel l1;
public BackgroundImageJFrame() {
setTitle("Background Color for JFrame");
setSize(1000, 1000);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
/*One way-----------------*/
setLayout(new BorderLayout());
JLabel background = new JLabel(new ImageIcon("background-landing.png"));
add(background);
background.setLayout(new FlowLayout());
l1 = new JLabel("Here is a button");
b1 = new JButton("I am a button");
JTextArea t1 = new JTextArea("enter username", 10, 20);
t1.setLocation(30, 30);
background.add(l1);
background.add(b1);
background.add(t1);
}
public static void main(String args[]) {
new BackgroundImageJFrame();
}
}
obviously JTextArea is not as simple as setting the location like a button.
You tried to create a label with the text "Here is a button" and a button with the text "I am a button"
You button is not displayed either so that comment doesn't make sense.
The issue is that you are adding components to a JLabel. By default a JLabel does not display child components since it does not have a layout manager.
You will be able to add components to the label by setting a layout manager:
JLabel background = new JLabel(...);
background.setLayout( new FlowLayout() );
Read the section from the Swing tutorial on Layout Managers for more basics and working example of using layout managers. The tutorial code will also show you how to better structure your class so you follow Swing guidelines.
You can also check out: Background Panel for a possible alternate solution.

How do I put a JPanel in center of a JFrame irrespective the size of JFrame (of course its size is greater than jpanel)? [duplicate]

I'm using the NetBeans GUI builder to handle my layout (I'm terrible with LayoutManagers) and am trying to place a simple JLabel so that it is always centered (horizontally) inside its parent JPanel. Ideally, this would maintain true even if the JPanel was resized, but if that's a crazy amount of coding than it is sufficient to just be centered when the JPanel is first created.
I'm bad enough trying to handle layouts myself, but since the NetBeans GUI Builder autogenerates immutable code, it's been impossible for me to figure out how to do this centering, and I haven't been able to find anything online to help me.
Thanks to anybody who can steer me in the right direction!
Here are four ways to center a component:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
class CenterComponent {
public static JLabel getLabel(String text) {
return getLabel(text, SwingConstants.LEFT);
}
public static JLabel getLabel(String text, int alignment) {
JLabel l = new JLabel(text, alignment);
l.setBorder(new LineBorder(Color.RED, 2));
return l;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JPanel p = new JPanel(new GridLayout(2,2,4,4));
p.setBackground(Color.black);
p.setBorder(new EmptyBorder(4,4,4,4));
JPanel border = new JPanel(new BorderLayout());
border.add(getLabel(
"Border", SwingConstants.CENTER), BorderLayout.CENTER);
p.add(border);
JPanel gridbag = new JPanel(new GridBagLayout());
gridbag.add(getLabel("GridBag"));
p.add(gridbag);
JPanel grid = new JPanel(new GridLayout());
grid.add(getLabel("Grid", SwingConstants.CENTER));
p.add(grid);
// from #0verbose
JPanel box = new JPanel();
box.setLayout(new BoxLayout(box, BoxLayout.X_AXIS ));
box.add(Box.createHorizontalGlue());
box.add(getLabel("Box"));
box.add(Box.createHorizontalGlue());
p.add(box);
JFrame f = new JFrame("Streeeetch me..");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(p);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
});
}
}
By using Borderlayout, you can put any of JComponents to the CENTER area. For an example, see an answer to Stack Overflow question Get rid of the gap between JPanels. This should work.
Even with BoxLayout you can achieve that:
JPanel listPane = new JPanel();
listPane.setLayout(new BoxLayout(listPane, BoxLayout.X_AXIS ));
JLabel label = new JLabel();
listPane.add(Box.createHorizontalGlue());
listPane.add(label);
listPane.add(Box.createHorizontalGlue());
mKorbel's solution is perfect for your goal. Anyway I always like to suggest BoxLayout because it's very flexible.
Mara: "thanks for your response, however the NetBeans GUI Build uses GroupLayout and this is not overridable."
Not true! Right click anywhere inside JFrame (or any other GUI container) in NetBeans GUI builder and select "Set Layout". By default is selected "Free Design", which is Group layout, but you can select any other layout including Border layout as advised by mKorbel.
There's many ways to do this, depending on the layout manager(s) you use. I suggest you read the Laying Out Components Within a Container tutorial.
I believe the following will work, regardless of layout manager:
JLabel.setHorizontalAlignment(SwingConstants.CENTER)

JTextField showing through JComboBox's dropdown after Scrolling

When a JTextField is in a JScrollPanel, if the panel has been scrolled, whenever the dropdown from a JComboBox is over the JTextField, the text field shows through the dropdown.
This only happens after the content has been scrolled (not on startup of the application).
The main question is how can we fix this?
Bonus points if the answer:
Is not a hack
Explains why is it happening in the first place
Things I've tried:
Moving the dropdown outside of the scrollpane (no change)
Adding a repaint to any and every container I could find on scroll (no change)
Different Layout managers for the content of the scrollpane (no change)
Code Example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TextFieldShowsThrough{
public static void main(String[] args){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createScrollDemo());
frame.pack();
// For demonstration purposes
frame.setSize(frame.getWidth() + 100, frame.getHeight() - 100);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static JScrollPane createScrollDemo(){
final Box optionsPanel = Box.createVerticalBox();
optionsPanel.add(createDropDown());
optionsPanel.add(createTextField("Option1"));
optionsPanel.add(createTextField("Option2"));
optionsPanel.add(createTextField("Option3"));
optionsPanel.add(createTextField("Option4"));
optionsPanel.add(createTextField("Option5"));
optionsPanel.add(Box.createVerticalGlue());
JScrollPane result = new JScrollPane(optionsPanel);
// Made attempts to fix here, but to no avail
/*result.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {
#Override
public void adjustmentValueChanged(AdjustmentEvent e) {
result.repaint();
}
});*/
return result;
}
public static Box createDropDown(){
Box b = Box.createVerticalBox();
b.setAlignmentX(JLabel.LEFT_ALIGNMENT);
b.add(new JLabel("Language"));
JComboBox combo = new JComboBox(new String[]{"en", "fr", "es"});
combo.setMaximumSize(new Dimension(500, 25));
b.add(combo);
return b;
}
public static Box createTextField(String label){
Box mainBox = Box.createVerticalBox();
mainBox.setOpaque(true);
mainBox.setBackground(new Color((int)(Math.random() * 0x1000000))); // because fun
JLabel jLabel = new JLabel(label);
jLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT);
mainBox.add(jLabel);
Box secondaryBox = Box.createHorizontalBox();
secondaryBox.setAlignmentX(JLabel.LEFT_ALIGNMENT);
TextField tf = new TextField();
tf.setMaximumSize(new Dimension(500, 25));
secondaryBox.add(tf);
mainBox.add(secondaryBox);
return mainBox;
}
}
That's because you're using a java.awt.TextField, which is heavy weight component, inside a light weight container. The popup window used by the JComboBox can also be a light weight component.
AWT components don't play well with Swing components, they have z-ordering issues.
Change TextField tf = new TextField(); to JTextField tf = new JTextField();
You should also avoid using setPreferred/Minimum/MaximumSize (see Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing? for more details) and instead use layout constraints and sizing hints (like the columns property of the JTextField)

Java Swing spacing between objects

I have a Java program where i would prefer if i could get a very specific layout.
This is what I get:
JLabel JToggleButon JLabel JToggleButon
This is what I want:
JLabel JToggleButon
JLabel JToggleButon
This is the code:
package Main;
import javax.swing.*;
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
public class SystemWindow {
static JFrame window = new JFrame("System statistics");
static JToggleButton button = new JToggleButton("Push me");
static JLabel status = new JLabel("Status: ");
static JLabel status2 = new JLabel("Status: ");
static JToggleButton button2 = new JToggleButton("Push me");
static FlowLayout layout = new FlowLayout();
public static void openWindow(){
window.setLayout(new GridBagLayout());
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.add(status);
window.add(button);
window.add(status2);
window.add(button2);
window.setSize(100, 100);
window.pack();
window.setSize(200,70);
window.setVisible(true);
while(true){
status.setText("Status: "+button.isSelected());
status2.setText("Status: "+button2.isSelected());
}
}
}
p.s: Wrote the code in eclipse.
you can use GridLayout where you can specify rows, columns and spacings
i.e. add a jpanel with gridlayout and add these elements inside this panel
new JPanel(new GridLayout(2,2,5,5));
first parameter is the rows, second the columns and the others are the horizontal and vertical spacing between controls
I guess this works
JPanel panel = new JPanel(new GridLayout(2,2,5,5));
window.add(panel);
panel.add(status);
panel.add(button);
panel.add(status2);
panel.add(button2);
The behaviour you are getting is the default behaviour for FlowLayout. Read more about it here. Read morea bout layouts here and choose what you prefer.
As you are using GridBayLayout you have to provide some position constraints when adding controls to container. Here you have complete guide. 3rd party layout manager as MigLayout should suit your needs too.
while(true){
status.setText("Status: "+button.isSelected());
status2.setText("Status: "+button2.isSelected());
}
your computer is going to explode thanks to that code :)

Centering a JLabel on a JPanel

I'm using the NetBeans GUI builder to handle my layout (I'm terrible with LayoutManagers) and am trying to place a simple JLabel so that it is always centered (horizontally) inside its parent JPanel. Ideally, this would maintain true even if the JPanel was resized, but if that's a crazy amount of coding than it is sufficient to just be centered when the JPanel is first created.
I'm bad enough trying to handle layouts myself, but since the NetBeans GUI Builder autogenerates immutable code, it's been impossible for me to figure out how to do this centering, and I haven't been able to find anything online to help me.
Thanks to anybody who can steer me in the right direction!
Here are four ways to center a component:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
class CenterComponent {
public static JLabel getLabel(String text) {
return getLabel(text, SwingConstants.LEFT);
}
public static JLabel getLabel(String text, int alignment) {
JLabel l = new JLabel(text, alignment);
l.setBorder(new LineBorder(Color.RED, 2));
return l;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JPanel p = new JPanel(new GridLayout(2,2,4,4));
p.setBackground(Color.black);
p.setBorder(new EmptyBorder(4,4,4,4));
JPanel border = new JPanel(new BorderLayout());
border.add(getLabel(
"Border", SwingConstants.CENTER), BorderLayout.CENTER);
p.add(border);
JPanel gridbag = new JPanel(new GridBagLayout());
gridbag.add(getLabel("GridBag"));
p.add(gridbag);
JPanel grid = new JPanel(new GridLayout());
grid.add(getLabel("Grid", SwingConstants.CENTER));
p.add(grid);
// from #0verbose
JPanel box = new JPanel();
box.setLayout(new BoxLayout(box, BoxLayout.X_AXIS ));
box.add(Box.createHorizontalGlue());
box.add(getLabel("Box"));
box.add(Box.createHorizontalGlue());
p.add(box);
JFrame f = new JFrame("Streeeetch me..");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(p);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
});
}
}
By using Borderlayout, you can put any of JComponents to the CENTER area. For an example, see an answer to Stack Overflow question Get rid of the gap between JPanels. This should work.
Even with BoxLayout you can achieve that:
JPanel listPane = new JPanel();
listPane.setLayout(new BoxLayout(listPane, BoxLayout.X_AXIS ));
JLabel label = new JLabel();
listPane.add(Box.createHorizontalGlue());
listPane.add(label);
listPane.add(Box.createHorizontalGlue());
mKorbel's solution is perfect for your goal. Anyway I always like to suggest BoxLayout because it's very flexible.
Mara: "thanks for your response, however the NetBeans GUI Build uses GroupLayout and this is not overridable."
Not true! Right click anywhere inside JFrame (or any other GUI container) in NetBeans GUI builder and select "Set Layout". By default is selected "Free Design", which is Group layout, but you can select any other layout including Border layout as advised by mKorbel.
There's many ways to do this, depending on the layout manager(s) you use. I suggest you read the Laying Out Components Within a Container tutorial.
I believe the following will work, regardless of layout manager:
JLabel.setHorizontalAlignment(SwingConstants.CENTER)

Categories