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();
}
Related
So I'm trying out IntelliJ IDEA's content designer for a simple GUI, and I followed all guides on using it, but it when run from IDEA (not compiled into a JAR yet) it comes back with the following error:
Exception in thread "main" java.awt.IllegalComponentStateException: contentPane cannot be set to null.
at java.desktop/javax.swing.JRootPane.setContentPane(JRootPane.java:594)
at java.desktop/javax.swing.JFrame.setContentPane(JFrame.java:679)
at com.AdamT.MergeSortGui.<init>(MergeSortGui.java:18)
at com.AdamT.MergeSortGui.main(MergeSortGui.java:13)
My code:
package com.AdamT;
import javax.swing.*;
class MergeSortGui extends JFrame {
private JPanel panel;
private JTextField inputList;
private JButton submitButton;
private JLabel inputLabel;
private JLabel outputLabel;
public static void main(String[] args) {
new MergeSortGui();
}
MergeSortGui() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setContentPane(panel);
this.setTitle("MergeSort GUI");
this.add(inputList);
this.add(submitButton);
this.add(inputLabel);
this.add(outputLabel);
this.pack();
this.setVisible(true);
}
}
I would add my form, too, but I can't because then this woudld be mostly code... I uploaded all of my project here. From what I have seen from the error, it is because it's assuming that the content of each variable is null, even though it's taken care of by my .form file. Any ideas?
(I know this is a dupe of this, but that has no working answer so I really am at completely lost)
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
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.
SEE UPDATE AT THE BOTTOM!!
I've tried to figured out how to do this for a couple of days but so far I have had no luck.
Basically what I want to do is have a combobox, which when an option is selected loads an applet, and passes a value to the applet.
Here is the code for the ComboBox class, which is supposed to open the other class in a new window. The other class is the main class for an applet. They are both in the same project but in different packages. I know that there aren't any errors with the rest of the code.
//where I evaluate the selection and then open SteadyStateFusionDemo
// more selections just showing one code block
combo.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie){
String str = (String)combo.getSelectedItem();
if (str.equals("NSTX")) {
machine = "A";
JFrame frame = new JFrame ("MyPanel2");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
SteadyStateFusionDemo d = new SteadyStateFusionDemo();
frame.getContentPane().add (new SteadyStateFusionDemo());
d.init();
frame.pack();
frame.setVisible (true);
And just to cover everything here is the beginning of the init() method of SteadyStateFusionDemo as well as the main method in the class. Too much code to post otherwise. There are several different privates before the init method.
//method that initializes Applet or SteadyStateFusionDemo class
public void init() {
//main method of the SteadyStateFusionDemo class
public static void main (String[] args) {
JFrame frame = new JFrame ("MyPanel");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new SteadyStateFusionDemo());
frame.pack();
frame.setVisible (true);
What am I doing wrong? Why doesn't my class load?
UPDATED: Changed the code so that a JFrame opens and then the JApplet loads inside. I have successfully done this in a test Java applet but for some odd reason it won't work with this Applet. I even set up the test in a similar way (The code for this is virtually the same, except with different class names, and of course a much, much shorter init() method). Can someone help me figure out why this isn't working? Also, a JFrame will open if I delete the lines referring to SteadyStateFusionDemo, but once I reference it won't work. Why does this happen?
UPDATE:
Based on your feedback, it seems you are trying to achieve the following:
Use the code of an existing Applet (found here) in a Desktop application (i.e. in a JFrame).
Converting an Applet to a Desktop application is an "undertakable" task, the complexity of which depends on how much "Applet-specific" stuff is used by the Applet. It can be as simple as creating a JFrame and adding myFrame.setContentPane(new myApplet().getContentPane()); or as complex as...hell.
This tutorial might be a good place to start.
After taking a look at the Applet at hand, it seems to be fairly easy to convert it. The only complicating factor is the use Applet's methods getCodeBase() and getImage(URL) (somewhere in the code). These two methods result in a NullPointerException if the Applet is not deployed as...an Applet.
So, what you can do is override those two methods in order to return the intended values (without the exception). The code could look like this:
/* Import the necessary Applet entry-point */
import ssfd.SteadyStateFusionDemo;
/* Subclass SSFD to override "problematic" methods */
SteadyStateFusionDemo ssfd = new SteadyStateFusionDemo() {
#Override
public URL getCodeBase() {
/* We don't care about the code-base any more */
return null;
}
#Override
public Image getImage(URL codeBase, String imgPath) {
/* Load and return the specified image */
return Toolkit.getDefaultToolkit().getImage(
this.getClass().getResource("/" + imgPath));
}
};
ssfd.init();
/* Create a JFrame and set the Applet as its ContentPane */
JFrame frame = new JFrame();
frame.setContentPane(ssfd);
/* Configure and show the JFrame */
...
The complete code for an example JFrame Class can be found here.
Of course, you need to have all Classes from the original Applet accessible to your new Class (e.g. put the original Applet in your classpath).
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.