Swing code compilation error "missing ;" - java

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());
}
}

Related

JButton and JTextField

What's wrong? ImageIcon and the frame's size are working properly.
But the JTextField and the JButton aren't.
I need the solution.
import javax.swing.*;
import javax.swing.ImageIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Frame {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("Alkalmazás");
frame.setVisible(true);
frame.setSize(500,500);
frame.setResizable(false);
JTextField field = new JTextField();
field.setBounds(40,250, 300,35);
JButton button = new JButton(new ImageIcon("table.png"));
button.setBounds(40,400, 250,25);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
tf.setText(""something);
}
});
frame.add(field);
frame.add(button);
}
}
You didn't mention what's "not working properly", but there are a few errors with your code:
Don't call your class Frame, it may confuse you or others about java.awt.Frame, something that may work would be MyFrame
Right now all your class is inside the main method and it's not placed inside the Event Dispatch Thread (EDT), to fix this, create an instance of your class and call a method createAndShowGUI (or whatever you want to name it) inside SwingUtilities.invokeLater()
For Example:
public static void main(String args[]) {
SwingUtilities.invokeLater(new MyFrame()::createAndShowGUI)
}
Or if using Java 7 or lower, use the code inside this answer in point #2.
setVisible(true) should be the last line in your code, otherwise you may find some visual glitches that may be resolved until you move your mouse above your window or something that triggers the call to repaint() of your components.
Instead of calling setSize(...) directly, you should override getPreferredSize(...) of your JPanel and then call pack() on your JFrame, see this question and the answers in it: Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?
You're adding 2 components to the CENTER of BorderLayout, which is a JFrame's default layout manager, there are other layout managers and you can combine them to make complex GUI's.
setBounds(...) might mean that you're using null-layout, which might seem like the easiest way to create complex layouts, however you will find yourself in situations like this one if you take that approach, it's better to let Swing do the calculations for you while you use layout managers. For more, read: Why is it frowned upon to use a null layout in Swing?
With all the above tips now in mind, you may have a code similar to this one:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class MyFrame {
private JFrame frame;
private JPanel pane;
private JTextField field;
private JButton button;
public static void main(String[] args) {
SwingUtilities.invokeLater(new MyFrame()::createAndShowGUI);
}
private void createAndShowGUI() {
frame = new JFrame("Alkalmazás");
pane = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(100, 100);
}
};
pane.setLayout(new BoxLayout(pane, BoxLayout.PAGE_AXIS));
field = new JTextField(10);
button = new JButton("Click me");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
field.setText("something");
}
});
pane.add(field);
pane.add(button);
frame.add(pane);
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Now you have an output similar to this one:
What about you want the JTextField to have a more "normal" size? Like this one:
You'll have to embed field inside another JPanel (with FlowLayout (the default layout manager of JPanel)), and then add that second JPanel to pane, I'm not writing the code for that as I'm leaving that as an exercise to you so you learn how to use multiple layout managers

exit button java

