Java code error not sure what i am supposed to do? - java

I bought a new book called "learning Java" and I am struggling with the following problem.
It asked me the type the code below, however now it says we are going to replace the JLabel with our own graphical class. HelloCompoent is the new graphical class that he wants me to create and it should display Hello Java.
import javax.swing.*;
public class Helloworld {
public static void main(String[]args){
JFrame frame = new JFrame ("Hello, Java");
JLabel label = new JLabel("Hello world", JLabel.CENTER);
frame.add(label);
frame.setSize(300,300);
frame.setVisible(true);
}
}
I tried
import javax.swing.*;
import java.awt.*;
public class Helloworld {
public static void main(String[]args){
JFrame frame = new JFrame ();
class HelloComponent extends JComponent{
public void paintComponent (Graphics g){
g.drawString("Hello, Java", 123, 95);
frame.add(new HelloComponent());
}
}
}
}

After declaring your class you need to create an instance of it and add it to the frame:
HelloComponent helloComponent = new HelloComponent( );
frame.add(helloComponent);
frame.setSize(300,300);
frame.setVisible(true);
and you probably should remove the
frame.add(new HelloComponent());
from the paintComponent-method.
The paintComponent will only be called if an instance of the class is added to the component hierarchy of a visibile frame. So you have to add it to the frame before calling the paintComponent. Therefore you can remove it from that method.

Related

Is it possible to create a panel with a class on the left and right side?

I have been practicing my code with Java Swing and have gotten decent on controlling where to place some items, such as labels and or buttons, but I was wondering if you can do the same with classes? I have just a simple class with enough code to put a button in it and that's it, that I am trying to create an instance of the class and then control for to put on the left and right side but when I do, all it does is create two separate windows with the button in the middle and that's it. Am I doing something wrong, or can you not do classes the same way?
The code:
import java.awt.Color;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Fun extends JFrame
{
private final int WIDTH = 500;
private final int HEIGHT = 400;
public Fun()
{
setTitle("Fun Management");
setSize(WIDTH, HEIGHT);
BuildPanel west = new BuildPanel(); /// BuildPanel is the name of the class that has just a button in it.
BuildPanel east = new BuildPanel(); ///
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(west, BorderLayout.WEST); /// I am doing the same thing with the instances as I would with buttons or labesl
add(east, BorderLayout.EAST);
setVisible(true);
}
public static void main(String[] args)
{
new Fun();
}
}
I took your code and created the following GUI.
Oracle has a rad tutorial, Creating a GUI With Swing, that will show you how to create Swing GUIs. Skip the Netbeans section.
Always start your Swing application with a call to the SwingUtilities invokeLater method. This method ensures that your Swing components are created and executed on the Event Dispatch Thread.
Use Swing components. Don't extend a Swing component unless you want to override one or more of the component methods.
The JFrame methods must be called in a specific order. This is the order I recommend for most Swing applications. Use the JFrame pack method and let the components size the JFrame.
I created a BuildPanel class to build a JPanel. There are good reasons to do this, but be careful. You have to manage each instance of the class you create. As an example, what if you want the text of the two buttons to be different? What if you want to assign two different ActionListener classes, one to each button?
Here's the complete runnable code. I made the BuildPanel class an inner class so I can post the code as one block.
import java.awt.BorderLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TwoPanelExample implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new TwoPanelExample());
}
#Override
public void run() {
JFrame frame = new JFrame("Fun Management");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BuildPanel west = new BuildPanel();
BuildPanel east = new BuildPanel();
frame.add(west.getPanel(), BorderLayout.WEST);
frame.add(east.getPanel(), BorderLayout.EAST);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public class BuildPanel {
private final JPanel panel;
public BuildPanel() {
this.panel = createMainPanel();
}
private JPanel createMainPanel() {
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(5, 30, 5, 30));
JButton button = new JButton("Click Me");
panel.add(button);
return panel;
}
public JPanel getPanel() {
return panel;
}
}
}

Swing code compilation error "missing ;"

How do I solve this compilation error? Note that I'm new to Swing.
http://prntscr.com/bpz2ve
package gui;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class GUI extends Frame {
public static void main(String[] args) {
JFrame frame = new JFrame("Hello World - YaBoiAce");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(500, 300);
// Layout //
frame.setLayout(new BorderLayout());
// Swing Component //
final JTextArea textarea = new JTextArea();
JButton jbutton = new JButton("Click me");
// Add Component to content pane
Container c = frame.getContentPane();
c.add(textarea,BorderLayout.CENTER);
c.add(jbutton, BorderLayout.SOUTH);
// Action Listener
jbutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textarea.append("Hello");
} // Eclipse says 'missing ;' on this line.
}
private static void setDefaultCloseOperation(int exitOnClose) {
}
}
Eclipse says "Missing ;" But when I put that in, It highlights the ; saying "Missing ;" again. It keeps on doing that. Any help?
It is on the line marked with:
// Eclipse says 'missing ;' on this line.
There are many problems in your code:
As stated in the
comments
by #HovercraftFullOfEels:
You're not matching closing parenthesis on your addActionListener method too. Again good code formatting will help you see this.
// Action Listener
jbutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textarea.append("Hello");
} // Eclipse says 'missing ;' on this line.
}); //HERE YOU NEED TO ADD: );
You're extending Frame (Maybe you were trying to extend JFrame)
and creating a JFrame object, choose which one you want to use
(Recommended to create the object instead of extending, because if
you extend a JFrame your class is a JFrame and cannot be
included somewhere else and you're not changing it's functionallity
either so, no need to extend).
You're creating a private static method
private static void setDefaultCloseOperation(int exitOnClose) {}
That method should be public and belongs to JFrame class, I guess your IDE wrote that when you extended Frame instead of JFrame.
Frame belongs to java.awt while JFrame belongs to javax.swing so, they are not the same.
You're creating your windows and every component inside your main
method instead of the constructor
You're adding your components to a Container but never add that container to your JFrame, so you need to call
frame.setContentPane(c);
So your code should look like this:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class GUI {
JFrame frame;
public GUI() {
frame = new JFrame("Hello World - YaBoiAce");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(500, 300);
// Layout //
frame.setLayout(new BorderLayout());
// Swing Component //
final JTextArea textarea = new JTextArea();
JButton jbutton = new JButton("Click me");
frame.add(textarea,BorderLayout.CENTER);
frame.add(jbutton, BorderLayout.SOUTH);
// Add Component to content pane
Container c = frame.getContentPane();
c.add(textarea,BorderLayout.CENTER);
c.add(jbutton, BorderLayout.SOUTH);
frame.setContentPane(c);
// Action Listener
jbutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textarea.append("Hello");
} // Eclipse says 'missing ;' on this line.
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new GUI());
}
}

