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.
Related
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.
Game(){
JFrame frame = new JFrame("Display Image");
JPanel panel = (JPanel)frame.getContentPane();
frame.setSize(1000,625);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel();
label.setIcon(new ImageIcon("C:/Users/Ragnar/Desktop/GameBoard.png"));
panel.add(label);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
So i have this constructor ,and i want to add some new JLabels with Images,but i want them to be displayed on top of first image which is the image of the first jLabel label.Can anyone guide me how to achieve this please?I tryed to add them as usually but they are displayed behind the label.
If you have a background image and you want to display the JLabel on top of the background image, you can use a JPanel to hold the background image, then add your JLabel.
Usually if you try to let 2 JLabel overlap each other it won't succeed due to the default layout manager used by the container (such as FlowLayout in JPanel or BorderLayout in JFrame).
If you really want to let them over lap, you will have to set the layout as null. But they may introduce new problems as you lose control over the appearance of your components.
Hence, in cases like this I would usually go for custom painting and draw the images you want in any particular order you are interested in.
For example: How to create a background and foreground image which overlaps?
If you are working with eclipse, and you have installed the windowbuilder plugin you can use the graphical editing view.
Within this view use the contextual menu to order the elements.
What worked for me was, when adding the components with the method add(component), adding them in order from front to back. In the following example I add a lot of components to a JFrame, and the last one to be added is the wallpaper, so it stays at the background.
import java.awt.Image;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class LogIn extends JFrame implements ActionListener{
public static JFrame operador;`enter code here`
private JLabel logo, foot, mensaje, wallpaper;
private JTextField fldUser;
private JPasswordField fldPass;
private JButton entrar;
private int ancho =400, largo= 530;
public static String user="", pass="", name;
public LogIn() {
setLayout(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(ancho,largo);
setResizable(false);
setTitle("Acceso al sitema");
setLocationRelativeTo(null);
setIconImage(getIconImage());
fldUser = new JTextField();
fldUser.setHorizontalAlignment(JTextField.CENTER);
fldUser.setBounds(125,320,150,25);
fldUser.setBackground(new Color(50,50,255));
fldUser.setForeground(Color.WHITE);
fldUser.setBorder(new SoftBevelBorder(BevelBorder.LOWERED));
add(fldUser);
fldPass = new JPasswordField();
fldPass.setHorizontalAlignment(JTextField.CENTER);
fldPass.setBounds(125,360,150,25);
fldPass.setBackground(new Color(50,50,255));
fldPass.setForeground(Color.WHITE);
fldPass.setBorder(new SoftBevelBorder(BevelBorder.LOWERED));
add(fldPass);
mensaje= new JLabel();
mensaje.setBounds(0,390,ancho,15);
mensaje.setForeground(Color.RED);
mensaje.setHorizontalAlignment(SwingConstants.CENTER);
add(mensaje);
entrar =new JButton("Entrar");
entrar.setBounds(125,410,150,40);
entrar.setForeground(new Color(50,50,255));
//entrar.setBorder(new SoftBevelBorder(BevelBorder.RAISED));
entrar.addActionListener(this);
add(entrar);
logo = new JLabel();
logo.setBounds(50,0,300,300);
ImageIcon imgLogo= new ImageIcon("src/images/DS.png");
Icon iconoLogo = new ImageIcon(imgLogo.getImage().getScaledInstance(logo.getWidth(),logo.getHeight(), Image.SCALE_DEFAULT));
logo.setIcon(iconoLogo);
foot = new JLabel("Desarrollado por Gabriel Santos");
foot.setBounds((ancho-200)/2,largo-60,200,30);
//When JLabels overlap, the ones that come to the front are the first to be added to the window.
add(foot);
add(logo);
wallpaper = new JLabel();
wallpaper.setBounds(0,0,window.getWidth(),window.getHeight());
ImageIcon img = new ImageIcon("src/images/wallpaperPrincipal.jpg");
Icon icono = new ImageIcon(img.getImage().getScaledInstance(this.getWidth(),this.getHeight(), Image.SCALE_DEFAULT));
wallpaper.setIcon(icono);
add(wallpaper);
setVisible(true);
}
}
I am trying to make a Rock, Paper, Scissors game and I have added 3 buttons to the frame, however when I launch the program two of the buttons don't appear until you hover over them, anyone have any idea why?
import javax.swing.*;
import java.awt.event.*;
import java.util.Random;
import java.awt.FlowLayout;
import javax.swing.JOptionPane;
public class RPSFrame extends JFrame {
public static void main(String [] args){
new RPSFrame();
}
public RPSFrame(){
JFrame Frame1 = new JFrame();
this.setSize(500,500);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Rock, Paper or Scissors game");
this.setLocationRelativeTo(null);
ClickListener cl1 = new ClickListener();
ClickListener cl2 = new ClickListener();
ClickListener cl3 = new ClickListener();
JPanel panel1 = new JPanel();
JLabel label1 = new JLabel("Result:");
panel1.setLayout(new FlowLayout(FlowLayout.CENTER, 25, 25));
this.add(panel1);
this.setVisible(false);
JPanel panel2 = new JPanel();
JButton Rock = new JButton("Rock");
Rock.addActionListener(cl1);
panel2.setLayout(new FlowLayout(FlowLayout.LEFT));
panel2.add(Rock);
this.add(panel2);
this.setVisible(true);
JPanel panel3 = new JPanel();
JButton Paper = new JButton("Paper");
Paper.addActionListener(cl2);
panel3.setLayout(new FlowLayout(FlowLayout.CENTER));
panel3.add(Paper);
this.add(panel3);
this.setVisible(true);
JPanel panel4 = new JPanel();
JButton Scissors = new JButton("Scissors");
Scissors.addActionListener(cl3);
panel4.setLayout(new FlowLayout(FlowLayout.RIGHT));
panel4.add(Scissors);
this.add(panel4);
this.setVisible(true);
}
private class ClickListener implements ActionListener{
public void actionPerformed(ActionEvent e){
if(e.getSource() == "Rock"){
int AI = new Random().nextInt(3) + 1;
JOptionPane.showMessageDialog(null, "I have been clicked!");
}
}
}
}
The setVisible(true) statement should be invoked AFTER all the components have been added to the frame.
You currently have two setVisible(...) statements, so you need to get rid of the first one.
Edit:
Took a second look at the code. You have multiple setVisible(...) statements. Get rid of them all except for the last one.
Don't create separate panels for each button. Instead you create one panel (called buttonPanel) for all the buttons. In your case you might use a horizontal BoxLayout. Add a button to the panel, then add glue then add a button, then add glue and then add your final button. Then add this buttonPanel to the NORTH of the frame. ie. this.add(buttonPanel, BorderLayout.NORTH). Read the section from the Swing tutorial on How to Use Box Layout for more information on how the layout works and on what glue is.
The problem is that JFrame has a default BorderLayout. When you just add(component) without specifying a BorderLayout.[POSITION] e.g add(panel, BorderLayout.SOUTH), then the component will get added to the CENTER. The problem with that is each POSITION can only have one component. So the only component you see id the last one you add.
Now I don't know after specifying the positions, if you will get your desired result. A BorderLayout may not be the right fit. But just to see a change, you can set the layout to GridLayout(0, 1) and you will see the component.
this.setLayout(new GridLayout(0, 1));
If this is not the result you want, then you should look over Laying out Components within a Container to learn the different layouts available to you.
Also as I pointed out in my comment
if(e.getSource() == "Rock"){
with the above, you are trying to compare an object (ultimately a button) with a String. Instead you will want to compare the actionCommand
String command = e.getActionCommand();
if("Rock".equals(command)){
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 :)
I'm trying to write an undecorated JFrame. I'm trying to put my button over my background label. However setting the button's Z order causes the button streches to size of jframe and neither setBounds() nor setSize() changes the situation. Here is my code:
import javax.swing.*;
public class MyApp {
public static void main(String[] args) {
JFrame mainFrame = new JFrame();
mainFrame.setBounds(0, 112, 100, 50);
mainFrame.setLayout(null);
mainFrame.setUndecorated(true);
JLabel lblBackground = new JLabel(new ImageIcon(JFrame.class.getResource("/res/green.png")));
lblBackground.setBounds(0, 0, 100, 50);
JButton btnStart = new JButton("");
btnStart.setBounds(5, 15, 10, 15);
mainFrame.add(lblBackground);
mainFrame.add(btnStart);
mainFrame.setComponentZOrder(btnStart, 0);
mainFrame.setComponentZOrder(btnStart, 1);
mainFrame.setVisible(true);
}
}
Thanks for replies.
Use a JLayeredPane for this.
You will need to create a new JLayeredPane:
JLayeredPane layered = new JLayeredPane();
Set your JFrame to use this as a content pane:
mainFrame.setContentPane(layered);
And add your components, in this format:
layered.add(Component c, int layerNumber);
Hope that works for you!
More on JLayeredPanes
Don't play with null layouts. Swing was designed to be used with layout managers
Add the button to the label. For example:
JLabel label = new JLabel(...);
label.setLayout( new FlowLayout() );
JButton button = new JButton(...);
label.add( button );
frame.add(label);
frame.pack();
frame.setVisible(true);
Now the frame should be the same size as your image. The button should be centered on the top of the image. If you want the button positioned somewhere else then use a different layout manager.