Different windows with the same code? - java

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.

Related

JTabbedPane Malfunctioning

I have a problem with my code. I am trying to get into user interfaces in Java, and have started using JOptionPane. At the moment, I'm experimenting with JTabbedPane, but I have a problem with it. My problem is the following: when I try to run the code, so that a panel with one tab appears reading 'You are using the program "CarDealership".', nothing happens. I don't know what's the problem, but my terminal reads the following when I compile and run my program...:
Terminal...: TerminalOutput
My code...: ProgramCode
I'm coding in Visual Studio Code, and, as you can tell by reviewing the code, I am from México. I translated the variables used in the program in a comment. Thank you for reading!
Code in text...:
/*
The name of the program translates to 'ProgCarDealership'.
Variables used...:
Example: 'Type/NameInSpanish/NameInEnglish'
- JTabbedPane/Pestañas/Tabs
- JLabel/Contenido/Content
- JPanel/Pestaña1/Tab1
*/
import javax.swing.*;
public class ProgLoteDeCarros extends JFrame
{
public VentanaPrincipal()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setExtendedState(MAXIMIZED_BOTH);
setVisible(true);
setTitle("Programa Lote de Carros");
JTabbedPane Pestañas = new JTabbedPane();
JPanel Pestaña1 = new JPanel();
JLabel Contenido = new JLabel ("Estas usando el programa 'Lote de Carros'.");
Pestaña1.add(Contenido);
Pestañas.addTab("Información", Pestaña1);
getContentPane().add(Pestañas);
}
public static void main (String [] Yoshi)
{
ProgLoteDeCarros VentanaPrincipal = new ProgLoteDeCarros();
}

jMenuItem doesn't appear

I've just starting using Java Swing and I have a issue.
I tried to do a simple menuBar and a menuItem 'Exit', but before linking the button to the action the menuItem appeared, now that I've linked the button to a System.exit(0) action it disappeared. Help?
The code is the following:
in MainPanel (the autogenerated code from swing is excluded):
public void init() {
initComponents();
initActions();
setLocationRelativeTo(null);
pack();
setVisible(true);
}
private void initActions() {
this.menuItemExit.setAction(Application.getInstance().getPanelControl().getActionExit());
}
In PanelControl:
public class PanelControl {
private Action actionExit;
public Action getActionExit() {
return actionExit;
}
public class ActionExit extends AbstractAction{
public ActionExit(){
putValue(Action.NAME, "Exit");
putValue(Action.SHORT_DESCRIPTION, "Exit from the application");
putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("ctrl e"));
putValue(Action.MNEMONIC_KEY, KeyEvent.VK_E);
}
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
In Application:
private void init() {
viewMainPanel = new MainPanel();
controlPanel = new ControlPanel();
viewMainPanel.init();
}
i think the problem is somewhere in here but i can't figure out where. any help?
(there's other code but i just put the more relevant part, also i translated the code from italian so i'm sorry if there are any problems or a few names dont match up)
private Action actionExit;
public Action getActionExit() {
return actionExit;
}
Your actionExit variable is null.
Nowhere in your code do you create an instance of your ActionExit class.
Somewhere you need:
actionExit = new ActionExit();
Your design seems a bit complicated, I have no idea why you have a panel just to create an instance of the ActionExit class.
I would suggest you just create the ActionExit instance in your main class and get rid of the PanelControl class.
Instead of using an IDE to generate confusing code you should consider learning how to write the code yourself so you can better structure your classes. Read the section from the Swing tutorial on How to Use Menus for a working example to get you started.
A menu item has to be added to a Native Java Swing component. You have to add it to a JFrame. You can't add a MenuItem to a Panel. The Parent 'root' container in any Java Swing application is 'native' and a JFrame. Everything else in that container is 'drawn' into the rectangle using the look and feel of your choosing.
Then you CREATE a MenuItem using your TAbstractAction item. That object CAN be used to create a JButton, JMenuItem or ToolBar button. Keeping a reference to your TAbstractAction in your code, you can enable/disable the object and it implements an 'observable' pattern where it will enable/disable ALL UI controls you used to build with it. I actually wrote a Java Swing framework for doing Java Applications. It used to be on the Sun Open Source web site. If you wish I can put it up on GitLab for you to play with. Java Swing is nice but JavaFX should be the long term goal for UI on a JVM.
In your JFrame object you need to do this:
_menuBar = new JMenuBar();
// add controls to the frame
setJMenuBar(_menuBar);
Then you need to add your 'exitMenuItem' to your _MenuBar control.
Cheers

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

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.

Categories