Contentpanes not working in java - java

I can reply as soon as tomorrow morning (I'm really tired)
source of how I did this:
http://docs.oracle.com/javase/tutorial/uiswing/components/frame.html
This line of code is giving me errors:
win1.getContentPane().add(emptyLabel, BorderLayout.CENTER);
The part I'm having issues with is:
emptyLabel
It throws an error and it says to change to win1, which doesn't show the error but throws it
Full Class:
package examplepackage;
//imports
import java.awt.BorderLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import examplepackage.location.GetFilepath;
public class Starter {
public static void main(String[] args){
GetFilepath FP = new GetFilepath();
JFrame win1 = new JFrame("examplewindow");
win1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
win1.getContentPane().add(emptyLabel, BorderLayout.CENTER);
win1.pack();
win1.setSize(600, 800);
win1.setVisible(true);
win1.setLocationRelativeTo(win1);
win1.setIconImage(new ImageIcon(FP + "\\window\\Main").getImage());
}
}

So, based on you example, removing the references to GetFilePath, as I don't have access to that source, when I compile your code I get...
error: cannot find symbol
win1.getContentPane().add(emptyLabel, BorderLayout.CENTER);
^
symbol: variable emptyLabel
location: class Starter
Which basically means that emptyLabel is not defined. It's possible that your IDE is looking for a matching value that could be passed to the method parameter, again, based on you code, that leaves win1, which obviously isn't going to work (you can't add something to itself or a Window based component to a Container)
What you need to to is define and create an instance of some component, such as a JLabel, for example...
JLabel emptyLabel = new JLabel();
win1.getContentPane().add(emptyLabel, BorderLayout.CENTER);
I'd also suggest you have a read through Initial Thread and make sure you are initialising your UI's within the context of the Event Dispatching Thread

emmptyLabel is never initialized

Related

Need Help Updating JTextArea - Java

I'm on week three of a Java class. I am working on a class assignment that is due next week. I can complete the assignment without any problem using the console as output, which is acceptable. However, the Professor also suggested we research JTextArea and consider using it for our program output.
I found some code from a tutorial and was able to at least get a text block to appear with my first line of text to appear. But as I write the actual program, I need to continue to add additional lines to the text block as the program progresses.
When I attempt to use the following line of code in the main method to display text line 2, I get an error saying, "non-static variable textarea cannot be referenced from a static context".
textarea.append("Product1\t3\t$3.01\t$9.03");
Here is the code I have so far. Thanks in advance for any help!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ta extends JFrame{
JTextArea textarea;
public ta(){
setLayout(new FlowLayout ());
textarea = new JTextArea ("Product\tQuantity\tLine Cost\tOrder Cost\n", 5,30);
add(textarea);
}
public static void main(String[] args) {
ta gui = new ta();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(500,200);
gui.setVisible(true);
textarea.append("Product1\t3\t$3.01\t$9.03");
}
}
You can not reference textarea (which is a instance field) from a static context (ie from within main).
Instead, move textarea.append("Product1\t3\t$3.01\t$9.03"); to be within your constructor
public ta(){
setLayout(new FlowLayout ());
textarea = new JTextArea ("Product\tQuantity\tLine Cost\tOrder Cost\n", 5,30);
add(textarea);
textarea.append("Product1\t3\t$3.01\t$9.03");
}
Or provide some other "update" method for your ta class which you can call
You might like to have a read through Code Conventions for the Java TM Programming Language, it will make it easier for people to read your code and for you to read others

Best practise regarding static context

When writing a standalone java application, I see a lot of beginners code in the static context.
I used to get around this problem by creating an instance of the class in main, and working from the constructor.
I've added a few examples of a very simple standalone program, and would like to know if there are best practises for "leaving" the static context.
I would also like to know if there are things a standalone java program should be doing in the static context or specifically in the main method, what it's function is besides being the entry point of every standalone java program.
Any reading material is also welcome!
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ExampleStatic
{
JLabel label;
public static void main(String[] args)
{
//Option 1 - Work from static context:
JFrame frame = new JFrame();
frame.setBounds(10,10,100,100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel staticlabel = new JLabel("static");
frame.add(staticlabel);
frame.setVisible(true);
//Option 2 - Create instance, call initialisation function
ExampleStatic e = new ExampleStatic();
e.initialise();
//Option 3 - Create instance, handle initialisation in constructor
new ExampleStatic(true);
}
public ExampleStatic(){}
public ExampleStatic(boolean init)
{
JFrame frame = new JFrame();
frame.setBounds(10,10,100,100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label = new JLabel("constructor");
frame.add(label);
frame.setVisible(true);
}
public void initialise()
{
JFrame frame = new JFrame();
frame.setBounds(10,10,100,100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label = new JLabel("init function");
frame.add(label);
frame.setVisible(true);
}
}
Option 2 and Option 3 both are fine, as both provide the loose coupling as well if you want to use your instance somewhere else in other classes you can use it easily. But if everything you will write in Main method you are going to loose the scope and its reusability.
The JVM needs main to be static, after that you're free to do what you want. I would call a non-static "second main" that would handle initialization and then any further processing in different methods (or classes).
I would avoid putting things in the constructor, unless you really feel it's the right place for them.

how to use text fields in java

I just have a very basic question about how to use textfields in Java. It's very simple, but the tutorials and other questions I've been looking for haven't been helpful, and I'm hoping that someone can explain things a little more clearly for me.
Right now I have the following code that I just sort of slapped together for the sake of example:
import javax.swing*;
public class testText {
public static void main(String[] args){
JFrame frame = new JFrame();
JTextField text = new JTextField();
frame.add(text);
frame.setVisible(true);
System.out.println(text.getText());
}
}
All I'm trying to do, is print what the user types into the text field in the console. But nothing happens when I type into the text field.
Now,based on the research I've done, I think the problem is that I'm not using an actionListener. The thing is, I really don't understand how those work, and I'm hoping someone can clarify for me.
I've been using this tutorial to try and figure things out, and particularly the TextDemo example they have near the top. I'm still kind of at a loss though, and I can't seem to find any way to use the actionlistener interface without breaking the program. If someone could either just explain simply and directly how to use the actionlistener to pull a string from a text field and then use it, or else point me to somewhere else where I can FIND a simple straightforward explanation, I would immensely appreciate it. I've been beating my head against this for five hours now with absolutely nothing to show for it, so I apologize for asking such a basic question but I'm at a loss.
An action listener will be called when an enter key is pressed while typing in the field. From the JTextfield Javadoc :
How the text field consumes VK_ENTER events depends on whether the
text field has any action listeners. If so, then VK_ENTER results in
the listeners getting an ActionEvent, and the VK_ENTER event is
consumed.
Here is your example modified to work with an action listener :
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class testText {
public static void main(String[] args){
JFrame frame = new JFrame();
final JTextField text = new JTextField();
frame.add(text);
frame.setVisible(true);
text.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(text.getText());
}
});
}
}
And here is an object oriented complete example not relying only on a static main method.

What's Wrong WIth My Code involving JFrames

It's Giving me an error saying that "The method setContentPane(Container) in the type JFrame is not applicable for the arguments (GamePanel)"
Here is my Code:
package main;
import javax.swing.JFrame;
public class Game {
public static void main(String[] args){
JFrame window = new JFrame("Dragon Tales");
window.setContentPane(new GamePanel());
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(false);
}
}
I am following a tutorial exactly and his screen shows no errors at all.
Your GamePanel class does not extend any Swing GUI component such as Container or one of its children. Probably it should extend JPanel.
i.e.,
import javax.swing.JPanel;
public class GamePanel extends JPanel {
// .... etc
}
Please don't add the urgent or "help as soon as possible" bit. Yes your question is very important, but it is no more important than anyone else's.
Edit: Mad's link is worth putting in the answer: The Oracle Swing Tutorial.

Different windows with the same code?

This is the "main" class (doesn't contain the main method)
import javax.swing.*;
import java.awt.*;
//import java.lang.Object;
//import java.awt.event.ActionListener;
//import java.awt.event.;
public class Program {
public JFrame frame;
public JPanel header;
public JPanel text;
public JPanel body;
public JTextField input;
public JButton agregar;
public List listA;
public List listB;
public Program(String title) {
frame = new JFrame(title);
frame.setSize(500,600);
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
header = new JPanel();
header.setBackground(new Color(255,204,50));
header.setBounds(0,0,500,100);
text = new JPanel();
text.setBackground(new Color(255,204,100));
text.setBounds(0,100,500,50);
text.setLayout(null);
//Inicializando la "entrada"
input = new JTextField(20);
input.setBounds(50,13,300,25);
text.add(input);
agregar = new JButton();
agregar.setBounds(360,12,80,25);
agregar.setText("Agregar");
text.add(agregar);
//Listo
body = new JPanel();
body.setBackground(new Color(255,204,150));
body.setBounds(0,150,500,450);
//Lo que está dentro del body
listA = new List(20);
body.add(listA);
listB = new List(20);
body.add(listB);
//Listo
//Añadir todos los paneles al frame principal
frame.add(header);
frame.add(text);
frame.add(body);
}
}
And this is the MAIN class (This one contains the main method):
public class Main {
public static void main(String[] args) {
new Program("Ordenamiento Recursivo");
}
}
Each time I run the application, the UI components are presented differently, please see attached screen shot.
Well, thanks to everyone who responded the post, I finished the program and I'm very happy with the final result, here it is:
In case anyone wants to take a look at the code, here it is: Link
Problems:
You're call setVisible(true) on your JFrame before adding components and this will lead to unreliable drawing of your program's graphics and is why you are seeing different results. Don't do this, but rather call it after you've added all to the top-level Window.
As the others are saying, read up and learn to use the layout managers.
Different windows with the same code?
I think that is very simple and possible by implements CardLayout
I'd suggest don't opening a new Top-Level Container, only if is there really important reason then use JDialog or JOptionPane
Be sure to construct the GUI on the EDT. Not doing so can cause unpredictable results.
Call pack() after the components are added using layouts and then call setVisible(true).
You will need a layout manager for your form so setting the layout manager to null is not the thing to do.
Work in progress here ... https://gist.github.com/2510570
Couple of changes. Not quite finished yet, but check out the following
Have Program extend a JFrame.
Have set a layout manager.
Update
Finally I knocked this up in IntelliJ's form designer.
https://gist.github.com/2512197
Where you want to attach behaviour to the buttons search through the code for the comments that ask you to add code. Although I did this in the InteliJ Ultimate (this one that costs money) I think that no-cost free to download Community Edition UI designer also paints Swings GUIs. Very quick and easy. Netbeans also has a good GUI painter.
The Swing Tutorial on oracle.com is worth reviewing also.

Categories