How to Move JLabes Around - java

import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Gui_Window extends JFrame {
private JLabel Main_L;
public Gui_Window() {
setLayout(new FlowLayout());
Main_L = new JLabel("Did you know it is possible to bind keys?");
add(Main_L);
}
public static void main (String args[]) {
Gui_Window gui = new Gui_Window();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(300,300);
gui.setVisible(true);
gui.setTitle("Gamers AudioMute");
gui.setResizable(true);
}
}
I would like to know how to move my "Did you know" Label around. Could you also state how to align left, right, middle and how to move it around by its coordinates?

You can use methods included in Swing classes. Try
mainL.setHorizontalAlignment(SwingConstants.LEFT);
mainL.setVerticalAlignment(SwingConstants.BOTTOM);
The two methods setHorizontalAligment and setVeritcalAlignment both take integers that will set the start of either the horizontal or vertical component of the label to that pixel integer within the Swing window.
You should also read up on SwingConstants which allow you to plug in pre-defined integers by Swing that will align your texts to desirable locations within the panel. Here's a link
http://docs.oracle.com/javase/7/docs/api/javax/swing/SwingConstants.html
They are also useful when manipulating different layouts such as BorderLayout and GridLayout.

Related

Add Textfields on Jframe at Runtime

I am trying to create text-fields on frame by getting input at run-time. Is it possible? Or I have to create another frame for that. I tried this code, but it's not working. Please Help me out, and tell me what's wrong with this code.
import java.awt.BorderLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Check extends JFrame implements ActionListener
{
JTextField txtqty;
JTextField[] tfArr;
JPanel p1,p2;
JButton bsmbt;
public Check()
{
GUIDesign();
}
public void GUIDesign()
{
p1 = new JPanel();
txtqty = new JTextField(10);
JButton bsmbt= new JButton("OK");
p1.add(txtqty);
p1.add(bsmbt);
p2=new JPanel();
p2.setLayout(null);
add(p1,BorderLayout.NORTH);
setSize(500, 500);
setVisible(true);
setLocation(100, 100);
bsmbt.addActionListener(this);
}
public static void main(String[] args)
{
new Check();
}
public void TFArray(JTextField[] temp)
{
int x,y,width,height;
x=10;y=30;width=50;height=20;
int no_of_textboxes = Integer.parseInt(txtqty.getText());
temp=new JTextField[no_of_textboxes];
for(int i=0;i<no_of_textboxes;i++)
{
temp[i]= new JTextField(10);
temp[i].setBounds(x, y, width, height);
x+=(width+10);
p2.add(temp[i]);
}
add(p2);
}
#Override
public void actionPerformed(ActionEvent ae) {
JOptionPane.showMessageDialog(this, txtqty.getText());
TFArray(tfArr);
}
}
->Method TFArray() isn't working.
You have many errors in your code:
public void TFArray(JTextField[] temp): method names should start with lowerCamelCase
You're extending JFrame, you shouldn't extend JFrame, because when you extend it your class is a JFrame, JFrame is rigid so you can't place it inside anything else, instead you might consider creating a JFrame instance and if you ever need to extend JComponent extend from JPanel.
JButton bsmbt= new JButton("OK"); the variable bsmbt is a local variable inside your constructor, your global variable bsmbt is not used anywhere, and if you try to use it later you'll get a NullPointerException, instead change that line to:
bsmbt= new JButton("OK");
You're using null layout for p2, instead use a proper Layout manager and read Null layout is evil and Why is it frowned upon to use a null layout in swing?. Swing was designed to work with different PLAFs, screen sizes and resolutions, while pixel perfect GUIs (with setBounds()) might seem like the best and faster way to create a complex GUI in Swing, the more GUIs you make, the more errors you'll get due to this.
To solve your problem call revalidate() and repaint()
The above code creates 2 textfields. but when I again put some value and submit it, it doesn't seem to reflect any changes.
That might be because you're overriding x, y, height and width variables each time you enter TFArray method. But that is a guess, if you want a real answer, follow the suggestions above and post a proper and valid Minimal, Complete, and Verifiable example

JPanel not showing when added to another JPanel

