Error occurs when trying to start Java GUI in IntelliJ - java

GameLauncher class
package me.beanbeanjuice;
import me.beanbeanjuice.utilities.Game;
import me.beanbeanjuice.utilities.filehandlers.DictionaryHandler;
import me.beanbeanjuice.utilities.filehandlers.DistributionHandler;
public class GameLauncher {
public GameLauncher() {
new Window();
}
public static void main(String[] args) {
new DictionaryHandler();
new DistributionHandler();
new Game();
// TESTING. MenuScreen() should start first. MenuScreen() when "startButton" is hit, it should start game.
//new Window();
new GameLauncher();
}
}
Window class
package me.beanbeanjuice;
import javax.swing.JFrame;
public class Window extends JFrame {
public Window() {
super();
setTitle("Boggle");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setContentPane(new GamePanel(720, 1280));
add(getContentPane());
pack();
setLocationRelativeTo(null);
setVisible(true);
}
}
GamePanel class
package me.beanbeanjuice;
import javax.swing.*;
import java.awt.*;
public class GamePanel extends JPanel {
public static int width;
public static int height;
public GamePanel(int width, int height) {
super();
setPreferredSize(new Dimension(width, height));
setFocusable(true); // Allows the JPanel to have input as soon as the JFrame is made.
requestFocus();
}
}
Error Message
Error Message in GameLauncher class
Hello, I'm following a tutorial for making a Java GUI in IntelliJ, and it won't even start. If you look at the last link, it shows this weird "error" and it won't start the GUI. It leads to the "Error Message" link as shown for link number 4. How do I fix this? I followed the tutorial exactly and even tried making a new project to no avail. I've tried swapping the Window() and GameLauncher() calls in the GameLauncher class but it is still not working. I've also tried with and without the super() call.

So the issue was with a display driver, however, I do not know if it still occurs. What fixed it was unplugging all of my external monitors, running the code, plugging them back in, stopping the code, running the code, then it worked again.

In Window Constructor in the Window class, at this line add(getContentPane()); you are adding container's parent to itself. This line is the same as writing getContentPane.add(getContentPane()).
I dont know what do you mean to put in the frame. Using JFrame you need to add the child to the JFrame's content pane. Removing this line works for me.
https://docs.oracle.com/javase/tutorial/uiswing/components/frame.html

Related

How is JFrame.setResizable supposed to be used?

