Invoking one class from another - java

I am trying to learn java and surely I am not getting something.
For the sake of simplification let us assume I have two classes, class A and class B. I want to call class B from class A and when I do that I need that anywhere I right click (right button) inside class A to get the pop-up menu as defined in class B. The code is the following:
CLASS A code:
package test1;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class A {
JFrame frame;
Toolkit toolkit;
A () {
frame = new JFrame("A class");
setDimm(frame);
B b = new B();
frame.setVisible(true);
}
void setDimm(JFrame frame) {
this.frame=frame;
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(Color.gray);
frame.setSize(800, 600);
toolkit = frame.getToolkit();
Dimension size = toolkit.getScreenSize();
frame.setLocation((size.width-frame.getWidth())/2, (size.height-frame.getHeight())/2);
}
public static void main (String [] args) {
new A();
}
}
and CLASS B code is:
package test1;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
public class B extends JFrame {
JPopupMenu menu;
JMenuItem addRow, removeRow;
B(){
menu = new JPopupMenu();
addRow = new JMenuItem("Add row");
removeRow = new JMenuItem("Remove row");
// Adding two action listneres just to test the clicking on the items
addRow.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println("Add rows. Testing and it works");
}
});
removeRow.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.out.println("Remove rows. Testing and it works");
}
});
// end of action listeners
addMouseListener(new MouseAdapter(){
public void mouseReleased(MouseEvent e){
if (e.getButton() == e.BUTTON3) {
menu.show(e.getComponent(), e.getX(), e.getY());
}
}
});
menu.add(addRow);
menu.add(removeRow);
add(menu);
}
}
I added class B inside class A but it does not work.
I tried creating a JPanel and adding it to that, still nothing.
I tried creating a B instance with a JPanel or JFrame parameter and then inside class A invoking class B and putting a JPanel or JFrame from class A but still nothing.
I tried to create a main method inside class B and it works to create the right click but inside class B and that's not where I want it.
What am I doing wrong here?
Thanks and all the best!

Related

How can I access a JButton on another file or class in Java

I'm having a problem with JButton. I need to change the text on the goPauseButton when it has been clicked, but I get this error: goPauseButton cannot be resolved. I'm quite new to Java, so I started trying to solve the issue using techniques from other languages such as Free Pascal. There you need to refer to the class where the button is in, and then the button. In my code it would look like this:
PrisonersDilemma.goPauseButton.setText("Pause");
But then I get this error: Cannot make a static reference to the non-static field PrisonersDilemma.goPauseButton
This is my code (so far), I've erased unimportant things:
Main class
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingUtilities;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.util.Hashtable;
//...
public class PrisonersDilemma /* possible extends... */ {
// declaring
JFrame frame;
PlayingField field;
JPanel componentPanel;
public JButton goPauseButton;
public JPanel createComponentPanel() {
componentPanel = new JPanel();
componentPanel.setLayout(new GridLayout(2,6));
// set goPauseButton
goPauseButton = new JButton("GO!");
goPauseButton.addActionListener(field);
goPauseButton.setBounds(110,350, 80,20); // first coordinates, then size
frame.add(goPauseButton);
return componentPanel;
}
void buildGUI() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
field = new PlayingField();
// set frame
frame = new JFrame("Prisoners Dilemma");
frame.add(field);
createComponentPanel();
frame.add(field, BorderLayout.CENTER);
frame.setLocation(200, 200);
frame.pack();
frame.setVisible(true);
frame.setSize(400, 450);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
} );
}
Class with ActionEventHandler
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.JButton;
public class PlayingField extends JPanel
implements ActionListener,
ChangeListener {
private boolean started;
#Override
public void actionPerformed(ActionEvent e) {
// TODO
if ("GO!".equals(e.getActionCommand())){
System.out.println("GO!");
started = true;
goPauseButton.setText("Pause"); // here is the error
} else if ("Pause".equals(e.getActionCommand())){
System.out.println("Pause");
started = false;
} else if ("Reset".equals(e.getActionCommand())){
System.out.println("Reset");
}
}
}
I think you need to change the way you're approaching the problem. The PlayingField has no responsibility for modifying the state of the goPauseButton in PrisonersDilemma. Instead, PrisonersDilemma should update the goPauseButton and call an appropriate method of PlayingField
For example...
goPauseButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
goPauseButton.setText("Pause");
field.start();
}
});
And...
public class PlayingField extends JPanel {
public void start() {
System.out.println("GO!");
started = true;
}
public void pause() {
started = false;
System.out.println("Pause");
}
public void reset() {
System.out.println("Reset");
}
}

How to bind action with any gui interface in java

