Add JButton to JPanel from Different Class - java

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

Related

How do you have an ActionListener perform different events based on the actionPerformed?

I have four buttons each on four different panels. If I press the button I would want the panel it's on to change color. The problem is I only know how to do that for one button and not all four. Here is my code so far...
public class tester implements ActionListener
{
JPanel B;
JPanel A;
public static void main(String[]args)
{
new tester();
}
public void tester()
{
JFrame test = new JFrame("tester:");
B = new JPanel();
A= new JPanel();
JPanel cc = new JPanel();
JPanel dd = new JPanel();
JButton b = new JButton("ButtonB");
JButton a = new JButton("ButtonA");
JButton c = new JButton("ButtonC");
JButton d = new JButton("ButtonD");
test.setLayout(new GridLayout(2,2));
test.setSize(600,500);
B.setBackground(Color.BLUE);
A.setBackground(Color.RED);
cc.setBackground(Color.BLACK);
dd.setBackground(Color.WHITE);
B.add(b);
A.add(a);
cc.add(c);
dd.add(d);
test.add(A);
test.add(B);
test.add(cc);
test.add(dd);
test.setVisible(true);
b.addActionListener(this);
a.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
B.setBackground(Color.PINK);
}
}
You can use anonymously created Action listeners instead of implementing interface in your class.
b.addActionListener(new ActionListener() {
//method impl.
});
And use that to create 4 different actions.
Or you could get source of action from
e.getSource()
And then decide based on that.
Or you can skip ActionListener all the way, and use lambda
b.addActionListener(e -> someActionOrSomething(e))
You have to check the resource and can perform action based on it If you are trying to keep a common ActionListener,
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b)//button b
B.setBackground(Color.PINK);
else if(e.getSource()==a)//button a
A.setBackground(Color.BLACK);
}
Please note you have to declare your buttons globally, If you have to use it inside the class,
public class Test implements ActionListener
{
JPanel B;
JPanel A;
JButton b;
JButton a;
Also you have created the implementation in a method called tester which should be called as,
new Test().tester();

Access Intellij Form Designer objects

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

How can I inform the class which have an instance of a GUI builder class, when the JButton ActionEvent performed

Ok, here is my problem. Class B is a class that build a GUI ,which has a textField and button. class A has an instance of class B.Now I enter some value in the textfield, when I click the button, in class A I want to print out the value I just enter in the textfield, how can I achieve that?
Code below may better explain what I want to achieve:
public class A
{
B myB = new B();
(when the JButton was clicked,
how can I get the new textfield value here?)
}
public class B
{
JLabel myLabel;
JButton myButton;
public B()
{
getContentPane().setLayout(null);
myLabel = new JLabel();
myLabel.setLocation(0,0);
myLabel.setSize(100,30);
myLabel.setBackground( new Color(-6710887) );
myLabel.setText("");
getContentPane().add(myLabel);
myButton = new JButton();
myButton.setLocation(0,50);
myButton.setSize(100,30);
myButton.setBackground( new Color(-16737895) );
myButton.setText("Submit");
getContentPane().add(myButton);
myButton.addActionListener(this);
setSize(400,400);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{
(how can I pass this "myLabel.getText()" value to class A when
this action performed?)
}
}
Can anybody help me finish this little program? Thanks in advance!
You need to expose the value in text field with a method in class B. Then class A can call that method. What it actually sounds like though is that class A (or something else) should be a ActionListener for your button.
However, a bigger problem is that you don't have a text field you just have a label in class B. This code is a good reason why you shouldn't use a GUI builder, especially when learning Swing.
Some reading:
http://docs.oracle.com/javase/tutorial/uiswing/components/textfield.html
http://docs.oracle.com/javase/tutorial/uiswing/events/
I often make an "App" class that ties all my GUI-builder-built components together. Any GUI builder worth anything lets you add getters to the generated source code. Add some getters to the GUI-built components to retrieve key elements of the GUI, then let the App class use the getters to interact with the components as necessary. This won't win any MVC/MVVM/MVP design awards, but it gets the job done, which ought to count for something.
public class App {
private B _b;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
App app = new App();
app.run();
}
});
}
void run() {
_b = new B();
_b.getMainButton().addActionListener(new MainButtonListener());
_b.setVisible(true);
}
private void handleMainButtonClicked() {
String mainText = _b.getMainTextArea().getText();
System.out.println("Button clicked; main text = " + mainText);
}
public class MainButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
handleMainButtonClicked();
}
}
}
public class B extends JFrame {
private JPanel _contentPane;
private JTextArea _jTextArea;
private JButton _jButton;
public B() {
initComponents();
}
private void initComponents() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
_contentPane = new JPanel();
setContentPane(_contentPane);
_jTextArea = new JTextArea();
_contentPane.add(_jTextArea, BorderLayout.CENTER);
_jButton = new JButton("My Button");
_contentPane.add(_jButton, BorderLayout.SOUTH);
}
public JButton getMainButton() {
return _jButton;
}
public JTextComponent getMainTextArea() {
return _jTextArea;
}
}

Passing information between buttons

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.

How to get acces to elements from another GUi?

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

Categories

Resources