text field not appearing or not reacting on location code - java

strange thing, i want to add text field next to the label. When i'm doing that it's not reacting on .setLocation command and background color does not change. Dont know why.
But when i set frame Layout to null , than background command working and changing the color , but text field are not showing. Strange. i tried with adding text field through panel, not working, by simple frame.add(textField) , not working.
public class EcrWindow extends JFrame {
JFrame ecrFrame;
JLabel ecr;
static JTextField ecrTitle;
public static void main(String[] args)
{
new EcrWindow();
}
EcrWindow()
{
JPanel p = new JPanel();
ecrFrame = new JFrame ("ECR WINDOW");
ecrFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
ecrFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
ecrFrame.setResizable(true);
ecrFrame.getContentPane().setBackground(Color.RED);
//ecrFrame.setLayout(null);
ecr = new JLabel("Emergancy Change title");
ecr.setSize(ecr.getPreferredSize());
ecr.setLocation(100,50);
ecrFrame.add(ecr);
ecrTitle = new JTextField();
ecrTitle.setColumns(30);
//ecrTitle.setSize(ecrTitle.getPreferredSize());
ecrTitle.setLocation(150,50);
p.add(ecrTitle); // adding text field to the panel, and panel adding to the frame
ecrFrame.add(p);
// ecrFrame.add(ecrTitle);
ecrFrame.setVisible(true);
}
}

The ContentPane of the Frame is not visible as soon as you add the Panel p to the frame. The content pane will be hidden by the panel which will consume the whole available space in the frame.
When you set the Layout to null, you do not see the Panel p any more as there is no information where it is rendered in the frame (the TextBox should also disappear when you set the Layout to null). This is why the red background is visible then.
Please try to add the following line to your code before you add the Panel p to the frame:
p.setBackground(Color.RED);
Then you should see a red background which is actually the Panel p.
Regarding the layout, you shouldn't use setLocation(). It is much better to use a different layout mechanism with a proper LayoutManager.
See also this answer.
You can use setLocation() if you use absolute positioning. But that would mean that you effectively write a layout manager by hand. I would advise you to read the guide Laying Out Components Within a Container - there are various explanations and examples you can build up upon.

Related

I can't to get Label and Buttons components in created window