I'm trying to create a game in Java - the game is going to be a 2-D scrolling game. I have a class called CornPanel which extends JPanel and shows a corn plant - the CornPanel's are what will be moved across the screen. I know the CornPanel class is working because it shows up when I add it directly to a JFrame. However, when I try to add a CornPanel to another JPanel and then add that JPanel to the JFrame, the CornPanel doesn't show up.
Here's my CornPanel class (abbreviated - I took out the stuff I'm pretty sure isn't causing the problem):
package game;
import java.awt.Graphics;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class CornPanel extends JPanel{
BufferedImage cornImage;
public CornPanel(){
loadImages();
}
public void loadImages(){
try{
cornImage = ImageIO.read(new File("src\\cornBasic.png"));
} catch(IOException e){
e.printStackTrace();
}
}
protected void paintComponent(Graphics g){
g.drawImage(cornImage, 0, 0, cornImage.getWidth(), cornImage.getHeight(), this);
}
}
My Game class:
package game;
import java.awt.Color;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Game extends JFrame{
ArrayList<CornPanel> cornPanels;
JPanel gameContainer;
public Game(){
cornPanels = new ArrayList<CornPanel>();
gameContainer = new JPanel();
setSize(1000, 1000);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBackground(new Color(98, 249, 255));
setExtendedState(JFrame.MAXIMIZED_BOTH);
getContentPane().add(gameContainer);
addCornPanel();
setVisible(true);
}
public void addCornPanel(){
CornPanel cornPanel = new CornPanel();
cornPanels.add(cornPanel);
gameContainer.add(cornPanel);
cornPanel.setVisible(true);
getContentPane().repaint();
repaint();
}
public static void main(String[] args) {
Game game = new Game();
}
}
Note: I got it to work by setting the LayoutManager for both the JFrame and gameContainer to new GridLayout(1,1), but the problem is that then I can't use setLocation() on the CornPanel in order to make it animate. If there's a way to do it without setLocation() let me know. Also, I took out a lot of code I don't think is necessary for diagnosing the problem - hopefully I didn't take out too much.
Your corn panel doesn't specify a prefered size, so the layout manager probably is just setting it to 0x0.
There is an easier way to add an icon into a pane. JLabel::JLabel(Icon) will create a label that has the image icon specified, and is of the right size to hold it.
If you do need something more complex than a single image, then your JComponent implementation should override getPreferredSize().
You also should call "pack" on your jframe, so that it can figure out the ideal size for display.
A few other comments not related to your original question:
You shouldn't extend JFrame for the main frame, just create a new JFrame instance, and configure it.
You should do the work in the Event Dispatch Thread. See EventQueue and more specifically read through Lesson: Concurrency in Swing
I know the CornPanel class is working because it shows up when I add it directly to a JFrame. However, when I try to add a CornPanel to another JPanel and then add that JPanel to the JFrame, the CornPanel doesn't show up.
The layout of the content pane of a frame is BorderLayout, the default constraint is CENTER which stretches a component to fill the space.
The default layout of a panel is FlowLayout which ..doesn't stretch the component to fit.
The best way to fix this is to (firstly) override the getPreferredSize() method of CornPanel to return a sensible size, then add it to a layout/constraint that has the behavior required when it has more space than it needs.

why is my JLabel not producing an image?

I have gone over several tutorials and was wondering why my JLabel is not producing an image? I thought I had everything where I should be for the image to be displayed. Is it possible other graphics in my program are interfering? Is there any top-down layer system java uses to determine which images are on top of each other if you have multiple ones on top of each other??
package scratch;
import java.awt.Font;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Graphics;
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JLabel;
//import statements
//Check if window closes automatically. Otherwise add suitable code
public class okay extends JFrame {
JPanel jp = new JPanel();
JLabel jl = new JLabel();
public okay(){
jl.setIcon(new ImageIcon("C:\\Users\\ShawnK\\Desktop\\cat.png"));
jp.add(jl);
add(jp);
validate();
}
public static void main(String args[]) {
JFrame window = new JFrame();
okay t1 = new okay();
window.setSize(640,800);
window.setTitle("lets do this");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
window.setVisible(true);
drawingComponent DC = new drawingComponent();
ai enemy = new ai();
window.add(DC);
window.add(t1);
}
}
You're just creating a plain vanilla JFrame:
JFrame window = new JFrame();
and you never create a new okay() object. Understand that it will not create itself by magic, and if you want it displayed, you have to do this in code.
As an aside, I have no idea in creation what a drawingComponent is:
drawingComponent DC = new drawingComponent();
since you never show the class code. Also you shouldn't set a JFrame visible until all the components have been added.
Also
Learn and follow Java naming conventions as doing this will help others (us!!) better understand your code. Variable names should all begin with a lower case letter while class names with an upper case letter.
Avoid extending JFrame. While this may be OK for trivial programs such as this, it does not scale well, meaning it makes your code more complicated and paints you in the corner in even slightly larger or more complex programs.
Instead gear your GUI's toward creating JPanels, panels that then can be placed in JFrames if desired, or JDialogs, or JOptionPanes, or other JPanels. This will give your code much greater flexibility.
Again, don't call setVisible(true) on a JFrame until all initial components have been added.
Yes, you're better off getting your image as a BufferedImage using ImageIO.read(...) and then placing this into your ImageIcon. It's a bit safer and (I think) allows for better caching of images.

