I'm trying to set the components of this application to a set location using setLocation so far i haven't been able to move the components. There is more code but its get calling and setting this code for the most part. any ideas?
import javax.swing.*;
public class HangmanPanel extends JPanel {
private static final long serialVersionUID = -5793357804828609325L;
public HangmanPanel(){
JLabel heading = new JLabel("Welcome to the Hangman App");
JButton Button = new JButton("Ok");
//Button.addActionListener();
JLabel tfLable = new JLabel("Please Enter a Letter");
JTextField text = new JTextField(10);
String input = text.getText();
heading.setLocation(50, 20);
tfLable.setLocation(20, 100);
text.setLocation(320, 50);
Button.setLocation(230, 100);
this.add(heading);
this.add(tfLable);
this.add(text);
this.add(Button);
}
}
You should not use setLocation() to layout Swing components, it is much better to use a Layout. Please have a look at these Layout Tutorials.
Related
I'm trying to add a .gif image to a JButton, but can't seem to get the image to load when i run the code. I've included a screenshot. Included is the frame that's created. I'd really appreciate any help that can be provided. Stack is telling me I can't enter images yet, so it created a link for it. I'm also going to enclose the actual code here:
package java21days;
import javax.swing.*;
import java.awt.*;
public class ButtonsIcons extends JFrame {
JButton load, save, subscribe, unsubscribe;
public ButtonsIcons() {
super("Icon Frame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
//Icons
ImageIcon loadIcon = new ImageIcon("load.gif");
ImageIcon saveIcon = new ImageIcon("save.gif");
ImageIcon subscribeIcon = new ImageIcon("subscribe.gif");
ImageIcon unsubscribeIcon = new ImageIcon("unsubscribe.gif");
//Buttons
load = new JButton("Load", loadIcon);
save = new JButton("Save", saveIcon);
subscribe = new JButton("Subscribe", subscribeIcon);
unsubscribe = new JButton("Unsubscribe", unsubscribeIcon);
//Buttons To Panel
panel.add(load);
panel.add(save);
panel.add(subscribe);
panel.add(unsubscribe);
//Panel To A Frame
add(panel);
pack();
setVisible(true);
} //end ButtonsIcon Constructor
public static void main(String[] arguments) {
ButtonsIcons ike = new ButtonsIcons();
}
} //end ButtonsIcon Class
enter image description here
The easiest way is.
Label or Jbutton and what ever else supports HTML 3.5
JLabel a = new JLabel("");
add that to your container.
Haven't figured out how to enter code sorry
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 an UI in java and i am new in this so sorry if it's an easy question.
public class viewDeneme extends JFrame {
private static final long serialVersionUID = -7284396337557548747L;
private JTextField nameTxt = new JTextField(10);
private JTextField passwordTxt = new JTextField(10);
private JButton loginBtn = new JButton("Giriş");
private JLabel nameLbl = new JLabel("Kullanıcı adi:");
private JLabel passwordLbl = new JLabel("Şifre:");
public viewDeneme(){
JPanel loginPanel = new JPanel();
this.setSize(600,200);
this.setLocation(600, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
nameLbl.setBounds(200, 200, 100, 50);
loginPanel.add(nameTxt);
loginPanel.add(passwordTxt);
loginPanel.add(loginBtn);
loginPanel.add(nameLbl);
loginPanel.add(passwordLbl);
this.setVisible(true);
this.add(loginPanel);
}
public static void main(String[] args) {
new viewDeneme();
}
}
here is my code.I am trying to set bounds for labels and textboxes but it's not changing anything.There isn't any error so i must missing something but i couldn't find it with searching in web.Thanks for your help
See What is setBounds and how do I use it?
JPanel layout must be null to use absolute positioning. JPanel object is initialized to use a FlowLayout, unless you specify differently when creating the JPanel. So you must write
loginPanel.setLayout(null);
For the sake of less code, I am taking out code that is unrelevant to the problem, such as addActionListener(); etc.
My main class is public class TF2_Account_Chief
I have my main Jframe f; and its contents:
private static JFrame f = new JFrame("TF2 Account C.H.I.E.F.");
private JLabel runnableTogetherLabel = new JLabel("How many idlers would you like to run at a time?");
private static JTextField runnableTogetherInput = new JTextField();
private JButton runButton = new JButton("Run!");
private JButton stopButton = new JButton("Stop!");
private JButton resetButton = new JButton("Reset!");
private JButton exitButton = new JButton("Exit!");
and I set the properties of all the contents:
public void launchFrame() {
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
f.add(runnableTogetherInput);
f.add(runnableTogetherLabel);
f.add(runButton);
f.add(stopButton);
f.add(resetButton);
f.add(exitButton);
f.setSize(625, 500);
runnableTogetherInput.setSize(35, 20);
runnableTogetherLabel.setSize(275, 25);
runButton.setSize(60, 25);
stopButton.setSize(65, 25);
resetButton.setSize(70, 25);
exitButton.setSize(60, 25);
f.setLocation(0, 0);
runnableTogetherInput.setLocation(285, 3);
runnableTogetherLabel.setLocation(5, 0);
runButton.setLocation(330, 0);
stopButton.setLocation(395, 0);
resetButton.setLocation(465, 0);
exitButton.setLocation(540, 0);
}
then I have my main() method:
public static void main(String[] args) throws IOException {
TF2_Account_Chief gui = new TF2_Account_Chief();
gui.launchFrame();
Container contentPane = f.getContentPane();
contentPane.add(new TF2_Account_Chief());
}
And then I have my second JFrame iF which is not displaying the contents correctly:
private void invalidInput() {
JFrame iF = new JFrame("Invalid Input!");
JLabel iL = new JLabel("The input you have entered is invalid!");
JButton iB = new JButton("Exit!");
Container contentPane2 = iF.getContentPane();
contentPane2.add(new TF2_Account_Chief());
iF.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
iF.pack();
iF.setVisible(true);
iF.add(iL);
iF.add(iB);
iF.setSize(500, 300);
iL.setSize(125, 25);
iB.setSize(60, 25);
iF.setLocation(0, 0);
iL.setLocation(0, 15);
iB.setLocation(0, 45);
}
Now, JFrame iF is launched when the invalidInput() method is called, but you can't see that because that part of the code is unrelevant to the problem. What does matter is that the JFrame iF is launched.
The new frame looks like this:
Any ideas on why the contents are not displaying properly?
(By improperly, I mean the JButton iB takes up the whole frame and the frame is a light blue instead of the normal grey.)
You are using absolute positions without using a null layout, that's why you see a large button.
To see every component, you have to use
iF.setLayout(null);
but it's not a good practice, I'd suggest you to learn how to use Layouts and leave all the work to the layout manager
The default layout of JFrame is BorderLayout, in which there are "5" locations you can put your components to
CENTER
PAGE_START
PAGE_END
LINE_START
LINE_END
So, iF.add(component) will add the component to the CENTER, you can specify the location like this:
iF.add(component, BorderLayout.PAGE_END);
//You can also put PAGE_START, LINE_START, LINE_END, CENTER
Take my advice and read more about BorderLayout, because if you refuse to learn Layout Managers, you probably go to Absolute Positioning( null layout) which is not a good way and must not be used.
I am trying to create a form manually with code rather than the designer, I have already created using the designer.
This is the manual code that I came up with so far but I am having problem aligning the label and textfield side by side
mport java.awt.*;
import javax.swing.*;
/**
*
* #author jackandjill
*/
public class summinup_copy extends JFrame
{
private JLabel lblTitle, lblOctal, lblDecimal, lblMessage ;
private JTextField txtOctal, txtDecimal;
private JButton calculate_btn;
public summinup_copy()
{
JPanel panel = (JPanel)this.getContentPane();
panel.setLayout(new BorderLayout());
JPanel panCentre = new JPanel();
panCentre.setLayout(new GridLayout(3,3));
lblTitle = new JLabel("Area of Triangle");
lblTitle.setFont(new Font("Arial", 1, 20));
lblTitle.setHorizontalAlignment(JLabel.CENTER);
lblOctal = new JLabel("Octal");
lblOctal.setHorizontalAlignment(JLabel.CENTER) ;
//lblDecimal = new JLabel("Decimal");
//
//lblDecimal.setHorizontalAlignment(JLabel.CENTER);
lblMessage = new JLabel("Result will be displayed here");
lblMessage.setForeground(Color.red);
lblMessage.setHorizontalAlignment(JLabel.CENTER);
txtOctal = new JTextField("0", 5);
txtOctal.setHorizontalAlignment(JLabel.CENTER);
//txtDecimal = new JTextField("0", 5);
//
//txtDecimal.setHorizontalAlignment(JLabel.CENTER);
calculate_btn = new JButton("Calculate Area");
//AHandlerClass aListener = new AHandlerClass() ;
//btnOtoD.addActionListener(aListener);
//btnDtoO.addActionListener(aListener);
panCentre.add(lblOctal);
//panCentre.add(lblDecimal);
panCentre.add(txtOctal);
//panCentre.add(txtDecimal);
panCentre.add(calculate_btn);
//panCentre.add(btnDtoO);
panel.add(lblTitle, BorderLayout.NORTH);
panel.add(lblMessage,BorderLayout.SOUTH);
panel.add(panCentre, BorderLayout.CENTER);
}
public static void main(String args[]) {
summinup_copy myGui = new summinup_copy();
myGui.setTitle("Bharath");
myGui.setSize(400, 200);
myGui.setVisible(true);
}
}
As you have already figured out, you have to use LayoutManagers when coding a Swing GUI by hand. Here are some links that can help you figure out which LayoutManager is appropriate for a given look:
http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
http://docs.oracle.com/javase/tutorial/uiswing/layout/using.html
In order to place a JLabel next to a JTextField or other component, I usually use GridLayout or GridBagLayout. I find that it takes a lot of trial and error trying to get components to look the way I want. Often you have to have layers of embedded JPanels to get it just right.