I have an assignment where I have to click a button 1 in panel 1 and change the information on button 2 in panel 2, however I cannot figure out how to pass the information.
I thought I might be able to pass the information from method b() from panel2 back to one but that's not working.
I'm pretty stuck and don't know how to move forward with the program. Any help is appreciated.
Panel1
public class MyJPanel1 extends JPanel implements ActionListener {
Student st1 = new student("Fred","Fonseca",44);
JButton j = new JButton(st1.getInfo());
JButton b1 = new JButton("..");
public myJPanel1() {
super();
setBackground(Color.yellow);
// the whatsUp of this student has to shown in the other panel
j.addActionListener(this);
add(j);
}
public void actionPerformed(ActionEvent event) {
Object obj = event.getSource();
//=====================================
if (obj == j){
b1.setText(st1.whatsUp()); // Output on JButton in JPanel2
}
}
}
}
Panel2
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class myJPanel2 extends JPanel {
JButton j1 = new JButton("");
public void b(JButton b1) {
JButton j1 = b1;
}
public myJPanel2() {
super();
setBackground(Color.pink);
setLayout(new GridLayout(3,1));
add(j1);
// j1.setText(b1);
}
}
Create a method in MyJPanel2 which sets the text in JButton.
public class myJPanel2 extends JPanel {
JButton button = new JButton("");
...........
public void setButtonText(String text) {
button.setText(text);
}
}
In MyJPanel2, you need to store a reference of MyJPanel1. Then just call the setButtonText in the ActionListener
public class MyJPanel1 extends JPanel implements ActionListener {
private MyJPanel2 panel;
public MyJPanel1(MyJPanel2 panel) {
this.panel = panel;
}
public void actionPerformed(ActionEvent event) {
if (obj == j){
panel.setButtonText(yourText);
}
}
}
}
A couple things to keep in mind. Java is an Object Oriented language, meaning that you want define your Objects using Classes, and then reuse those objects as much as possible. If you have two panels, each one containing a button, then that is the perfect time to define the Class once
public class MyPanel extends JPanel{
protected JButton button;
public MyPanel(String buttonName){
button = new JButton(buttonName);
}
//etc etc etc
}
and then use the Class over and over
public class MyProgram {
protected MyPanel panel1;
protected MyPanel panel2;
public MyProgram(){
panel1 = new MyPanel("Button 1");
panel2 = new MyPanel("Button 2");
}
//etc etc
}
Now, once you have your program set up like this, it is very easy to communicate between the two panels, since in MyProgram you have both instances of your panels available.
So, lets say your MyPanel class had a method called setButtonText
public void setButtonText(String text){
button.setText(text);
}
You could call this method in your MyProgram in order to change the text on one of the buttons
myPanel1.setText("New Button 1 text");
But how do we know if the button in myPanel1 or myPanel2 was pushed? You can look into how Java uses ActionListener to communicate events between different objects.
Good luck!
If I write sea you don't have connected that two panels together. The best way to coonect them together is from thrid calass wher you declare this two clasess. And set this two classes eachOther.
Example:
class conecctor{
ClassA first;
ClassB secod;
public void init(){
{
first=new ClassA();
second=new ClassB();
first.setClasB(second);
second.setClasA(first);
}
}
class ClassA{
ClassB classB;
public void setClassB(ClassB classB){
this.classB=classB;
}
}
class ClassB{
ClassA classA;
public void setClassA(ClassA classA){
this.classA=classA;
}
}
And then when you have instances in each class you can call all public methods from evrywher.
Beter way is to create interface and just pass the interface (listener) steal you pass whole class if that clas implements interface but it its more clearly and other advatages.
Related
Why doesn't my car object pass into my ViewCarForm?
A car gets passed into InventoryItemPanel.
public class InventoryItemPanel extends JPanel{
Car car;
Button button = new Button("View More Details");
public InventoryItemPanel(Car car){
this.car = car;
// executes ButtonActionPerformed when button is clicked.
button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ButtonActionPerformed(evt);
}
});
add(button);
}
public void ButtonActionPerformed(java.awt.event.ActionEvent evt) {
new ViewCarForm(car).setVisible(true);
}
}
The button when clicked is then supposed to pass the same car to ViewCarForm.
public class ViewCarForm extends javax.swing.JFrame {
Car car;
public ViewCarForm() {
initComponents();
}
public ViewCarForm(Car car){
new ViewCarForm().setVisible(true);
jLabel.setText(car.getMake());
}
}
However, the label in ViewCarForm does not get updated by the car object, so I assume that it is not passing through?
Let's look at what this constructor is doing:
public ViewCarForm(Car car){
new ViewCarForm().setVisible(true); // (A)
jLabel.setText(car.getMake()); // (B)
}
On line (A) you create a new ViewCarForm object -- and you do so within the ViewCarForm constructor, not something that I recommend that you do, since now you have two ViewCarForm instances, the original one, and a new one that you display.
On line (B) you set the text of a JLabel, a variable of the first and non-displayed ViewCarForm instance (I'm guessing that it's a variable of this class -- you never show us the variable declaration or instantiation. OK this will set the JLabel text of a non-displayed GUI, meanwhile the second ViewCarForm instance, the one that you do display, has no change to the text of its JLabel.
You don't call this() or initComponents() within the 2nd constructor, and so the code from the first default constructor, including the initComponents(); call, is never called, and so components are never properly laid out when this constructor is called.
Solution: don't do this, don't create two ViewCarForm instances, especially from within the same class's constructor. The only reason you don't have a stackoverflow error is because your class has two constructors, but even without the stackoverflow, it's insanity to do this. Create only one instance and set its JLabel text. Get rid of line (A)
Also, if the ViewCarForm is a secondary window, it shouldn't even be a JFrame but rather it should be a JDialog, either modal or non-modal depending on your need.
Also, you only init components in one ViewCarForm constructor and not in the other. So the JLabel will not show up in the second constructor/instance.
For example:
import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.awt.Window;
import javax.swing.*;
public class InventoryFoo extends JPanel {
private static final Car FIRST_CAR = new Car("Honda");
private InventoryItemPanel inventoryItemPanel = new InventoryItemPanel(FIRST_CAR);
public InventoryFoo() {
inventoryItemPanel.setBorder(BorderFactory.createTitledBorder("Inventory Item"));
add(inventoryItemPanel);
}
private static void createAndShowGui() {
InventoryFoo mainPanel = new InventoryFoo();
JFrame frame = new JFrame("InventoryFoo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
class InventoryItemPanel extends JPanel {
Car car;
// Button button = new Button("View More Details"); // should be a JButton
JButton button = new JButton("View More Details"); // should be a JButton
public InventoryItemPanel(Car car) {
this.car = car;
// executes ButtonActionPerformed when button is clicked.
button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ButtonActionPerformed(evt);
}
});
add(button);
}
public void ButtonActionPerformed(java.awt.event.ActionEvent evt) {
// new ViewCarPanel(car).setVisible(true);
// get current JFrame
Window thisJFrame = SwingUtilities.getWindowAncestor(this);
// Create a non-modal JDialog
JDialog dialog = new JDialog(thisJFrame, "Car Make", ModalityType.MODELESS);
// create new viewCarPanel
ViewCarPanel viewCarPanel = new ViewCarPanel(car);
// add to dialog
dialog.add(viewCarPanel);
dialog.pack();
dialog.setLocationRelativeTo(thisJFrame);
dialog.setVisible(true);
}
}
// better for this to be a JPanel
class ViewCarPanel extends JPanel {
Car car;
private JLabel jLabel = new JLabel();
public ViewCarPanel() {
add(new JLabel("Car Make:"));
add(jLabel);
setPreferredSize(new Dimension(300, 80));
}
public ViewCarPanel(Car car) {
// so that we init components from the default constructor
this();
// new ViewCarPanel().setVisible(true);
jLabel.setText(car.getMake());
}
}
class Car {
private String make;
public Car(String make) {
this.make = make;
}
public String getMake() {
return this.make;
}
}
Hi is there a way to Add JButton to JPanel from Different Class. So basically the JPanel is in a Class A and JButton is in a Class B how can I put the button on the Panel which is in a different class. Hopefully this makes sense if you need me to clarify let me know. Thanks for the help in advance.
You can make something like this:
public OtherClass {
public JButton getButton (){
JButton b = new JButton();
b.set...();
b.set...();
b.set...();
b.set...();
return b;
}
}
Then you can use this function to create a JButton which is always the same.
Another option is to create your Button as a static and use it in your OtherClass, this is not a well solution, but it can be an option
You would need the instance object of class B in class A to access its variables and methods. You could then write something like the following:
public ClassB {
public JButton getButton() {
return myJButton;
}
}
Another way to do it is to make the JButton static in class B, however this is a dirty hack that is a bad design pattern.
public ClassB {
public static JButton myJButton;
}
You could then access the JButton from ClassA by using ClassB.myJButton
You can Inherit classes or use a single one:
public class Example{
public static void main(String []args){
JFrame wnd = new JFrame();
//edit your frame...
//...
wnd.setContentPane(new CustomPanel()); //Panel from your class
wnd.getContentPane().add(new CustomButton()); //Button from another class
//Or this way:
wnd.setContenPane(new Items().CustomPanel());
wnd.getContentPane().add(new Items().CustomButton());
}
static class CustomButton extends JButton{
public CustomButton(){
//Implementation...
setSize(...);
setBackground(...);
addActionListener(new ActionListener(){
//....
});
}
}
static class CustomPanel extends JPanel{
public CustomPanel(){
//Implementation...
setSize(...);
setBackground(...);
OtherStuff
//....
}
}
static class Items{
public JButton CustomButton(){
JButton button = new JButton();
//Edit your button...
return button;
}
public JPanel CustomPanel(){
JPanel panel = new JPanel();
//Edit your panel...
return panel;
}
}
}
When I design a Java Form with intellij it only declares private components like
Private JPanel myPanel;
But how can I access this object from within my class sourcefile. E.g. when I want to add a JButton to myPanel?
i know I can write a getter for myPanel but how do I access it then?
Let me explain my solution with the change of a button text.
Create the button in intellij GUI Designer
Add a getter method to it (go to source, write getter manually or let intellij do it for you)
Now you can use the getter method to access the objects methods.
Example: Change button text of a GUI-designer-created button on click:
import javax.swing.*;
import java.awt.event.*;
public class TestForm {
private JButton button1;
private JPanel panel1;
public TestForm() {
getButton1().addActionListener(new clickListener());
}
public JButton getButton1() {
return button1;
}
public static void main(String[] args) {
JFrame frame = new JFrame("TestForm");
frame.setContentPane(new TestForm().panel1);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public void changeTextOnButton(){
getButton1().setText("gwerz");
}
public class clickListener implements ActionListener{
public void actionPerformed(ActionEvent e){
if (getButton1().getText().equals("Button")){
getButton1().setText("Dgsdg");
}
else {
getButton1().setText("Button");
}
}
}
}
First I have a GUI (gui1), when I press a button, a different GUI (gui2) is created. My question is: How I can get access to elements from gui2, using methods from gui1?
Example: When I press a button from gui1, I want to QuesHandText.setText(myVector[0]); QuesHandText is a JTextField from gui1 and myVector[0] a var from gui2. The result error message: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
When I press Ok from Gui2 , I want to setText for the JTextField on Gui1
http://img72.imageshack.us/img72/2822/36185233.png
//imports
public class Gui extends JFrame{
public JButton Simulate, Particular, Start, HandSelection;
public JTextField QuesHandText, FlopTurnRiverText, RezultatText;
public Gui g;
public Gui()
{
QuesHandText = new JTextField(4);
//instruct
ClassParticular handler1 = new ClassParticular();
Particular.addActionListener(handler1);
}
public Gui(String t)
{
//instruct
myVector[0]="some_string";
myVector[1]="some_string2";
}
public class ClassParticular implements ActionListener{
public void actionPerformed(ActionEvent event){
//instruc
HandSelection hs = new HandSelection();
HandSelection.addActionListener(hs);
StartClass hndlr = new StartClass();
Start.addActionListener(hndlr);
add(HandSelection);
add(Start);
}
}
public class HandSelection implements ActionListener{
public void actionPerformed(ActionEvent e){
g = new Gui("Hand selection");
g.setVisible(true);
g.setSize(1135,535);
g.setDefaultCloseOperation(HIDE_ON_CLOSE);
g.setResizable(false);
}
}
public class StartClass implements ActionListener{
public void actionPerformed(ActionEvent event){
QuesHandText.setText(myVector[0]); // THE PROBLEM IS HERE, I KNOW IT !!
}
}
}
You have two constructors of Gui.
public Gui()
And
public Gui(String t)
You have initialized QuesHandText in the first one, but not in the second one.
If you use the second one to initialize the Gui you are supposed to get a NullPointerException.
I think you should do this in constructors:
[Edited as suggested by Kleopetra]
public Gui(){
this("");
}
public Gui(String t){
//instruct (I am not sure what it means)
quesHandText = new JTextField(4);
classParticular handler1 = new ClassParticular();
particular.addActionListener(handler1);
myVector = new String[2]; // or some other size you need.
myVector[0]="some_string";
myVector[1]="some_string2";
}
1.your problem is
public class Gui extends Jframe{
that should be
public class Gui extends JFrame{
2.another problems are
public JButton Simulate, Particular, Start, HandSelection;
public JTextField QuesHandText, FlopTurnRiverText, RezultatText;
public Gui g;
remove JButton and JTextField because they are JComponents and API names
or declare JButton and JTextField correctly
.
public JButton myButton, ...
public JTextField myTextField, ...
3.don't extends JFrame create that as local variable
4.don't re_create a new GUI from ActionPerformed use CardLayout
I am having problem with JFrames.
Currently I have 2 JFrames running,
MainFrame with a button to call Frame2.
And from Frame2 with JButton, I wan to call the current running/background MainFrame without calling another new MainFrame.
Actually I am making a search function on Frame2 and when click button search, wanna display the results in the Main Frame.
If Frame2 inherits MainFrame then do this:
Frame2.getParent().getBackground();
There are a multitude of solutions for such problems. It really depends on what best suits your use case.
In the example below I use an interface to issue callbacks to MainFrame from Frame2. I assume the latter is a member of MainFrame. This sort of solution makes it easy for you to use the same Frame2 implementation in multiple implementations of MainFrame (a common search for more than one frame).
Note that code below is just skeleton code to demonstrate the pattern being used.
public class Frame2 extends JFrame {
private final Controller controller;
private JButton button;
public Frame2(Controller controller) {
this.controller = controller;
button = new JButton("Search");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// do search and create result object
Object results = new Object();
Frame2.this.controller.displaySearchResults(results);
}
});
}
public interface Controller {
// users implement this
public void displaySearchResults(Object results);
}
}
public class MainFrame extends JFrame {
private Frame2 search;
private JButton button;
public MainFrame() {
search = new Frame2(new ControllerImplementation());
button = new JButton("Show search");
button.addActionListener(new ShowSearch());
}
private class ShowSearch implements ActionListener {
public void actionPerformed(ActionEvent e) {
search.setVisible(true);
}
}
private class ControllerImplementation implements Frame2.Controller {
public void displaySearchResults(Object results) {
// display results by accessing members of MainFrame
}
}
}
This may help you achieve what you want.