Creating a Interactive GUI for a java game

Hey guys I'm creating a game similar to farmville in java and I'm just wondering how would I implement the interactive objects/buttons that the user would usually click to interact with the game client.
I do not want to use the swing library (generic windows looky likey objects), I would like to import custom images for my buttons and assign button like properties to those images which would be used for the GUI.
Any advice? Any pointers? I can't seem to find that information through youtube or some other java gaming sites as they're only showing simple example using swing.
Any help would be deeply appreciated thanks!
Regards
Gareth
Do you really not want to use Swing, or do you just not want the default look and feel of a JButton and other swing controls? What does " (generic windows looky likey objects), " mean?
There are many sources out there that describe customizing buttons to include images on top of them:
Creating a custom button in Java
JButton and other controls have all the events and methods associated with adding click listeners, etc. You probably don't want to create your own control. We do not have enough information to go off of, for example what does "interactive objects" mean?
If you simply want to add an icon to a JButton, use the constructor that takes an Icon.
You can use JButton, just override the paint function. and draw what ever you want there. It takes a while until you get it at the first time how this works. I recommend you to read a little about the event-dispatching thread (here is java's explanation)
And here is some code that I wrote so you have a simple reference.
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Test extends JButton implements ActionListener{
private static final long serialVersionUID = 1L;
Image img;
/** constuctor **/
public Test(String tImg, JFrame parent){
this.img = new ImageIcon(tImg).getImage();
this.addActionListener(this);
}
/*********** this is the function you want to learn ***********/
#Override
public void paint(Graphics g){
g.drawImage(this.img, 0, 0, null);
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO do some stuff when its clicked
JOptionPane.showMessageDialog(null, "you clicked the button");
}
public static void main(String[] args) {
JFrame f = new JFrame();
Test t = new Test("pics.gif", f);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new GridLayout(1, 1));
f.add(t);
f.setSize(400,600);
f.setVisible(true);
}
}

Fire mouse event on underlying components

I'm looking for a way to pass mouse events to components covered by other components. To illustrate what I mean, here's a sample code. It contains two JLabels, one is twice smaller and entirely covered with a bigger label. If you mouse over the labels, only the bigger one fires mouseEntered event however.
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.WindowConstants;
import javax.swing.border.LineBorder;
public class MouseEvtTest extends JFrame {
public MouseEvtTest() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLayout(null);
setSize(250, 250);
MouseAdapter listener = new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
System.out.printf("Mouse entered %s label%n", e.getComponent().getName());
}
};
LineBorder border = new LineBorder(Color.BLACK);
JLabel smallLabel = new JLabel();
smallLabel.setName("small");
smallLabel.setSize(100, 100);
smallLabel.setBorder(border);
smallLabel.addMouseListener(listener);
add(smallLabel);
JLabel bigLabel = new JLabel();
bigLabel.setName("big");
bigLabel.setBorder(border);
bigLabel.setSize(200, 200);
bigLabel.addMouseListener(listener);
add(bigLabel, 0); //Add to the front
}
public static void main(String[] args) {
new MouseEvtTest().setVisible(true);
}
}
What would be the best way to fire mouse entered event on the smaller label when cursor is moved to the coordinates above it? How would it work in case where there would be multiple components stacked on top of each other? What about the remaining mouse events, like mouseClicked, mousePressed, mouseReleased, etc.?
Take a look at Alexander Potochkin's blog entry on A Well-Behaved GlassPane
In your listener:
bigLabel.dispatchEvent(mouseEvent);
Of course, you will have to define bigLabel as final
Well to understand whats happening you need to understand how Z-Ordering works. As a quick overview, the component that was added last is painted first. So in your case you want to add the small component before the big component.
// add(bigLabel, 0); //Add to the front
add(bigLabel); // add to the end so it is painted first
The OverlayLayout might help explain this better and give you another option.

Categories