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");
}
}
}
}
Related
my question is: how do I get the object of my CustomPanel, so that I am able to access its fields (because in my real programm I have some more fields in there) and also am able to delete it from my ArrayList?
I don't know how I have to implement an ActionListener in the Class Window, to somehow get the Object in my Arraylist, which containes the button that got pressed.
Also I am wondering if I am somehow able to implement an ActionListener in the Class CustomPanel which can influence the behaviour of the Object which is an instance of my Class Window.
I have kind of the following code:
public class Window extends JFrame{
ArrayList<CustomPanel> aLCustomPanel = new ArrayList();
JPanel jp = new JPanel();
public Window() {
for(int i=0;i<5;i++){
aLCustomPanel.add(new CustomPanel());
//here I could put the code from the 1 edit - see below
jp.add(aLCustomPanel.get(i));
}
this.add(jp);
}
public static void main(String args[]){
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Window().setVisible(true);
}
});
}
}
class CustomPanel extends JPanel {
private JButton button;
public CustomPanel(){
button = new JButton("button");
this.add(button);
}
public JButton getButton(){
return this.button;
}
}
my Code is much longer and weirder, so I tried to extract the (for this question) importing things.
Thanks for any help in advance!
edit:
for example: I would like to delete the object from the ArrayList, of which the button got pressed.
//imagine this comment in above code
aLCustomPanel.get(aLCustomPanel.size()-1).getButton().addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button_IwantToDeleteYou(e); //here I want to remove the panel, containing the button that got pressed from the above ArrayList, which is located in Class Window
}
});
edit2:
added a missing bracket and fixed some mistakes, code should be ok now.
Your code contained a few "gaps", i.e. missing code, which I filled in, as follows:
Added calls to [JFrame] methods setDefaultCloseOperation() and pack() and setLocationByPlatform(). I suggest you refer to the javadoc for those methods in order to understand what they do.
I set a layout manager for jp class member variable in your Window class.
Yes, you need to register an ActionListener with the JButton in class CustomPanel and that listener should reside in your Window class - the one that extends JFrame.
Here is my rewrite of your code. Note that I changed the name of class Window to CusPanel so as to distinguish between your class and java.awt.Window class. Not that it makes a difference, I just prefer not to use names of classes from the JDK.
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class CusPanel extends JFrame implements ActionListener {
private static final int COUNT = 5;
private ArrayList<CustomPanel> aLCustomPanel = new ArrayList<>();
private JPanel jp = new JPanel(new GridLayout(0, COUNT));
public CusPanel() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
for (int i = 0; i < COUNT; i++) {
aLCustomPanel.add(new CustomPanel(this));
// here I could put the code from the 1 edit - see below
jp.add(aLCustomPanel.get(i));
}
this.add(jp);
pack();
setLocationByPlatform(true);
}
public void actionPerformed(ActionEvent actionEvent) {
Object source = actionEvent.getSource();
if (source instanceof JButton) {
JButton button = (JButton) source;
Container parent = button.getParent();
jp.remove(parent);
jp.invalidate();
jp.repaint();
pack();
// aLCustomPanel.remove(parent); <- optional
}
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new CusPanel().setVisible(true);
}
});
}
}
class CustomPanel extends JPanel {
private JButton button;
public CustomPanel(ActionListener parent) {
button = new JButton("button");
button.addActionListener(parent);
this.add(button);
}
public JButton getButton() {
return this.button;
}
}
Note that after removing a CustomPanel, the GUI components need to be laid out again and the JFrame should also be resized accordingly. Hence in the actionPerformed() method, I call invalidate(), then repaint() and then pack(). I also think that if you remove a CustomPanel from the GUI, you should also remove it from the ArrayList, but hey, I still don't understand why you want to do this although I obviously don't know the whole story behind you wanting to do this in the first place.
Of-course, since each button (and each CustomPanel) looks exactly the same, you can't really know which button was removed. Again, I assume you see the big picture whereas I don't.
I tried to create a dialog box with Jbutton but when I am adding actionListener to it and passing the class to button which i have created to implements ActionListener I am getting "PathakP(Class Name) cannot be resolved to a type"
the code I have used is
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class GUI1 extends JFrame {
private JTextField J;
private Font pf,bf,itf,bif;
private JRadioButton pb,bb,ib,bib;
private ButtonGroup B;
private JButton ab;
public GUI1(){
super("To check the Font styles" );
setLayout(new FlowLayout());
J=new JTextField("This is the Text who's Font will be Changed pahtak is with me ",40);
add(J);
pb=new JRadioButton("Plain Button",true);
bb=new JRadioButton("Bold Button",false);
bib=new JRadioButton("Bold & Italic Button",false);
ib=new JRadioButton("Italic Button",false);
ab=new JButton("PathakButton");
add(ab);
add(pb);
add(bb);
add(bib);
add(ib);
B=new ButtonGroup();
B.add(pb);
B.add(bb);
B.add(bib);
B.add(ib);
pf=new Font("Serif",Font.PLAIN,15);
bf=new Font("Serif",Font.BOLD,15);
itf=new Font("Serif",Font.ITALIC,15);
bif=new Font("Serif",Font.BOLD+Font.ITALIC,16);
J.setFont(pf);
pb.addItemListener(new HandlerClass(pf));
bb.addItemListener(new HandlerClass(bf));
bib.addItemListener(new HandlerClass(bif));
ib.addItemListener(new HandlerClass(itf));
ab.addActionListener(new PathakP());
}
private class HandlerClass implements ItemListener{
private Font font;
public HandlerClass(Font f){
font=f;
}
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method stub
J.setFont(font);
}
private class PathakP implements ActionListener{
public void actionPerformed(ActionEvent ae) {
JOptionPane.showMessageDialog(null, "This is just JOptionPane example");
}
}
}
}
Main Class
import javax.swing.*;
public class Apples {
public static void main(String[] args) {
GUI1 G=new GUI1();
G.setVisible(true);
G.setSize(500,250);
G.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
I don't believe there is any error in the main class
I can troubleshoot this error by just creating another class outside but I want to know why it is not taking the class I have created and show unused in it
Your PathakP is written inside of HandlerClass. You have two solutions from there (after having corrected your bracket problem)
Either write it inside of GUI instead and since you're calling it from the constructor, it will be binded to this instance of GUI
Or, if you want to keep it within HandlerClass, you need to bind it to an instance of HandlerClass : ab.addActionListener(new HandlerClass().new PathakP())
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.
I'm trying to parse String to another frame Using JAVA
i have 2 jFrames. jFrame1 have 1 text field and jFrame 2 have 1 text field. i want to parse jFrame1 text filed's text to jframe2's text field.
It's look like this : But this is not code :(
jFrame2.textfield1.setText(jFrame1.textfield1.gettext());
Anyone know how to parse String to another frame Using JAVA?
Thanks in advance!
Assuming that you have two separate GUIs on the screen at the same time because both textFields have the same reference, each JFrame will be a Object in its own right.
Therefore the only way to access another objects variables is with its methods.
Create a setter method in jFrame2 to change the textField in question.
See Working code below.
import java.awt.*;
import javax.swing.*;
import javax.swing.BoxLayout;
import java.awt.event.*;
public class JframeLink {
public static void main(String[] args)
{
new JframeOneGui();
new JframeTwoGui();
}
//JFrame one Object
public static class JframeOneGui extends JFrame implements ActionListener
{
JPanel jPanelOne = new JPanel();
JTextField textField1 = new JTextField("Message for transfer");
JButton buttonOne = new JButton("Transfer");
public JframeOneGui()
{
//setup swing components
textField1.setSize(100,10);
buttonOne.addActionListener(this);
//setup jPanelOne
jPanelOne.setLayout(new BoxLayout(jPanelOne, 1));
jPanelOne.add(textField1);
jPanelOne.add(buttonOne);
//setup JframeOneGui
this.add("Center",jPanelOne);
this.setLocation(25,25);
this.setTitle("JframeOneGui");
this.setSize(200,200);
this.setResizable(false);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == buttonOne)
{
//Here we are calling JframeTwoGui's Setter method
JframeTwoGui.setTextFieldOne(textField1.getText());
}
}
}
//JFrame two Object
public static class JframeTwoGui extends JFrame
{
JPanel jPanelOne = new JPanel();
static JTextField textField1 = new JTextField();
public JframeTwoGui()
{
jPanelOne.setLayout(new BoxLayout(jPanelOne, 1));
jPanelOne.add(textField1);
this.add("Center",jPanelOne);
this.setLocation(300,25);
this.setTitle("JframeTwoGui");
this.setSize(200,200);
this.setResizable(false);
this.setVisible(true);
}
//Setter to change TextFieldOne in this Object
public static void setTextFieldOne(String text)
{
textField1.setText(text);
}
}
}
I just started learning Java 1 week ago, and I'm a 100% totally beginner. In this code, I can't seem to be able to put an actionlistener/get one to work. I don't even know where/how/in what way to put it, despite reading dozens of tutorials. I've created a JFrame with a JPanel in it, and on the JPanel there's a button. So far so good (and working). But then, I want it to be so that if the button is clicked, another button appears. Thank you sooo much in advance!
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class Skeleton extends JFrame implements ActionListener {
public static void main(String[] args) {
//------------------------------------------------
JFrame frame = new JFrame("Skeleton");
JPanel panel = new JPanel();
frame.setContentPane(panel);
frame.setSize(600,600);
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
JButton button = new JButton("This is a button.");
JButton button2 = new JButton("Hello");
panel.setLayout(null);
button.setBounds(20,20,200,25);
button2.setBounds(20,70,200,25);
panel.add(button);
//-------------------------------------------
button.addMouseListener(this);
}
public void ActionPerformed(ActionEvent e) {
System.out.println("Hello");
}
}
i will give you some advice
1) Don't implement ActionListener in top classes, use anonymous classes or private classes instead.
Example :
Anonymous class (also call Swing Actions)
myComponent.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent evt){
//code here
}
})
or
//inner class
public class Skeleton{
// in some part
private class MyActionListener implements ActionListener{
public void actionPerformed(ActionEvent evt){
//code here
}
}
}
2) Your code won't compile cause you are not implementing ActionListener interface
public void actionPerformed(ActionEvent evt) is the signature.
You have to addActionListener to your component
button.addActionListener(this);
3) Don't use null layout, cause you'll have a lot of problem if you want to add more components or resize windows cause you have to setBounds manually and it will be frustrating instead use [Layout Manager][1].
4) Try to not extends JFrame if is not necesary instead have a reference in your class, for example.
public class Skeleton{
private JFrame frame;
}
You need to add the actionlistener.
Register an instance of the event handler class as a listener on one or more components. For example:
yourdesiredcomponent.addActionListener(this);
For more details check the doc