I'm trying to followed java tutorials and now I am going over JFrame.
This is a information inquiry more than help question.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Login {
public static void main(String[] args){
//Creating object of LoginFrame class and setting some of its properties
LoginFrame frame = new LoginFrame();
frame.setTitle("LoginForm");
frame.setVisible(true);
frame.setBounds(10, 10, 370, 600);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
This code will cause the frame to be resized to a very small size at the top left corner regardless of the bounds I set.
A simple fix for this is to place frame.setResizable() before setting its bounds.
Does anyone know why this happens or am I doing something wrong?
I'm also on Ubuntu 20.04, maybe this matters but I haven't found an answer.
Tutorial shows above code.
The following is the code for LoginFrame
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//Creating LoginFrame class
public class LoginFrame extends JFrame implements ActionListener {
//Creating constructor of LoginFrame() class
LoginFrame(){
}
//Overriding actionPerformed() method
#Override
public void actionPerformed(ActionEvent e){
}
}
Like I was saying I was only following a tutorial. This was only the beginning of the tutorial but I had the same issue when starting another very simple frame tutorial.
The following works fine for me :
import javax.swing.*;
class Scratch extends JFrame {
public Scratch() {
super();
}
public static void main(String[] args){
//Creating object of LoginFrame class and setting some of its properties
Scratch frame = new Scratch();
frame.setTitle("LoginForm");
frame.setVisible(true);
frame.setBounds(10, 10, 370, 600);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Result : I see a big rectangular window - in the shape of a smart phone screen I'd say.
setResizable(false) means you cannot resize the frame. I suspect the problem you're trying to identify lies somewhere in the LoginFrame class... no code for this was included though so hard to comment furhter.

Java components are invisible when swing app is run as APPLET

Respected all,
I am making a Swing-application window in ECLIPSE. When I run the program as 'JAVA-Application' the program functions well. However when I try to run the program as "Java_applet" the components like 'command button', 'textbox' are invisible.
I am entirely new to Java. I had previously worked on C#. Kindly please help me.
import java.awt.EventQueue;
import java.applet.*;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import java.awt.BorderLayout;
public class sa extends Applet{
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
sa window = new sa();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public sa() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JRadioButton rdbtnNewRadioButton = new JRadioButton("New radio button");
frame.getContentPane().add(rdbtnNewRadioButton, BorderLayout.CENTER);
}
}
You can't just have your class extend Applet and expect that that is all that is necessary for it to behave like a proper Applet. You need to give the class a proper init method and build the GUI from within this method. But most importantly you will need to read an Applet tutorial, any decent tutorial should do. Myself, I'd have my GUI extend JPanel, build the GUI in its constructor, and then I could use this JPanel in a JApplet or JFrame as needed.
As Andrew aptly notes in comment,
I think the OP should also dump the entire 'applet' part of it and develop the JFrame with an idea to launching it from a link using Java Web Start. At least then it would have a better chance for working for users of Chrome and FireFox (which are both planning to remove all support for applets).

Game in Java won't respond to key presses

I have just exported a Java game I made to a Runnable JAR.
The game has an opening screen (a class named OpeningScreen extending JPanel). When you press ENTER, it's supposed to go from the opening screen to the game itself (create a new Board instance and add it to the JPanel.)
It works fine inside Eclipse.
An instance of OpeningScreen is created in the class with main(), named Starter.
When exporting, I set the Starter class as the "Launch configuration", and set "Library handling" to "Extract required libararies into generated JAR".
After exporting, I get a window saying that it exported with compile errors, but doesn't tell me which errors exactly.
When starting the program from the generated JAR, the opening screen does show, but pressing ENTER won't start the game, although it does work inside Eclipse.
Here's the code for OpeningScreen:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class OpeningScreen extends JPanel implements KeyListener{
private static final long serialVersionUID = 1L;
public OpeningScreen(){
setFocusable(true);
setVisible(true);
addKeyListener(this);
}
public void paint(Graphics g){
super.paint(g);
setBackground(Color.BLACK);
Graphics2D g2d = (Graphics2D) g;
// A lot of drawing Strings.
}
public void startGame(){
JFrame frame = new JFrame("Pong Battle");
frame.setSize(500,500);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Board board = new Board();
frame.add(board);
frame.setVisible(true);
}
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key==KeyEvent.VK_ENTER)startGame();
}
public void keyReleased(KeyEvent arg0) {
}
public void keyTyped(KeyEvent arg0) {
}
}
EDIT: Starter class:
import javax.swing.*;
import java.awt.*;
public class Starter extends JFrame {
public Starter(){
setSize(500,500);
setResizable(false);
setTitle("Pong Battle");
setDefaultCloseOperation(EXIT_ON_CLOSE);
OpeningScreen openingS = new OpeningScreen();
add(openingS);
setVisible(true);
}
public static void main(String[]args){
Starter starter = new Starter();
}
}
What could be the problem? Thanks
Don't use a KeyListener. You should be using Key Bindings.
See Motion Using the Keyboard for the reasons why and a working example.
Your opening screen needs to be added inside another container and subsequently another Jframe
Create another JFrame.
Make it undecorated. f.setUndecorated(true)
Make opening screen panel as content panel f.setContentPane(new OpeningPanel())
Display this frame.
Remove the opening screen frame once Enter key is pressed. f.dispose()
and then call startGame()

I want to make my frame close when the X(close button) is clicked

