Refer to the class inside of a JPanel action listner - java

I'm trying to refer to my class in a method within a action listener so I can pass it though the method. My code looks a little something like this:
My MainPanel Class:
public class MainPanel extends JPanel{
private JButton submitButton;
JTextArea consoleOutput;
public MainPanel(){
Border border = BorderFactory.createLineBorder(Color.LIGHT_GRAY);
setLayout(null);
setBackground(Color.WHITE);
Font f1 = new Font("Arial", Font.PLAIN, 14);
submitButton = new JButton("Get Cards");
submitButton.setBounds(35, 285, 107, 49);
submitButton.setFont(f1);
consoleOutput = new JTextArea();
consoleOutput.setBounds(199, 122, 375 , 210);
consoleOutput.setBorder(BorderFactory.createCompoundBorder(border, BorderFactory.createEmptyBorder(3, 4, 0, 0)));
consoleOutput.setEditable(false);
consoleOutput.setFont(f1);
submitButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String username;
String password;
Cards cards = new Cards();
cards.openTabs(username, password, this); //THIS IS THE METHOD IM TRYING TO PASS THE CLASS INTO
}
});
add(submitButton);
add(consoleOutput);
}
}
My Cards Class:
public class Cards{
public void openTabs(String username, String password, MainPanel panel){
panel.consoleOutput.setText(username + ", " + password);
}
In eclipse it underlines the method in my MainPanel and this is the problem or error is has:
The method openTabs(String, String, MainPanel) in the type Cards is not applicable for the arguments (String, String, new ActionListener(){})
What should I do? What should I pass in instead of this because it seems not not be working. I'm lost and have no idea what to do, Any help is appreciated!!

Your problem is that you are using this within an anonymous inner class. In other words: this this has not the usual meaning of this - it doesn't refer the "outer" MainPanel object, but the inner ActionListener object!
You have to use MainPanel.this instead!

Related

.getText(); not working for textField variable that is declared in another class

In trying to read the text that is entered into a textField, I used the actionlistener for a button right next to it. In this actionlistener class, I had an action performed method in which I created a string that was set equal to the textField.getText();. This class however has a problem recognizing textField variable from the previous class.
It is necessary for the .getText() or reading of the textField entry to be in the actionlistener class. I do not know what to try besides the code that I have listed down below.
public class MainClass {
public static void main(String args[]) {
JFrame frame = new JFrame ("Welcome");
frame.setVisible(true);
frame.setSize(500, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
JLabel label = new JLabel("...");
panel.add(label);
JTextField text = new JTextField(20);
panel.add(text);
JButton SubmitButton = new JButton("Analyze");
panel.add(SubmitButton);
SubmitButton.addActionListener(new Action1());
}
static class Action1 implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
JFrame frame1 = new JFrame("Word Commonality");
frame1.setVisible(true);
frame1.setSize(500,200);
String ReceivedPath = text.getText();
System.out.println(ReceivedPath);
Error is present at second to bottom line of code. The error is "text cannot be resolved"
I expect that the text can be read and printed out in the console.
Your problem is revolved around function scoping to fix it you need a direct access to the JTextField object you can do so by instantiating a new action performed straight in the MainClass like this:
public class Main {
public static void main(String args[]) {
new MainClass();
}
}
Here I created a class only used to instantiate the window class
For the main class I suggest extending JFrame so you can inherit all of it methods.
//Imports
public class MainClass extends JFrame {
private JPanel panel;
private JLabel label;
private JTextField text;
private JButton SubmitButton;
public MainClass(){
super("Welcome");
setSize(500, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
add(panel);
label = new JLabel("...");
panel.add(label);
text = new JTextField(20);
panel.add(text);
SubmitButton = new JButton("Analyze");
panel.add(SubmitButton);
SubmitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String ReceivedPath = text.getText();
System.out.println(ReceivedPath);
}
});
setVisible(true);
}
}
This is how your class should look like.
Side notes:
Set visible is at the end otherwise the items will not be see able.
The MainClass is inheriting from JFrame so it can use all its methods without instatiating it look at inheritance(https://www.w3schools.com/java/java_inheritance.asp)
The action performed now can acces the text JTextField because it is a class attribute.
If the solution is correct please think of marking this answer as final. Thank you
If you place the getText() outside the ActionListener, it will be read immediately after creating the panel. That is why it is empty. You can make the ActionListener assign a value to a variable, but it will be empty until the action is performed.
Also see here: Swing GUI doesn't wait for user input

Java popup sending multiple action

The first popup would only send one action, the second would send two, third will be three so and so forth. I was able to narrow it down to it being the button sending action multiple time.
At first, I was using jframe for all my window, so I tried using jdialog, the problem persists. tried making it so that when the user clicks on the button the window is disposed, still don't fix it.
public class BoothDetails extends JDialog implements ActionListener{
FloorPlanGUI floorPlan = new FloorPlanGUI();
static JLabel bname = new JLabel();
JTextArea details = new JTextArea();
static JButton addsche = new JButton("ADD TO SCHEDULE");
JPanel northPanel = new JPanel();
public BoothDetails(String name, String detail) {
setVisible(true);
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
bname.setText(name);
details.setText(detail);
setLayout(new BorderLayout());
northPanel.setLayout(new FlowLayout(0, 10, 10));
northPanel.add(bname);
northPanel.add(addsche);
addsche.addActionListener(floorPlan);
addsche.addActionListener(this);
add(northPanel, BorderLayout.NORTH);
add(details, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent a) {
dispose();
}
}
static JLabel bname = new JLabel();
JTextArea details = new JTextArea();
static JButton addsche = new JButton("ADD TO SCHEDULE");
Don't use the static keyword. This means the variable is shared by all instances of the class.
So every time you create a new instance of the class you execute the following code:
addsche.addActionListener(floorPlan);
which adds another ActionListener to the button.
The static keyword is should generally only be used when you create constant variables in your class, it should NOT be used for components which need to be unique for each class.

Getting answer from action listener

I'm creating a user name confirm box, and I need to confirm if the text typed into the text field matches with the already defined type in a variable name.
I don't know how to get it. I had been trying by implementing the following code, which in the action performed once the button is pressed it will verify if the textfield matches with the variable name.
code is as follows.
public class Action extends JFrame implements ActionListener
{
JLabel l;
JTextField t;
JButton b;
final String name = "harry";
public Action()
{
l = new JLabel("Name");
l.setBounds(10, 10, 100, 33);
t = new JTextField();
t.setBounds(60, 10, 100, 30);
b = new JButton("send text");
b.setBounds(80, 120, 100, 40);
add(l);
add(t);
add(b);
setSize(300, 300);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e)
{
if (t.getText() == name)
{
JOptionPane.showMessageDialog(this, "you mach");
}
else
{
JOptionPane.showMessageDialog(this, "you dont");
}
}
public static void main(String[] args)
{
new Action();
}
}
In your Action() constructor, you have to add an actionlistener to the frame:
addActionListener(this);
in order for it to work;
Also, you compare strings by .equals() because strings are objects. Stack does not store the string's value, the heap does. To compare the string's value, you have to call t.getText().equals(name)
Change that in your actionPerformed() class and you are good to go!

how to include diferrent swing items to main class from another class

I am quite new to java. I have created a GUI window with some jlabel , jtextfield. But recently for a project I need to create another class with those jlabel and jtextfield and need to display them to main class. But I dont know how to do that. I have seen this tutorial , but it has covered only with jmenu (not jtext field and jlabel) .
Adding Swing components from another class
my code is below,
public class common_items extends JFrame {
public void item_gui(String labelForMatrix) {
JPanel contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
JLabel lbl = new JLabel(labelForMatrix);
lbl.setBounds(5, 5, 424, 14);
lbl.setHorizontalAlignment(SwingConstants.CENTER);
contentPane.add(lbl);
JTextField txt2 = new JTextField();
txt2.setBounds(178, 117, 86, 20);
contentPane.add(txt2);
txt2.setColumns(10);
JTextField txt1 = new JTextField();
txt1.setColumns(10);
txt1.setBounds(178, 64, 86, 20);
contentPane.add(txt1);
JLabel lblRowNumber = new JLabel("Row number");
lblRowNumber.setBounds(189, 39, 67, 14);
contentPane.add(lblRowNumber);
JLabel lblColumnNumber = new JLabel("column number");
lblColumnNumber.setBounds(155, 95, 119, 14);
contentPane.add(lblColumnNumber);
}
}
I have tried to display them to main class but it fails . my main class code is below
common_items itm=new common_items();
itm.item_gui();
Plzz suggest me what should I do .
If I understood correctly what you are trying to do, you are trying to make a main JFrame class that includes components from other classes like the JLabel or the JTextArea that connect to the class and use them as normal components.
So what you need to do is just create a main class (not the JFrame) and make a JFrame class (call it mainFrame for example) and then just create the components class (e.g textArea JLabel ...) and then you just represent these classes as variables in the frame class (which we will be executing from the main class).
and maybe you just understand code better than speech:
Main class to start the program (load the frame class which contains everything)
public class Main {
public Main(){
//execute the frame
new Frame();
}
public static void main(String[] args) {
new Main(); //execute the function that launches the JFrame
}
}
Frame class which (obviously) contains the frame
import javax.swing.JFrame;
public class Frame extends JFrame{
private static final long serialVersionUID = -5151041547543472432L; //ignore this it is just the serial id of the JFrame you can omit this line from your code
ComponentsStorage cs = new ComponentsStorage(); //display class as variable so we can use it more efficnent
public Frame(){
launch(); //execute function
}
public void launch() { //launch
setTitle("Frame Demo");//title
setSize(640, 480);//size (width * height)
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//close when close button is pressed
//you can just do ComponentStorage.tf.blah blah blah... but it is much easier as a variable
cs.label.setSize(500, 500); // you can mess up witht the components you stored there
cs.tf.setSize(40, 5); //as you can see here I am just adding the components by
//add them here
add(cs.label);
add(cs.tf);
setLocationRelativeTo(null);//by setting this you place the screen always in the middle of the screen
setVisible(true);//there is no point of creating JFrames if they aren't visible
}
}
And just another class that stores the components (JLabel, JTextField...) that you want to use (it can be any class that just contains these things even if there are other functions in it I named it ComponentStorage)
import javax.swing.JTextField;
import javax.swing.JLabel;
public class ComponentsStorage {
JLabel label = new JLabel();
JTextField tf = new JTextField();
}

Listener doesn't work

I'm writing a Java programm, according to MVC model.
So the problem is that the Frame doesn't react to button click.
(The text, that I write isn't added to the TextArea after click)
At first I call constructors for View and Controller
MessageFrame mf = new MessageFrame(con);
MessageFrameListener mfl = new MessageFrameListener(mf);
Here is the part of MessageFrameListener class (controller)
public class MessageFrameListener{
private MessageFrame mf;
public MessageFrameListener(MessageFrame m_f){
mf = m_f;
m_f.addButtonListener(new SButtonListener());
}
//#Override
public class SButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String insert = mf.getInput();
mf.addLine(insert);
mf.refreshInput();
}
}
}
Here is the part from MessageFrame class (View)
public class MessageFrame{
public JTextField messField;
public JTextArea dialogArea;
public JButton sendButton;
public JFrame frame;
public Contact con;
public MessageFrame (Contact con_get) {
con = con_get;
frame = new JFrame();
frame.setSize(538, 299);
JPanel panel_1 = new JPanel();
frame.getContentPane().add(panel_1, BorderLayout.NORTH);
JPanel panel_2 = new JPanel();
frame.getContentPane().add(panel_2, BorderLayout.SOUTH);
panel_2.setLayout(new BoxLayout(panel_2, BoxLayout.X_AXIS));
messField = new JTextField();
panel_2.add(messField);
messField.setColumns(10);
JButton sendButton = new JButton("Send");
panel_2.add(sendButton);
JPanel panel_3 = new JPanel();
frame.getContentPane().add(panel_3, BorderLayout.EAST);
JPanel panel_4 = new JPanel();
frame.getContentPane().add(panel_4, BorderLayout.CENTER);
panel_4.setLayout(new BorderLayout(0, 0));
JTextArea dialogArea = new JTextArea();
panel_4.add(dialogArea);
frame.setVisible(true);
}
public String getInput(){
return messField.getText();
}
public void refreshInput(){
messField.setText("");
}
public void addLine(String line){
dialogArea.append(line);
}
public void addButtonListener(ActionListener bal){
sendButton.addActionListener(bal);
}
}
You will definately find the answer if you check the output of your program or debug it.
Exception in thread "main" java.lang.NullPointerException
at test3.MessageFrame.addButtonListener(Main.java:93)
at test3.MessageFrameListener.<init>(Main.java:28)
at test3.Main.main(Main.java:18)
Your are hiding the reference to the JButton sendButton by declaring it again in the constructor so the field is never initialised.
JButton sendButton = new JButton("Send");
panel_2.add(sendButton);
Since you've posted code scraps and have not posted a functioning SSCCE that we can test, all we can do is guess -- so you'll get what you paid for, and here goes my guess:
You're listening on the wrong MessageFrame. Your program has 2 or more MessageFrame objects, one of which is displayed, and the other which is being listened to, and so your displayed MessageFrame will of never trip the listener.
If this doesn't help, and you need better help, then please provide us with a better question, and an sscce.
You are adding an empty string:
String insert = mf.getInput(); //all it does is: messField.getText();
mf.addLine(insert); //adding the empty string
mf.refreshInput(); //all it does is: messField.setText("");

Categories