I am new to java.
Can someone tell me how to add ActionListener with my code?
Do I need to make a different function for it? I want to retrieve value from textfield which is entered by user. I am getting error.
Please explain me the background logic behind when to make function of methods that already exists in java or can we use them directly? My code is:
Also tell me how by pressing ENTER I can get value attached with text field in string?
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.*;
import javax.swing.JList;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Clientgui
{
public static void main(String[] args)
{
JFrame guiFrame=new JFrame();
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("Client GUI");
guiFrame.setSize(30,30);
guiFrame.setLocationRelativeTo(null);
final JPanel comboPanel = new JPanel();
JLabel Msg = new JLabel("Type Message");
JTextField textbox=new JTextField(10);
comboPanel.add(Msg);
comboPanel.add(textbox);
textbox.addActionListener(this);
String text = textbox.getText();
//textArea.append(text + newline);
//textbox.selectAll();
textbox.setText("Enter message here");
//final JPanel comboPanel1 = new JPanel();
//JLabel listLb2 = new JLabel("Connect");
//comboPanel.add(listLb2 );
JButton connect=new JButton("Connect");
guiFrame.add(comboPanel,BorderLayout.NORTH);
guiFrame.add(connect,BorderLayout.SOUTH);
guiFrame.setVisible(true);
}
}
You need an instance of something that implements ActionListener, you are getting a compilation error here -
textbox.addActionListener(this); // <-- no instance "this".
// You may have new Clientgui(), but
// Clientgui does not implement ActionListener.
As mentioned by Elliott Frisch You can add the Action to the instance of something that implements ActionListener which you can achieve in two way
textbox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Write your action here.
}
});
OR
public class Clientgui implements ActionListener{
// content of class goes here
textbox.addActionListener(this);
// content of class goes here
}
In order to bind the enter key with your text box you should implements KeyListener
textbo.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_ENTER)
{
System.out.println("ENTER key pressed");
}
}
});

accessing swing component of other class

I have two classes mainpanel.java and subpanel.java. The subpanel.class contains a checkbox and some labels. I want to change the setSelected() and setText() of these components when i click some buttons in the mainpanel.java .
I have created a method in subpanel.java which i call from mainpanel.java and pass the boolean values.
public void schedulerchange(boolean check){
System.out.println("checked"+check);
scheduleenabler.setEnabled(check);
scheduleenabler.setSelected(check);
scheduleinfo.setText("Scheduler in On");
//subpanel21.updateUI();
}
When i call this function from mainpanel.java the function is called but the values don't change unless i make jcheckbox and jlabel static. But from what i learned we should not use static components unless very necessary.
Is there some other way to change the components?
If I have understood your question then I think you want to write a separate ActionListener class and perform action there which will enable or disable the JCheckBox in the UI-class. The below code shows that. Pass your checkbox reference to that PerformAction class and make it enabled or disabled by clicking on the button.
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class MainClass {
MainClass() {
JFrame jfrm = new JFrame("JTable Demo");
jfrm.setLayout(new FlowLayout());
jfrm.setSize(460, 180);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JCheckBox check = null;
// Get the Panel from the subclass;
JPanel panel = new CheckBox().getCheckBoxPanel();
// From the compoenents present in the panel get the CheckBox compoenent.
for(int i = 0; i < panel.getComponentCount(); i++) {
if(panel.getComponent(i) instanceof JCheckBox) {
check = (JCheckBox) panel.getComponent(i);
}
}
JButton button = new JButton("Click");
// Pass the CheckBox Compoenent to the ActionListener.
button.addActionListener(new PerformAction(check));
jfrm.add(button);
jfrm.add(panel);
jfrm.setVisible(true);
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new MainClass();
}
});
}
}
class PerformAction implements ActionListener {
JCheckBox check = null;
public PerformAction(JCheckBox checkBox) {
check = checkBox;
}
#Override
public void actionPerformed(ActionEvent e) {
boolean checkStatus = check.isSelected();
if(checkStatus == true) {
check.setEnabled(false);
check.setSelected(false);
} else {
check.setEnabled(true);
check.setSelected(true);
}
}
}
class CheckBox {
public JPanel getCheckBoxPanel() {
JPanel checkPanel = new JPanel();
JCheckBox check = new JCheckBox();
checkPanel.add(new JLabel("CheckBox"));
checkPanel.add(check);
return checkPanel;
}
}
This is not an appropriate use of updateUI(), which "Resets the UI property to a value from the current look and feel." Using revalidate(), as suggested in a comment, would be helpful only if components are added to, or removed from, the enclosing Container. Instead, invoke repaint() directly on the sub-panel instance. For greater flexibility, use the observer pettern suggested here.
Addendum: This example use Action to encapsulate the button's behavior. Because the checkbox's selected state is a bound property, the component is repainted automatically, but you can invoke repaint() explicitly if needed.
Addendum: Update to pass a reference as a parameter.
Addendum: In this variation, the parameter is a reference to the exported Action.
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
/** #see https://stackoverflow.com/a/14412516/230513 */
public class Example {
private void display() {
JFrame f = new JFrame("Example");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new GridLayout(0, 1));
JPanel panel = new JPanel();
final JCheckBox check = new JCheckBox("Check");
Action checkAction = new AbstractAction("Update") {
#Override
public void actionPerformed(ActionEvent e) {
check.setSelected(!check.isSelected());
}
};
panel.add(check);
f.add(panel);
f.add(new SubPanel(checkAction));
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private static class SubPanel extends JPanel {
public SubPanel(final Action action) {
this.add(new JButton(action));
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Example().display();
}
});
}
}