How to create an hello world in Java Swing? What is wrong in my code?

I am studying Java Swing and I have some problem with the following simple code:
package com.techub.exeute;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
public class Main{
public static void main(String[] args) {
JFrame frame = new JFrame("FrameDemo");
frame.setMinimumSize(new Dimension(800, 400));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel myLabel = new JLabel("Hello World !!!", SwingConstants.CENTER);
myLabel.setFont(new Font("Serif", Font.BOLD, 22));
myLabel.setBackground(Color.blue);
myLabel.setOpaque(true);
myLabel.setPreferredSize(new Dimension(100, 80));
frame.getContentPane().add(myLabel, BorderLayout.NORTH);
}
}
My idea is to create a JFrame object and insert into it an Hello World JLabel object settings some property.
I do it into the main() method. The problem is that when I execute the program I don't see anything !!! Why? What is wrong in my code?
Tnx
Andrea
You are creating the frame but you are not displaying it. Call
frame.setVisible(true);
to display it.
Another thing: you should not manipulate GUI components in the main thread. Instead, create a new method for creating the frame and setting up the components, and run that method in the event dispatch thread, like in the example from the official tutorial:
import javax.swing.*;
public class HelloWorldSwing {
private static void createAndShowGUI() {
JFrame frame = new JFrame("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Hello World");
frame.getContentPane().add(label);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Just add
frame.setVisible(true);
to your code
See the steps to Creating and Showing Java Swing Frames
//1. Create the frame.
JFrame frame = new JFrame("FrameDemo");
//2. Optional: What happens when the frame closes?
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//3. Create components and put them in the frame.
//...create emptyLabel...
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
//4. Size the frame.
frame.pack();
//5. Show it.
frame.setVisible(true);
You missed out #5
You need a
frame.setVisible(true);
call in your code.
As others mentioned you should not use the main Thread for gui operations. I suggest you should refer to the official tutorials of SWING, they are rather helpful and you'll see examples there for proper threading.
keep this line in your method
frame.setVisible(true);

JPanel code in a class without main method

I am trying code a JPanel in a class (classA) and trying to instantiate it from a class (classB) (where the main method is).
But when I try to code the classA the content assist does not supports. It does not resolves panel related codes, shows syntax error.
What could the problem be?
import javax.swing.*;
import java.awt.*;
public class gui1 {
JFrame j = new JFrame("MY Menu");
j.setSize(900, 700);
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
j.setResizable(false);
}
You cannot call methods outside of a method / static initialization block. Try initializing it in the constructor:
public class Gui1 {
JFrame my_frame;
public Gui1()
{
my_frame = new JFrame("MY Menu");
my_frame.setSize(900, 700);
my_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
my_frame.setResizable(false);
}
}

Java GUI won't display JLabel

I would like to create a simple GUI in Java. I know the basics of creating JLabel, etc. However, I cannot find why my JLabel is not displayed on the screen. Here is my code:
package test;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.*;
public class A1Panel extends JPanel implements ActionListener {
JLabel firstInt;
public void init() {
makeComponents();
makeLayout();
}
private void makeComponents() {
firstInt = new JLabel("First argument");
firstInt.setFont(new Font("Helvetica", Font.BOLD, 16));
firstInt.setBackground(Color.lightGray);
firstInt.setVisible(true);
firstInt.setHorizontalAlignment(SwingConstants.CENTER);
}
private void makeLayout() {
add(firstInt);
}
public void actionPerformed(ActionEvent e) {
}
}
I then add my JPanel to my JFrame using a different class called GUI:
import test.A1Panel;
public class GUI {
public static void main(String[] args) {
JFrame frame = new JFrame("Testing GUI");
frame.setLayout( new GridLayout(1,3));
JPanel panel = new A1Panel();
panel.setBorder( BorderFactory.createRaisedBevelBorder() );
frame.add( panel);
frame.setSize(800,600);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.pack();
}
}
When I hit compile, what I get is a simple frame with three empty panels. I do not understand why my JLabel is not in the first panel since I have added it to my frame. Am I missing something?
The frame is not empty, the panel is. Nowhere in your code do I see a call to the methods init() or makeComponents(). In fact, I would turn your init() method into a constructor, like so:
public A1Panel() {
makeComponents();
makeLayout();
}
Another alternative to this would be to call panel.init() after declaring JPanel panel = new A1Panel()
After you instance A1Panel, you haven't called A1Panel.init()
I would suggest removing init() and adding all the code to the constructor of A1Panel. If, however, you wanted to keep the init() function, you would want to call it after JPanel panel = new A1Panel()
The code to add the label was not actually called in the main, was it? So look carefully, when is init actually called?
Look at the
private void makeLayout()
method.
If I replace public void init() by A1Panel(), it does the job. Thank you for your help.

Categories