How To Add JLabel to Already Existing Jframe? - java

lol i dont even know if i worded that right
i am a really new programmer and this is my code for the main class:
package culminatingnew;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class CulminatingNew {
public static void main(String[] args) {
Container container = null;
JFrame jframe = new JFrame("Math Adventure");
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setLocationRelativeTo(null);
jframe.setBounds (150, 0, 1000, 1000);
jframe.setBackground(Color.blue);
jframe.setVisible(true);
JLabel labelText = new JLabel("Welcome!");
jframe.getContentPane().add(new CharacterChoose());//
jframe.setVisible(true);
jframe.getContentPane().add(labelText);
jframe.setVisible(true);
So basically, I'm making a game. In another class in the assignment package is CharacterChoose, where the user is greeted with a picture of their character. All I want to do is add text to this same screen saying "Welcome", but whenever I try this it just ignores the CharacterChoose screen and opens a new blank frame that says "Welcome". Is there any way to fix this?

GUI's are not linear/procedural programs, the are event driven, that is, something happens and you respond to it.
Instead, maybe consider using a button saying "Continue" or something, which the user must press, once pressed, you can then present the next view.
I'd recommend having a look at CardLayout for easier management of switching between views.
See How to Use Buttons, Check Boxes, and Radio Buttons, How to Write an Action Listeners and How to Use CardLayout for more details

Related

Could someone help me understand how the ACCELERATOR_KEY works in Java?

I am trying to understand how the ACCELERATOR_KEY is used and what it does. I found a code example online that shows how it is used, but when I run the code nothing seems to happen.
If I had to guess it seems the ACCELERATOR_KEY allows the user to assign a keyboard command to something, but in this example when I press ‘A’, nothing happens. Any ideas or explainations would be most appreciated! Thank you!
// w w w . java 2 s .c o m
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.KeyStroke;
public class Main {
public static void main(String[] a) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Action action = new ShowAction();
JCheckBox button = new JCheckBox(action);
frame.add(button, BorderLayout.CENTER);
frame.setSize(350, 150);
frame.setVisible(true);
}
}
class ShowAction extends AbstractAction {
public ShowAction() {
super("About");
putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("A"));
putValue(Action.NAME, "Go to number ");
}
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("About Swing");
}
}
If I had to guess it seems the ACCELERATOR_KEY allows the user to assign a keyboard command to something
Correct.
However, if you read the ActionAPI you will see that the ACCELERATOR_KEY is only used for components that extend JMenuItem (except for JMenu).
If you want to use "A" as a KeyStroke to invoke an Action for the JCheckBox, then you need to use Key Bindings to manually do the binding by using the InputMap and ActionMap of the check box.
Read the section from the Swing turtorial on How to Use Key Bindings for more information.
Note the tutorial also has a section on How to Use Menus and the demo code in that section demonstrates how to use an accelerator.
You can also try the How to Use Actions section. The Actions used in that demo are used by both a menu item and a button. You can try adding an accelerator the the Action to see the difference between the two components.

Added components are not painted until parents are repainted from another source

When I modify a component in a component tree of any depth, the modifications usually show automatically, immediately, without need for me to take any action to that end.
Not so when the modification is an addition of a new child.
Furthermore, if I want to force the repaint using any of the methods appropriate (as far as I understand the API), this has no tangible effect as well.
Only when a new modification to the existing tree - including the added, but still invisible component - is made, does the added child appear.
Here is an example, that will render a black window with an "Add" button at the bottom. Clicking the button will have no effect. Resizing or minimising the window will cause as many white "XX" strings to appear, as the button has been pressed beforehand.
I would, of course, very much like to have the additions appear immediately one by one, whenever the button is pressed.
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Applikation
{
public static void main(String[] argumente)
{
Box dummy = new Box(BoxLayout.Y_AXIS);
JFrame window = new JFrame();
JPanel panel = new JPanel();
panel.setBackground(Color.black);
window.add(dummy);
dummy.add(panel);
JButton button = new JButton("Add");
button.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e)
{
JLabel white = new JLabel("XX");
white.setBackground(Color.white);
white.setForeground(Color.white);
panel.add(white); // only visible after resizing window or switching focus to another program and back
panel.invalidate(); // does nothing
panel.repaint(); // does nothing
panel.repaint(200); // does nothing
} });
dummy.add(button);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
}
What am I missing?
Note that this is essentially a duplicate of this question, but as can bee seen in my example code, none of its answers do apply: They empirically do not work.

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.

Why my JScrollPane is different from the example?

I'm trying to learn a bit of Swing and i'm trying 14.46.2.Add component to JScrollPane example. The code is this:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.border.LineBorder;
public class AddingToJScrollPane {
public static void main(String args[]) {
JFrame frame = new JFrame("Tabbed Pane Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Label");
label.setPreferredSize(new Dimension(1000, 1000));
JScrollPane jScrollPane = new JScrollPane(label);
JButton jButton1 = new JButton();
jScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
jScrollPane.setViewportBorder(new LineBorder(Color.RED));
jScrollPane.getViewport().add(jButton1, null);
frame.add(jScrollPane, BorderLayout.CENTER);
frame.setSize(400, 150);
frame.setVisible(true);
}
}
From the page you can see what is the expected result.
However, just copy&pasting that code, I get the result in the image below. I'm trying to understand if the example is out of date or the example image is wrong (where's the red border on the tutorial image?). Moreover, my scrollbars are not enabled whiley I'm expecting that they are. Am i missing something to get them enabled (in the tutorial they are ok)? I'm using JDK7.
It is OK to see the red border, it is caused by this line:
jScrollPane.setViewportBorder(new LineBorder(Color.RED));
As a background info, you should be aware that setting a colored line border to components is a useful debugging possibility in Swing (otherwise it is often hard to see where one component ends and another starts), so here the author probably wanted to debug something after taking the screenshot, and forgot to remove this line from the code.
BTW, if you want to learn Swing, the best online resource is the "official" one: http://docs.oracle.com/javase/tutorial/uiswing/components/scrollpane.html
EDIT: the scrollbars are enabled, it is not like they are "greyed out", there is a visual change if you click on the arrows. There is nothing to scroll, because the button is always resized to the size of the visible area. As I said, this is not a good example, don't learn from here...
The code is ok and the bordar is Red
jScrollPane.setViewportBorder(new LineBorder(Color.RED));
and the image in the link is wrong image

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);
}
}

Categories