I have a small template that ive built for the purpose of implementing an applet through a simple java application via netbeans 7.1 (as in not using Javacard, Netbeans Platform etc ..just a simple java application with applet initialized when application runs)
I have managed to make it invoke the applet when i press the run button in netbeans and i ahve functionality inside the applet but, i cant seem to get it to close and i have a horrible feeling people are gonna tell me to have used jFrame and implement the EXIT_ON_CLOSE method.
This is NOT something I would like to know how to do , my mission is to implement it using Frames != jFrames.
I hope someone can help as its bugged me for a bit now and i have to get on with Java assignment that involves its use.
Enclosed is the code/classes for A: the appletframe and B:the applet
* 1.4 Write an applet to display a line of text.
* The text should then change its font size and style (bold, italic, underline)
* depending on where the mouse is clicked on the screen.
*/
package appletframe;
import java.awt.Graphics;
import java.awt.Frame;
import java.applet.Applet;
/**
* #author MuthaLoad aka Gruffy2012
*/
import java.awt.*;
public class AppletFrame extends Applet{
public static void main(String[] args) {
/*construct needs object instances*/
MrApplet mrApplet = new MrApplet(); // create instance/obj of MrApplet
Frame myFrame = new Frame("Applet"); // create frame "title optional"
//setDefaultCloseOperation(myFrame.EXIT_ON_CLOSE);(jFrame- not wanted)
/* add applet to the frame*/
//myFrame.addWindowListener();
myFrame.add(mrApplet, BorderLayout.CENTER);
myFrame.setBounds(10,10,500,500);
myFrame.setVisible(true); // step to make frame visible
/*initialize instance of mrApplet*/
mrApplet.init();
} // end main
} // end class
B: applet
package appletframe;
import java.awt.*; //for buttons
import java.awt.event.*; //for events
import java.applet.*; //main applet api`s
import java.awt.Graphics; //graphics
public class MrApplet extends Applet implements ActionListener
{
private static final long serialVersionUID = 1L;
Button btnClick;
String msg = "";
public void init()
{
// TODO start asynchronous download of heavy resources
setSize(500, 500);
Button btnClick = new Button("Press Me ");
btnClick.addActionListener(this);
add(btnClick);
}
public void actionPerformed(ActionEvent e)
{
//throw new UnsupportedOperationException("Not supported yet.");
msg = "Yay, the button works";
repaint();
}
public void paint (Graphics g)
{
g.setFont(new Font("Serif", Font.ITALIC, 30)); //new font obj, font , font style, font size
g.setColor(new Color(0,255,0)); //new color obj, r,g,b
g.drawString(msg, 40, 80);
}
// TODO overwrite start(), stop() and destroy() methods
}
Once again thanks for reading, and to clarify any confusions..
I am looking for a pointer as to the solution of closing my applet and frame window upon exit , without reimplementing it all using jFrame, though i know this would be easier in the first instance.
Thankyou and as always, indebted to all your advice.
gruffy321
add this line at the end of ApplicationFrame class.
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
You want to do it with Frame not with JFrame, then you have to add the WindowListener event to the frame and have to override windowClosing() method.
myFrame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
});

Buttons all over the window - Java

I am trying to learn java and i am practicing with a simple program with 2 simple buttons. Here is my code :
import javax.swing.*;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Askhsh 3");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ColorJPanel application = new ColorJPanel();
frame.add(application);
frame.setSize(500,500);
frame.setVisible(true);
}
}
And the class ColorJPanel:
import java.awt.*;
import javax.swing.*;
public class ColorJPanel extends JPanel{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
this.setBackground(Color.WHITE);
JButton arxikopoihsh = new JButton("Αρχικοποίκηση");
JButton klhrwsh = new JButton("Κλήρωση");
add(arxikopoihsh);
add(klhrwsh);
this.revalidate();
this.repaint();
}
}
As you can see the only thing i want to do for now is to place 2 simple buttons that do nothing! Here is my output:
http://imageshack.us/photo/my-images/847/efarmogh.jpg/
When i am running the application i am seeing the buttons filling the window!
Note that if i remove the "this.revalidate();" command i have to resize the window to see the buttons !
Thanks very much for your time :)
Don't add components in paintComponent. This method is for painting only, not for program logic or to build GUI's. Know that this method gets called many times, often by the JVM and most of the time this is out of your control, and also know that when you ask for it to be called via the repaint() method, this is only a suggestion and the paint manager may sometimes choose to ignore your request. The paintComponent method must be lean and fast as anything that slows it down will slow down the perceived responsiveness of your application.
In your current code, I don't even see a need to have a paintComponent method override, so unless you need it (if doing for instance custom painting of the component), I suggest that you get rid of this method (and the calls to repaint and revalidate). Instead, add your components in the class's constructor and make sure to pack your top level container after adding components and before calling setVisible(true). Most important -- read the Swing tutorials as this is all covered there.
e.g.,
Main.java
import javax.swing.*;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Askhsh 3");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ColorJPanel application = new ColorJPanel();
frame.add(application);
frame.pack();
frame.setVisible(true);
}
}
ColorJPanel.Java
import java.awt.*;
import javax.swing.*;
public class ColorJPanel extends JPanel{
public static final int CJP_WIDTH = 500;
public static final int CJP_HEIGHT = 500;
public ColorJPanel() {
this.setBackground(Color.WHITE);
JButton arxikopoihsh = new JButton("Αρχικοποίκηση");
JButton klhrwsh = new JButton("Κλήρωση");
add(arxikopoihsh);
add(klhrwsh);
}
// let the component size itself
public Dimension getPreferredSize() {
return new Dimension(CJP_WIDTH, CJP_HEIGHT);
}
}

Categories