I am building a Java GUI on IntelliJ and making an 'exit' button - currently using
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
public class gui extends JFrame {
private JPanel mainPanel;
private JButton exitButton;
public gui(String title) {
super(title);
exitButton = new JButton("Exit");
exitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setContentPane(mainPanel);
this.pack();
}
public static void main(String[] args) {
JFrame frame = new gui("Emro GUI");
frame.setVisible(true);
}
}
The code runs, and I followed an exact tutorial on youtube, but the exit button isn't function how it should and I am unsure why. Should I have the exit button in a new class or function?
Adding the following three lines in appropriate locations will make it work.
import javax.swing.*;
mainPanel = new JPanel();
mainPanel.add(exitButton);
However:
Swing should always be used from the AWT Event Dispatch Thread (EDT) (use java.awt.EventQueue.invokeLater.
No need to extend JFrame.
No need for mainPanel and exitButton to be fields instead of locals.
Use a lambda expression for the ActionListener.
Have you tried this inside your action listeners method:
WindowEvent closeWindowEvent = new WindowEvent(frame, WindowEvent.WINDOW_CLOSING); frame.dispatchEvent(closeWindowEvent);

Java : using graphics component within an action listener

I've made a JFrame with Diferent JButtons and i'd like to get an image from another class. Any ideas? Or how draw on the same class but on the action performed?
Because it doesnt let me to do any drawings...my complier always gives me error messages
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.*;
public class red extends JFrame {
public JButton b;
public JButton b1;
public JButton b2;
public JButton b3;
public JButton b4;
public static Image p;
public static Graphics g;
public red() throws IOException {
gui1 x = new gui1();
setTitle(" ");
setSize(1200,700);
setLayout(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
b= new JButton("click");
b1= new JButton();
b.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e0){
b1.setBounds(0, 0, 200, 200);
b.show(false);
add(x);
}
});
b.setBounds(0, 0, 100, 100);
add(b1);
add(b);
setVisible(true);
}
public static void main(String[] args) throws IOException {
red k = new red();
}
}
import java.awt.*;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class gui1 extends Canvas {
public static Image p;
public void paint(Graphics g){
g.drawImage(p, 700, 200, 100, 100, this);
}
{
try {
p= ImageIO.read(new File("Lighthouse.jpg"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Phew! I see A LOT of errors in your code (even after I corrected the compilation errors):
You're not following the Java naming conventions:
Class names should be nouns, in mixed case with the first letter of each internal word capitalized
while red is a noun it should be more descriptive and be capitalized. The same goes for gui1
You're extending JFrame which in plain english would say: red is a JFrame, you should really avoid this and create your GUI based on JPanels instead... see Java Swing using extends JFrame vs callint it inside of class
You're setting size (a REAAAAAAALLY big one window for the JButton sizes you're using), instead use pack()
You're using null-layout, while pixel-perfect GUIs might seem like the easiest way to create complex GUIs for Swing newbies, the more you use them the more problems related to this you'll find in the future, they are hard to maintain and cause random problems, they don't resize, etc. Please read Null layout is evil and Why is it frowned upon to use a null layout in Swing? for more information about why you should avoid its use and why you should change your GUI to work with Layout Managers along with Empty Borders for extra spacing between components.
You're making use of a deprecated method JFrame#show() you should be using JFrame#setVisible(...) instead.
Related to point #4, you shouldn't be calling setBounds(...) method, but let that calculations to the layout managers.
You're not placing your program on the Event Dispatch Thread (EDT), Swing is not thread safe, you can fix this by changing your main() method as follows:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
//Your constructor here
}
});
}
You're mixing AWT and Swing components, instead of using AWT's Canvas use Swing's JPanel which has more functionality and support.
Images will become embedded resources once they're packaged in a JAR file, so it's wise to start treating them as if they already were, not as external files as shown in the embedded-resource tag.
Once you change from Canvas to JPanel you should override its paintComponent(...) method and not paint(...) and call it's super.paintComponent(g) method as the first line, also don't forget to add the #Overrides annotation. See the tutorial on Swing custom painting.
You're abusing the use of static keyword, see how does the static keyword works?
After seeing all the above errors I recommend you to go back and Learn the basics of the language before starting with a graphical environment which will only add more difficulty to your learning.
From what I understand you want to draw an image on a button click, if that's the case then you can wrap your image in a JLabel and add that JLabel to a JPanel which then is added to a parent JPanel which is later added to the JFrame:
As you can see in the GIF above, the icon is displayed after user presses the button.
Obviously this can be improved for the GUI to be more "attractive" with combinations of layout managers and empty borders as stated before.
This was done with the following code:
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ImageDrawingFromOneClassToAnother {
private JFrame frame;
private JPanel pane;
private JPanel leftPane;
private JPanel rightPane;
private ImageIcon icon;
private JButton button;
private JLabel label;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new ImageDrawingFromOneClassToAnother().createAndShowGui();
}
});
}
public void createAndShowGui() {
frame = new JFrame(getClass().getSimpleName());
icon = new ImageIcon(this.getClass().getResource("king.png")); //Read images as if they were already embedded resources
button = new JButton("Draw image");
label = new JLabel(""); //Create an empty label
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
label.setIcon(icon); //On button click, we set the icon for the empty label
}
});
pane = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 200); //Set a size for the main panel
}
};
pane.setLayout(new GridLayout(1, 2)); //The main panel
leftPane = new JPanel(); //The button panel
leftPane.setLayout(new BoxLayout(leftPane, BoxLayout.PAGE_AXIS));
leftPane.add(button);
rightPane = new JPanel(); //The panel where the image will be drawn
rightPane.add(label);
//We add both (button and image) panels to the main panel
pane.add(leftPane);
pane.add(rightPane);
frame.add(pane); //Add the main panel to the frame
frame.pack(); //Calculate its preferred size
frame.setVisible(true); //Set it to be visible
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

setVisible() for cardPanel is not working

I want to make it so the cardPanels are not visible until an action that is not on the cardPanel is completed. For instance, a window opens up when you select a certain Jradiobutton on that window. I want to use setVisible(boolean) to to do this. However, setVisible is not working for some reason. Is there something i'm missing?
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class MainFrame extends JFrame {
private JFrame frame = new JFrame("Swing Refresh Bug?");
private Container contentPane = frame.getContentPane();
private JPanel cardPanel = new JPanel();
private CardLayout cardLayout = new CardLayout();
private Component currentComponent;
private JButton next;
MainFrame() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// properties of the cardPanel
cardPanel.setLayout(cardLayout);
cardPanel.add(new JLabel("One"), "One");
cardPanel.add(new JLabel("Two"), "Two");
cardPanel.add(new JLabel("Three"), "Three");
cardPanel.setVisible(false);
// Create a radio button
JRadioButton addNext = new JRadioButton("Add next");
// Add the radio buttons listener
addNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cardLayout.show(cardPanel, "One");
}
});
// Set the layout of the content pane.
contentPane.setLayout(new BorderLayout());
contentPane.add(cardPanel, BorderLayout.CENTER);
contentPane.add(addNext, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
public MainFrame(String title) {
MainFrame mf = new MainFrame();
}
}
Your class need not extend JFrame, you have already created JFrame in the class, if you want to move accross the cards then change ActionListener as follows
addNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cardLayout.next(cardPanel);
}
});
You set your cardPanel not visible by setVisible(false) but you never set it to true after, so your cardPanel (containing your cardLayout) is never shown !
If you want your cardLayout to appear when pressing the radiobutton, you just have to add the setVisible(true) in the listener.
You can also use the isSelected() method from JRadioButton to check if it is clicked or not. For example :
addNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(addNext.isSelected()){
cardPanel.setVisible(true);
cardLayout.show(cardPanel, "One");
}
else{
cardPanel.setVisible(false);
//or : cardLayout.show(cardPanel, "Two");
}
}
});
If you want a JFrame to be opened this way, just creat it before, setting it not visible. Then, you set it visible in the listener.
I hope it helped :)
Initialize it in the ActionListener not in the constructor. You must also say setVisible(true) after that. I think you can make CardPannel class which extends JPannel. There is more point of doing it like that. Instead of adding JLabels in the MainFrame constructor do it in the CardPannel constructor. I am on my phone so I can't show you code right now. I hope I helped.

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