I tryed to learn about GUI and tryed to create the window with two buttons and jne Label on the screen. But I don't understand why I can't see these elements simultaneously. When I comment out lines for buttons I can see the Label element.
Here is my code:
import java.awt.*;
import javax.swing.*;
public class MyWin {
public static void main(String[] args) {
JFrame w = new JFrame("My Window");
w.setSize(1000,800);
w.setVisible(true);
JButton b = new JButton("My button");
b.setVisible(true);
b.setSize(150, 100);
b.setLocation(500, 20);
JButton b2 = new JButton("Second button");
b2.setVisible(true);
b2.setSize(150,100);
b2.setLocation(500, 600);
JLabel l = new JLabel("My label");
l.setVisible(true);
w.getContentPane().add(b);
w.getContentPane().add(b2);
w.getContentPane().add(l);
}
}
The default layout for the JFrame is BorderLayout and when you add your JLabel through single parameter add method you add it with a BorderLayour.CENTER constraint as a default, this causes to fill all the available space. So you might want to use layout manager suitable for your needs, then the components won't overlay themselves.
Visual Guide to Layour Managers
First of all, JFrame uses BorderLayout as a default layout and just adding the components (w.getContentPane().add(b)) sets them in BorderLayout.CENTER; where they occupy the whole JFrame to fill the empty space. Thus, is recommended to add components in a JPanel. So, you should create first a JPanel, add the components to the JPanel and finally add it to the JFrame.
The setSize(...); statement is not applied due to the default layout (FlowLayout) in JPanels and also is discouraged. (Because it won't work properly in different computers with different screen resolutions)
If you want to change the size of the components you should change the default layout and use instead a customLayout, borderLayout, gridLayout...
If you want to understand deeply how layouts work and all the available layouts in Java check this

Putting a Panel on top of a JLabel backGround (Java)

I've been fruitlessly searching the internet and nothing that people suggest seems to have any effect for me.
I have a JFrame which I'm trying to put a JPanel in. That JPanel ideally would have a JLabel with an imageicon as the background and a set of buttons in its own Jpanel in the foreground. The issue is every type of layout manager I've seen suggested just does not work as advertised for me. The best I've gotten to work so far is this approach:
public MenuBackgroundPanel(AsteroidsFrame frame)
{
this.gameFrame = frame;
this.setLayout(new OverlayLayout(this));
ImageIcon image = new ImageIcon(getClass().getResource("/resources/background1.gif"));
imageLabel = new JLabel(image, JLabel.CENTER);
mp = new MainMenuPanel(gameFrame);
mp.setMaximumSize(new Dimension(300,200));
this.add(mp);
this.add(imageLabel);
this.setVisible(true);
}
Unfortunately, I'm getting really strange alignments and trying to set location on the background (to actually get it to start at the JFrame's (0,0) or moving the button panel just seems to have no effect. Printing the location of each object says they're both at (0,0) but the image I'll link shows this is just not the case. My point is, I've tried things like JLayeredPane or setting the JLabel as the contentpane of the Jframe and making it transparent but nothing seems to do anything. One or the other of the two objects just covers the other completely.
As you can see the objects are not at all aligned.
Could anyone help me with this?
That JPanel ideally would have a JLabel with an imageicon as the background and a set of buttons in its own Jpanel in the foreground
Easiest way for something like this when the child panel is fully contained in the label image is to just set the layout manager of the JLabel and then add your components to the label.
JLabel background = new JLabel( new ImageIcon(...) );
background.setLayout( new GridBagLayout() );
JPanel buttons = new JPanel();
buttons.setOpaque( false );
buttons.add(...);
background.add(buttons, new GridBagConstraints() );
Now the button panel will be centered on the label.
As you can see the objects are not at all aligned
If you want to use the OverlayLayout then you need to play with the alignmentX/Y properties of each component. You would probably want to set them both to .5. Check out: Java Layout with Component always in Top Right for an example of how changing these values can affect the layout.

JButton positioning, does not appear

In my code I have a JFrame that opens up a main menu, in that menu you can click options, which will take you to the options menu. On that options menu I want to create a back button that will position itself somewhere in the top left corner of the screen. When I run the program and go to the options menu the JButton does not appear. Something must be wrong with my code. Any help? Below is where I first declare the JButton.
static JButton optionsBackButton = new JButton("<html><font size = 5
color = green>Back</font></html>");
Here is the other part of the code that has to do with the JButton.
//Options Menu
JPanel optionsPanel = new JPanel();
JLabel optionsOptionsTitle = new JLabel("<html><font size = 7 color = blue>Options</font></html>");
JPanel optionsOptionsTitlePanel = new JPanel();
JPanel optionsBackButtonPanel = new JPanel();
optionsPanel.setLayout(null);
optionsBackButton.setBounds(100,100,50,50);
optionsBackButtonPanel.add(optionsBackButton);
optionsOptionsTitlePanel.add(optionsOptionsTitle);
optionsPanel.add(optionsOptionsTitlePanel);
optionsPanel.add(optionsBackButtonPanel);
optionsBackButton.addActionListener(this);
//Add panels to the card
panel.add("Home Screen", homePanel);
panel.add("Options Menu", optionsPanel);
//card.add("Game screen", gamePanel);
cardLayout.show(panel, "HomeScreen");
contentPane.add(panel);
Your problem is stemming from your use of null layouts. Note:
JPanel optionsBackButtonPanel = new JPanel(); // holds the back button
// but never given a size
optionsPanel.setLayout(null); // uh oh,.... bad news
optionsBackButton.setBounds(100,100,50,50); // yes you set the bounds of the button
optionsBackButtonPanel.add(optionsBackButton);
optionsOptionsTitlePanel.add(optionsOptionsTitle);
optionsPanel.add(optionsOptionsTitlePanel);
optionsPanel.add(optionsBackButtonPanel); // again, optionsBackButtonPanel
// has been never given a size or location/bounds
optionsBackButton.addActionListener(this);
So you set the bounds of the button and add it to a JPanel that uses the default FlowLayout, and so the bounds are meaningless. Then you add that JPanel, whose bounds you never set, to a JPanel that uses null layout. So the optionsBackButtonPanel will never show.
Solution: Don't use null layouts, but instead learn and use the layout managers.
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.
Start here: Laying Out Components in a Container Tutorial

JFrame Questions (deleting textimages adding new ones)

So I am making a game, and I want to know if it is possible so when lets say "You created a fire" it deletes that line and then displays "Your fire turns into ashes".
two more,
I want to make a jframe background, and let's say I "login" the background disappears, and a new background comes in(but the game, not a background).
I want to add a image icon( already added) (IMAGE = FIRE) it deletes that image and a new one appears( IMAGE = ASHES), how can I do this?
public class FireLabel extends JPanel {
public LabelDemo() {
super(new GridLayout(3,1)); //3 rows, 1 column
JLabel label1;
//Create the first label.
label1 = new JLabel("You created a Fire", JLabel.CENTER);
//Add the labels.
add(label1);
add(label2);
add(label3);
}
The context is a little light, however.
For swicthing from one view to another, I would suggest using a CardLayout, which would allow you to change from the login screen to the game screen.
If you're using JLabel as you primary output...simple change the text or icon using setText or setIcon as required...
To change that, use JLabel.setText. You will then have to call validate for the change to take effect.
I recommend swapping out the content pane for this. Put the login screen in a JPanel and set that as the content pane, then when needed, change the content pane to a second JPanel for the game.
Use the same technique as #1. Use a JLabel to display the image.

How can I Change the default Icon of a JPanel based swing app (or window)

I've seen many answers for this question when it's a JFrame, but none for JPanel, and all that I've tried didn't work.
So basically I've written this simple class/app that extends JPanel, and all is working fine. Now I'd like to change the Default Icon.
Any ideas?
Just as guys are saying here in comments please reconsider what you are trying to do.
The only option to change an icon is to set it for the frame in which the panel is child, since the icon is a part/belongs to the frame.
If you want setting of the icon to be a functionality of a panel then in addNotify() method, which is called when a component receives a parent, look through the panel's parent and it parent and so on until you will reach the frame and set the icon for it.
Sample showing a number of parent you must go through to get to frame if a panel is its content pane.
JPanel p = new JPanel();
JFrame f = new JFrame();
f.setContentPane(p);
System.out.println(SwingUtilities.windowForComponent(p));

Categories

Resources