The Question
Create a new project in Eclipse
• Create a JFrame application that contains ONE JButton with the label “List All Locales” and ONE JTextArea. Output ALL available Locales to the JTextArea when the JButton is pushed.
So I have the code working where it has the JButton but I can't seem to get it printing out all the Locales in the JTextArea when the button is pressed. Is there something I'm missing
My Code:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import java.util.Locale;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
/**
*
*/
/**
* #author Michelle
*
*/
public class Exercise1 extends JFrame implements ActionListener{
JButton button;
JFrame frame;
JTextArea ta;
private static final long serialVersionUID = 1L;
Locale[] available = Calendar.getAvailableLocales();
public Exercise1(){
Container c = getContentPane();
JPanel p = new JPanel();
ta = new JTextArea(20,22);
ta.setText("All Locales will display here");
ta.setEditable(false);
button = new JButton();
button.setText("List all Locales");
JScrollPane output = new JScrollPane(ta);
button.addActionListener(this);
p.add(button, BorderLayout.SOUTH);
p.add(output);
c.add(p);
setSize(300,300);
setVisible(true);
}
public void actionPerformed(ActionEvent a) {
// TO DO Auto-generated method stub
if (a.getActionCommand().equals("List All Locales")){
for(int i=0; i<available.length;i++){
ta.append(available[i].getDisplayName()+"\n");
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Exercise1 myLocaleTest = new Exercise1();
myLocaleTest.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
The text on the button says "List all Locales"
button.setText("List all Locales");
In actionPerformed, you're checking if the action command is "List All Locales"
if (a.getActionCommand().equals("List All Locales")){
Do you see the difference between "List all Locales" and "List All Locales"?
To avoid this kind of mistake, you could create a constant in your class, and use that. For example:
public class Exercise1 extends JFrame implements ActionListener{
private static final String BUTTON_ACTION = "List all Locales";
public Exercise1(){
// ...
button.setText(BUTTON_ACTION);
// ...
}
public void actionPerformed(ActionEvent a) {
if (a.getActionCommand().equals(BUTTON_ACTION)){
// ...
Change to equalsIgnoreCase instead...
if (a.getActionCommand().equalsIgnoreCase("List all locales")){
Misspelling here if (a.getActionCommand().equals("List All Locales")). Button have next command "List all Locales". Change that and all will be work.
Others have already pointed out that your string check has an upper/lower case typo in it.
The suggestion to use a static final is good, but NOT for the button label! Why? Zero language support!
I did a quick search online and found the method: setActionCommand(String);
private static final String ACTION_COMMAND = "ac1";
...
JButton jbutton = new JButton();
jbutton.setText("My label text");
jbutton.setActionCommand(ACTION_COMMAND);
...
if ( action.getActionCommand().equals(ACTION_COMMAND) )
The static final should be used for setting the action command and for testing for the action, but not the label!
Related
I want to be able to call the Introduction.Intro() method into my main file code, but it tells me I am unable to call a non-static method intro from a static context. Since I am still fairly new to coding I'm not entirely sure what the problem is. I've added my codes down below. I've tried countless online methods but sadly none have seemed to work.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Start extends JFrame implements ActionListener
{
private JFrame Main;
private JPanel PanelA, PanelB, PanelC;
private JLabel Text, ImageL;
private JButton Button;
private ImageIcon Image;
public Start ()
{
//Button
Button = new JButton("Start");
Button.addActionListener(new ButtonListener());
//Text
Text = new JLabel("Welcome To The Game"); //ADD NAME OF THE GAME
//Image
Image = new ImageIcon(getClass().getResource("download.jfif")); //ADD THE IMAGE FOR WELCOME
ImageL = new JLabel(Image);
//Top Panel (PanelA) - Image
PanelA = new JPanel();
PanelA.setBorder(BorderFactory.createEmptyBorder(0,200,150,200));
PanelA.setLayout(new FlowLayout(FlowLayout.CENTER));
PanelA.add(ImageL);
//Middle Panel (PanelB) - Text
PanelB = new JPanel();
PanelB.setBorder(BorderFactory.createEmptyBorder(50,200,10,200));
PanelB.setLayout(new FlowLayout(FlowLayout.CENTER));
PanelB.add(Text);
//Bottom Panel (PanelC) - Buttons
PanelC = new JPanel();
PanelC.setBorder(BorderFactory.createEmptyBorder(0,200,20,200));
PanelC.setLayout(new FlowLayout(FlowLayout.CENTER));
PanelC.add(Button);
//Main Frame
Main = new JFrame ();
Main.add(PanelA, BorderLayout.NORTH);
Main.add(PanelB, BorderLayout.CENTER);
Main.add(PanelC, BorderLayout.SOUTH);
Main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Main.setTitle("GAME TITLE"); //ADD THIS LATER
Main.pack();
Main.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent ae)
{
}
public class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == Button)
{
Introduction.Intro1(); //THESE LINE RIGHT HERE
return null; //THESE LINE RIGHT HERE
}
}
}
public static void main(String[] args)
{
new Start();
}
}
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Introduction
{
private JFrame Main;
private JPanel PanelD;
private JLabel Text, ImageL;
private JButton Button;
private ImageIcon Image;
public void Intro()
{
Image = new ImageIcon(getClass().getResource("guy.jfif"));
ImageL = new JLabel(Image);
PanelD = new JPanel();
PanelD.setBorder(BorderFactory.createEmptyBorder(0,100,10,100));
PanelD.setLayout(new FlowLayout(FlowLayout.CENTER));
PanelD.add(ImageL);
PanelD.setVisible(true);
Main.add(PanelD, BorderLayout.NORTH);
}
}
EDIT: So I made another method in the Introduction class where I added this line of code, it managed to fix the error, however, the panel isn't being saved and my JFrame is outputting blank.
public static JFrame Intro1()
{
Introduction M = new Introduction();
return M;
}
If you are looking to initialize the Introduction class in main method of Start class, You can add belo code in main method after Start()
Introduction M = new Introduction();
You main method becomes :
public static void main(String[] args)
{
new Start();
Introduction M = new Introduction();
m.Intro
}
Looking at this set of code, It looks like there is incompatible issue, as you have declare JFrame as return type, while you are returning instance of Introduction.
public static JFrame Intro1()
{
Introduction M = new Introduction();
return M;
}
My question is about an error message I don't understand. Well.. I do understand what it says, but not why it says so or how to fix it. I just started the learning chapter about Swing, and this is one of the examples in my course. I copy/pasted every word into Netbeans but for some reason, it doesn't work.
I have a class called MijnVenster (meaning "MyWindow"), where a JPanel is created with some JButtons with an ActionListener. In the class, there are 2 inner classes describing the performed action.
There's an error message next to both class headers,, saying:
MijnVenster.HoofdLetterListener is not abstract and does not override abstract method actionPerformed (ActionEvent in ActionList)
The other error message next to both #Override statements says:
method does not override or implement a method from a supertype
Isn't that exactly what I did?
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import javafx.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
class MijnVenster extends JFrame {
private static final long serialVersionUID = 1L;
private final static String ZIN = "Hier staat een zin";
private final JTextField textField = new JTextField(ZIN);
public MijnVenster() {
super("Letters");
add(textField);
JPanel panelSouth = new JPanel(new FlowLayout(FlowLayout.LEFT));
JButton buttonHoofdLetters = new JButton("Hoofdletters");
panelSouth.add(buttonHoofdLetters);
JButton buttonKleineLetters = new JButton("Kleine letters");
panelSouth.add(buttonKleineLetters);
add(panelSouth, BorderLayout.SOUTH);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buttonHoofdLetters.addActionListener(new HoofdLetterListener());
buttonKleineLetters.addActionListener(new KleineLettersListener());
}
// an inner class for upper case
private class HoofdLetterListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
textField.setText(ZIN.toUpperCase());
}
}
// an inner class for lower case
private class KleineLettersListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
textField.setText(ZIN.toLowerCase());
}
}
}
I am coding on Android and using terminal IDE to compile my code. However, for some reason when I compile, it says the Button code is wrong.
package BlahBlahBlah;
import javax.swing.JButton;
import javax.swing.JFrame;
public class blahblahblah extends JFrame{
JFrame w = new JFrame();
w.setVisible(true);
w.setSize(1366, 768);
Button sb = new JButton();
sb.addListener(this);
add(sb);
}
It keeps saying illegal start of type or identifier expected which as you see there's a identifier in the Button.
Button sb = new JButton();
A "Button" without the "J" is not the same as a "JButton".
In Swing components start with a "J".
You should put your code inside a method.
public class blahblahblah extends JFrame{
public static void main(String[] args) {
JFrame w = new JFrame();
w.setVisible(true);
w.setSize(1366, 768);
Button sb = new JButton();
sb.addListener(this);
add(sb);
}
}
You can either remove sb.addListener(this); or implement our class with ActionListener and add it's umimplemented methods to your class. Also, do some changes like:
import java.awt.Button;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class blahblahblah extends JFrame implements ActionListener
{
public blahblahblah()
{
JFrame w = new JFrame();
w.setVisible(true);
w.setSize(1366, 768);
JButton sb = new JButton();
sb.addActionListener(this);
add(sb);
}
public static void main(String[] args) {
blahblahblah b = new blahblahblah();
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Your Stuff
}
}
I am learning JRadioButtons and I do not know why it is working in the tutorial I am watching and not in my code. Could someone please take a look at it?
Main Class:
import java.awt.*;
import javax.swing.*;
public class Calculator extends JPanel{
private static final long serialVersionUID = 1L;
public static void main(String[] args){
Screen screen = new Screen();
screen.setVisible(true);
}
}
Here is the Screen Class:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
public class Screen extends JFrame implements ActionListener{
private static final long serialVersionUID = 1L;
JRadioButton b1, b2;
ButtonGroup group;
JTextArea tb;
public Screen(){
super("First GUI");
setSize(600,600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JPanel p1 = new JPanel();
JTextArea tb = new JTextArea("Text Area");
group = new ButtonGroup();
group.add(b1);
group.add(b2);
b1 = new JRadioButton("Hello");
b1.setActionCommand("HELLO!");
b1.addActionListener(this);
b2 = new JRadioButton("Goodbye");
b2.setActionCommand("Goodbye! =)");
b2.addActionListener(this);
p1.add(b1);
p1.add(b2);
p1.add(tb);
add(p1);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
tb.setText(e.getActionCommand());
}
}
In my new Java head this should work perfectly. I initialize the buttons, initialize the group. I am getting an error after I click one of the buttons: AWT-EventQueue-0. I do not know what that means so I do not know how to fix this issue.
You have declared twice the same variable. If you declare the same variable (JTextArea tb) in the global and local scope, it will be a separate object. Remove the declaration in the local scope from the Screen() constructor so it will work.
Try this
tb = new JTextArea("Text Area");
instead of
JTextArea tb = new JTextArea("Text Area");
Because of your current code, tb is still not initialized in the global scope.
I am learning the basics of Java and decided to practice working on objects, by making a simple program which I called a 'PlayerAction Counter'. It does nothing more that counting an 'action' which is fired by clicking '+1' button and additionally reset the counter, when the 'Reset' button is clicked. For this case I've made a Application.java which holds the main method and launches the program, Interface.java for GUI, EventHandling.java for events and Person.java which holds interface components and methods to change their state. It looks like this:
My idea was to create the window in Interface class and set it's layout, then create two Person objects called PlayerOne and Player Two. The Person class creates two labels and two buttons and set a label of one by a constructor parameter.
I've managed to add these two objects' elements to the GUI by getters and it looks just fine. I added ActionListener to both buttons in Person class and it also works just fine.
I am stuck on getting back to Person fields and methods from EventHandling class. I've created a setValueLabel() which increases by one a value of 'action' and sets it on the label, but I have to idea how to launch the method from another class. I can not make another object inside (throws StackOverFlow error), but should it not somehow refer to those two made in Interface class?
Here is the code:
Application.java
import java.awt.EventQueue;
public class Application {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new Interface().setVisible(true);
}
});
}
}
Interface.java
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.SwingConstants;
public class Interface extends JFrame {
private JLabel titleLabel;
private JPanel mainPanel;
private JPanel leftPanel, rightPanel;
private JSeparator separator;
Person PlayerOne = new Person("PlayerOne");
Person PlayerTwo = new Person("PlayerTwo");
public Interface() {
//Basic init
setTitle("PlayerAction Counter");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
//Layout
mainPanel = new JPanel();
add(mainPanel);
mainPanel.setLayout(new BorderLayout());
mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
leftPanel = new JPanel();
rightPanel = new JPanel();
leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));
leftPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
mainPanel.add(leftPanel, BorderLayout.WEST);
separator = new JSeparator(SwingConstants.VERTICAL);
mainPanel.add(separator, BorderLayout.CENTER);
titleLabel = new JLabel("PlayerAction Counter");
mainPanel.add(titleLabel, BorderLayout.PAGE_START);
//Components init
PlayerTwo.getPersonLabel().setAlignmentX(Component.CENTER_ALIGNMENT);
leftPanel.add(PlayerTwo.getPersonLabel());
PlayerTwo.getValueLabel().setAlignmentX(Component.CENTER_ALIGNMENT);
leftPanel.add(PlayerTwo.getValueLabel());
PlayerTwo.getValueUpButton().setAlignmentX(Component.CENTER_ALIGNMENT);
leftPanel.add(PlayerTwo.getValueUpButton());
PlayerTwo.getValueResetButton().setAlignmentX(Component.CENTER_ALIGNMENT);
leftPanel.add(PlayerTwo.getValueResetButton());
rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
rightPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
mainPanel.add(rightPanel, BorderLayout.EAST);
PlayerOne.getPersonLabel().setAlignmentX(Component.CENTER_ALIGNMENT);
rightPanel.add(PlayerOne.getPersonLabel());
PlayerOne.getValueLabel().setAlignmentX(Component.CENTER_ALIGNMENT);
rightPanel.add(PlayerOne.getValueLabel());
PlayerOne.getValueUpButton().setAlignmentX(Component.CENTER_ALIGNMENT);
rightPanel.add(PlayerOne.getValueUpButton());
PlayerOne.getValueResetButton().setAlignmentX(Component.CENTER_ALIGNMENT);
rightPanel.add(PlayerOne.getValueResetButton());
pack();
}
}
Person.java
import java.awt.Component;
import javax.swing.JButton;
import javax.swing.JLabel;
public class Person {
private JLabel personLabel;
private JLabel valueLabel;
private JButton valueUpButton;
private JButton valueResetButton;
private int actionValue = 0;
public Person(String s) {
personLabel = new JLabel(s);
setComponents();
}
private void setComponents() {
valueUpButton = new JButton("+1");
valueResetButton = new JButton("Reset");
valueLabel = new JLabel(""+actionValue);
EventHandling eventHand = new EventHandling(valueUpButton, valueResetButton);
valueResetButton.addActionListener(eventHand);
valueUpButton.addActionListener(eventHand);
}
public void setValueLabel() {
actionValue++;
valueLabel.setText("" +actionValue);
}
public JLabel getPersonLabel() {
return personLabel;
}
public JLabel getValueLabel() {
return valueLabel;
}
public JButton getValueUpButton() {
return valueUpButton;
}
public JButton getValueResetButton() {
return valueResetButton;
}
}
EventHandling.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
public class EventHandling implements ActionListener {
private JButton valueUpButton;
private JButton valueResetButton;
public EventHandling(JButton valueUpButton, JButton valueResetButton) {
this.valueUpButton = valueUpButton;
this.valueResetButton = valueResetButton;
}
#Override
public void actionPerformed(ActionEvent event) {
if (event.getSource() == valueUpButton) {
//no idea how to launch Person.setValueLabel();
//creating new Person object throws StackOverFlow error and I doubt that's the way
}
else if (event.getSource() == valueResetButton) {
}
}
}
I do hope my issue is understandable. The question is: how should it be done?
Please keep in mind that I am a complete rookie and try to learn OOP, but am very confused by it. Please point my mistakes in thinking and the code.
Any feedback will be greatly appraciated.
Thank you.