How to get a JInternalFrame in the order i add it

I tried to access a JInternalFrame in my JDesktopPane and use getAllFrames method.
I just want to access the JInternalFrame in the order that i added into the JDesktopPane.
for example, i add a,b,c
frames[0] contain a
frames[1] contain b
frames[2] contain c
But i found out that the content in the array will change in case that i change my selection.
Every time I change my selection.
The selected JInternalFrame in the array will move to the top one.
For example , I select b
The array will become
frames[0] contain b
frames[1] contain a
frames[2] contain c
Are there any other ways to get the internal frame in the order i add it into desktoppane??
package org.app;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
public class MainFrame extends JFrame{
private static final long serialVersionUID = 1L;
private JDesktopPane theDesktop;
private List<JInternalFrame> frameList=new ArrayList<>();
public MainFrame() {
super("Internal Frame Demo");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(800,600);
this.setJMenuBar(setMenubar());
theDesktop=new JDesktopPane();
this.add(theDesktop);
this.setVisible(true);
}
public JMenuBar setMenubar() {
JMenuBar bar=new JMenuBar();
JMenu addMenu=new JMenu("Add");
JMenuItem newFrame=new JMenuItem("Internal Frame");
newFrame.addActionListener(new MenuAction());
addMenu.add(newFrame);
bar.add(addMenu);
return bar;
}
public JInternalFrame addInternalFrame() {
JInternalFrame jif=new JInternalFrame("Internal frame",true,true,true,true);
jif.setSize(new Dimension(240, 300));
jif.addInternalFrameListener(new InternalFrameAdapter() {
#Override
public void internalFrameClosing(InternalFrameEvent e){
frameList.remove(e.getInternalFrame());
System.out.println("from frame closing event");
}
});
jif.show();
return jif;
}
public JInternalFrame getInternalFrame(int index) {
return frameList.get(index);
}
class MenuAction implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
JInternalFrame f=addInternalFrame();
theDesktop.add(f);
frameList.add(f);
System.out.println("from menu action");
}
}
public static void main(String[] args){
new MainFrame();
}
}

Java button actions in multiple classes

Working in Java: I have a JFrame class, and separate classes for my two JPanels that are added to the JFrame. One of the JPanel classes has some buttons in it, which can interact with each other(when I click on one button, it can disable another button). However, I can't figure out how to get the button to call a method in the other JPanel (written in a separate class).
So, my program look like this:
JFrame
Jpanel1
Jpanel2 - This class has my buttons in it, I'm trying to get them to interact with the JPanel1 object.
Any tips appreciated, thanks!
One way to do this is to pass an instance of (to use your terminology) Jpanel1 into Jpanel2. This doesn't have to be done in the constructor, you can have a setConnectedPanel(JPanel) method, for example.
Here's some code that demonstrates what you want to do:
MyFrame.java
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class MyFrame extends JFrame {
public MyFrame() {
ReactionPanel rp = new ReactionPanel();
ActionPanel ap = new ActionPanel(rp);
setLayout(new GridLayout(2, 1));
add(ap);
add(rp);
pack();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MyFrame();
}
});
}
}
ActionPanel.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
public class ActionPanel extends JPanel implements ActionListener {
private ReactionPanel rp;
private JButton button;
public ActionPanel(ReactionPanel rp) {
this.rp = rp;
button = new JButton("Click");
button.addActionListener(this);
this.add(button);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(button)) {
rp.react();
}
}
}
ReactionPanel.java
import javax.swing.JLabel;
import javax.swing.JPanel;
public class ReactionPanel extends JPanel {
private JLabel label;
public ReactionPanel() {
label = new JLabel("PING");
this.add(label);
}
public void react() {
if(label.getText().equals("PING")) {
label.setText("PONG");
} else {
label.setText("PING");
}
}
}
As you can see, I tend to override all of my JFrames/JPanels when I write Swing GUIs as I find it easier and more flexible but YMMV.

Categories