How can I pass a JPanel as a parameter to a method? - java

Let me ask.
I´m working in a java project in Netbeans. I've created a JFrameForm (Design mode), inside the JFrameForm, there is five (5) JPanel.
I've found a method por enable/disable all components inside a Jpanel. Works.
private void changeState(){
for(Component c : mypanel.getComponents()){
c.setEnabled(false);
}
}
//mypanel it's one of a five panels in JFrameForm.
//I would like pass all the JPanel as parameters
I'm try writing a method where I can pass like parameter, just, the JPanel that I need when I invoced the method. Can you help me?
I'm try this,but don't work:
private void changeState(JPanel p){
for(Component c : p.getComponents()){
c.setEnabled(false);
}
}
I'm sorry if the answer it's very easy. I'm beginner in JAVA and in this community. I hope you can help me.

But it does work! When I run the following code (with your method included) it gives me 2 x true, and then 2 x false. So the method is fine.
public class Panelik extends JFrame {
JPanel panel;
JLabel label1, label2;
public Panelik() {
panel = new JPanel();
label1 = new JLabel();
label2 = new JLabel();
panel.add(label1);
panel.add(label2);
System.out.println(label1.isEnabled());
System.out.println(label2.isEnabled());
changeState(panel);
System.out.println(label1.isEnabled());
System.out.println(label2.isEnabled());
}
public void changeState(JPanel p) {
for(Component c : p.getComponents()) {
c.setEnabled(false);
}
}
public static void main(String[] args) {
Panelik panelik = new Panelik();
}
}

Related

Adding parameters to a GUI constructor stops GUI pop up

I've started learning Java with Eclipse, and I altered the main function to pass two strings to the similarly altered GUI constructor (there was nothing passed before).
The GUI doesn't pop up on the screen now, but can be accessed from the task bar at the bottom of the screen. I was just wondering why this happened? I've pasted the shortened code below.
I've tried it multiple times, and tried to find the problem with keywords on the web.
public class MainButton
{
public static void main(String[] args)
{
String A = "title"; String B = "Button";
Agui a = new Agui(A,B);
//BEFORE Agui a = new Agui();
}
}
import javax.swing.*;
public class Agui extends JFrame
{
//BEFORE public Agui()
public Agui(String A, String B)
{
setTitle(A);
setSize(400, 400);
// Create JButton and JPanel
JButton button = new JButton(B);
JPanel panel = new JPanel();
// Add button to JPanel
panel.add(button);
// And JPanel needs to be added to the JFrame itself!
this.getContentPane().add(panel);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
It'd be great to get the pop up without going to the task bar at the bottom of the screen, and to understand the logic of why this problem occurs.

Cannot Access Variable From Another Class

So, I have one class, with a radio button set up in it. Then in a second class, I extended the first class and made 3 "if" statements that will create an applet depending on the output of the radio button. In those "if" statements, it says that the variables cannot be resolved. How do I get these resolved? And please tell me if there are there any other errors in my code. Thanks a million, :D.
Thanks, any help will help greatly.
// The First Class Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RadioButton extends JPanel {
static JFrame frame;
JLabel pic;
RadioListener myListener = null;
public RadioButton() {
// Create the radio buttons
JRadioButton displacement = new JRadioButton("Displacement");
displacement.setMnemonic(KeyEvent.VK_N);
displacement.setSelected(true);
//Displacement Button, set to automatically be clicked
JRadioButton accel = new JRadioButton("Acceleration");
accel.setMnemonic(KeyEvent.VK_A);
accel.setActionCommand("acceleration");
//Acceleration Button
JRadioButton time = new JRadioButton("Change in time");
time.setMnemonic(KeyEvent.VK_S);
time.setActionCommand("deltaT");
//The change in time button
// Creates the group of buttons
ButtonGroup group = new ButtonGroup();
group.add(displacement);
group.add(accel);
group.add(time);
myListener = new RadioListener();
displacement.addActionListener(myListener);
accel.addActionListener(myListener);
time.addActionListener(myListener);
// Set up the picture label
pic = new JLabel(new ImageIcon(""+"numbers" + ".jpg")); //Set the Default Image
pic.setPreferredSize(new Dimension(177, 122));
// Puts the radio buttons down
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 1));
panel.add(displacement);
panel.add(accel);
panel.add(time);
setLayout(new BorderLayout());
add(panel, BorderLayout.WEST);
add(pic, BorderLayout.CENTER);
setBorder(BorderFactory.createEmptyBorder(40,40,40,40));
}
//Listening to the buttons
class RadioListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
pic.setIcon(new ImageIcon(""+e.getActionCommand()
+ ".jpg"));
}
}
public static void main(String s[]) {
frame = new JFrame("∆x = Vavg * time");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
});
frame.getContentPane().add(new RadioButton(), BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
My second class, with the if statements
import java.lang.Object;
import java.awt.Graphics;
public class RadioButtonMain extends RadioButton {
public static void main(String [ ] args) {
if ( displacement.isSelected())
{
//Option 1 for applet
}
if ( accel.isSelected()) {
//Option 2 for applet
}
else {
//Option 3 for applet
}
}
}
displacement is a local variable in your constructor. Therefore it won't be accessible outside the constructor.
If you want it to be accessible to other methods in the class, move it out of the constructor and make it an instance field, by saying JRadioButton displacement; above the constructor, in the same place where you declare myListener. In fact, you've already done the right thing with myListener, so you need to do the same thing with displacement.
This will make displacement accessible to other methods in the RadioButton class, but not to subclasses like RadioButtonMain. To make it accessible to RadioButtonMain, make the field protected:
protected JRadioButton displacement;
or, probably better, make it private and add a getter method to RadioButton to return the field, since you probably don't want subclasses to change displacement any time they feel like it.
Also, make sure you change this in your constructor:
JRadioButton displacement = new JRadioButton("Displacement");
to this:
displacement = new JRadioButton("Displacement");
so that you don't have a local variable with the same name as the field.
Finally, note that the main method is static. So even though it's defined inside RadioButtonMain, it won't have access to any fields of RadioButtonMain, including displacement. Make it something like this:
public static void main(String [ ] args) {
new RadioButtonMain().doMain();
}
public void doMain() {
if ( displacement.isSelected())
{
//Option 1 for applet
}
if ( accel.isSelected()) {
//Option 2 for applet
}
else {
//Option 3 for applet
}
}
}
This gives you a RadioButtonMain (which is also a RadioButton) to work with. Note that the RadioButton constructor will be called before doMain is called, which is what you want because the constructor sets up displacement.
displacement is not a global variable to access. within the method or constructor you cant access.

Variable sized array of JTextFields and other widgets

public class Creator extends JFrame {
JLabel[] pos;
JTextField[] monInitFi;
JPanel panel, statusP, inputP;
JTextField numMonsFi;
JButton goB, initRollB;
int numMons;
public Creator() {
panel = new JPanel();
createInputP();
panel.add(inputP);
add(panel);
}
//The Input board
public JPanel createInputP() {
inputP = new JPanel();
numMonsFi = new JTextField(3);
inputP.add(numMonsFi);
goB = new JButton("Go");
goB.addActionListener(new goBListener());
inputP.add(goB);
return inputP;
}
//Creates the initiative input board.
public JPanel createStatusP() {
statusP = new JPanel();
monInitFi = new JTextField[numMons];
for (int i = 0; i < numMons; i++) {
monInitFi[i] = new JTextField(3);
statusP.add(monInitFi[i]);
}
initRollB = new JButton("Roll");
statusP.add(initRollB);
return statusP;
}
//The button listener, should update numMons, and create and add the initiative panel.
public class goBListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
numMons = Integer.parseInt(numMonsFi.getText());
createStatusP();
panel.add(statusP);
}
}
public static void main(String[] args) {
Creator c = new Creator();
c.setVisible(true);
c.setSize(1000, 600);
c.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
c.setTitle("D&D 4e Encounter Tracker");
}
}
So this is only a sample of what I'm trying to do, but I cant even get the basics to work. When I run this the statusP(JPanel) does not show up, and I'm not sure if it's because its not running, or because it won't work.
I've tried putting the createStatusP() method in the GUI constructor but only the JButton will appear as if the for loop doesn't run.
Any help would be much appreciated.
In your goBListener's actionPerformed method, you should be calling panel.revalidate() to force the panel to be relaid out which will trigger a repaint, after you have added the statusP panel.
You should also try and follow Java naming conventions, the goBListener should start with an uppercase, GoBListener, it will make it easier for others to read (but will also make it easier for you to read other peoples code)
Instead of arrays, you might consider using some of List, this is a personal thing, but List is generally more flexible. Take a look at Collections for more details
This is because you call createInputP() as it's a procedure , but it's not ! it's a function it will return something that is in this case inputP panel ! so what's actually happening is overridable method call in constructor ! so the solution is add final keyword before createInputP() method !!
// final keyword after public keyword!
public final JPanel createInputP(){ ..... }
And modify goBListener like below :
public class goBListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
numMons = Integer.parseInt(numMonsFi.getText());
panel.revalidate();
panel.add(createStatusP());
}
}
Dang !! That's it !!

Using AWT Buttons and detecting if clicked

I just joined, and am glad to be here~ So, this morning (at like 2am, but thats besides the point :P ) I was doing a little bit of Java tests with JFrame and other GUI stuff. This is my first time working with GUIs. I was trying to make a little java app that would act as a dream journaller. However, my progress was frozen when I encountered a problem i could not solve. My code is as follows.
import java.awt.*;
import javax.swing.*;
import java.applet.*;
public class Display extends Canvas
{
static final int WIDTH = 600;
static final int HEIGHT = 400;
public static String defaultEntry = "Dreams...";
public static final String TITLE = "Dream Journal Testing";
Button erase;
public static void main(String[] args)
{
Display d = new Display();
d.create();
}
public void create()
{
JFrame frame = new JFrame();
System.out.println("Running");
Panel cardOne = new Panel();
Panel p1 = new Panel();
Panel p2 = new Panel();
Panel p3 = new Panel();
Panel grid = new Panel();
cardOne.setLayout(new BorderLayout());
p1.setLayout(new GridLayout(2,1,3,6));
TextArea textArea1 = new TextArea(defaultEntry);
/*Font f1 = new Font("Courier", Font.PLAIN, 16);
setFont(f1);*/
Label l1 = new Label("Welcome to the Dream Journal! :)");
Label l2 = new Label("Type your dream below:");
p1.add(l1);
p1.add(l2);
p2.add(textArea1);
p3.setLayout(new FlowLayout(FlowLayout.CENTER));
Button ok = new Button("Save");
erase = new Button("Erase");
p3.add(erase);
p3.add(ok);
cardOne.add("North",p1);
cardOne.add("Center",p2);
cardOne.add("South",p3);
frame.add(cardOne);
//frame.add(cardOne);
//frame.setLocationRelativeTo(null);
frame.pack();
frame.setTitle(TITLE);
frame.setSize(WIDTH, HEIGHT);
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
System.out.println(textArea1.getText());
}
/*public boolean handleEvent(Event evt)
{
if(evt.target == erase)
{
System.out.println("it works");
return true;
}
else return super.handleEvent(evt);
}
*/
public boolean action(Event evt, Object arg)
{
if("Erase".equals(arg))
{
System.out.println("hello");
//textArea1.setText("");
}
return true;
}
}
The problem i have is I am not able to figure out how to make it so if the "Erase" AWT button is pushed, the system will print a line (as a test). I have tried
public boolean action(Event evt, Object arg)
And
public boolean handleEvent, but neither worked. Anyone have any suggestions for the Java noob that is me? Thanks!! :)
One way is to add an action listener to the button (e.g. for Save). Another way is to create an Action (e.g. for Erase).
Don't mix Swing with AWT components unless it is necessary. It is not worth even learning how to use AWT components at this point in time, use Swing only for best results and best help.
Here is a version of the app. using all Swing components.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Display
{
static final int WIDTH = 600;
static final int HEIGHT = 400;
public static String defaultEntry = "Dreams...";
public static final String TITLE = "Dream Journal Testing";
JButton erase;
public static void main(String[] args)
{
Display d = new Display();
d.create();
}
public void create()
{
JFrame frame = new JFrame();
System.out.println("Running");
JPanel cardOne = new JPanel();
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
cardOne.setLayout(new BorderLayout());
p1.setLayout(new GridLayout(2,1,3,6));
JTextArea textArea1 = new JTextArea(defaultEntry);
JLabel l1 = new JLabel("Welcome to the Dream Journal! :)");
JLabel l2 = new JLabel("Type your dream below:");
p1.add(l1);
p1.add(l2);
p2.add(textArea1);
p3.setLayout(new FlowLayout(FlowLayout.CENTER));
JButton ok = new JButton("Save");
ok.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
System.out.println("Do " + ae.getActionCommand());
}
});
erase = new JButton(new EraseAction());
p3.add(erase);
p3.add(ok);
// Use the constants
cardOne.add(BorderLayout.PAGE_START,p1);
cardOne.add(BorderLayout.CENTER,p2);
cardOne.add(BorderLayout.PAGE_END,p3);
frame.add(cardOne);
frame.pack();
frame.setTitle(TITLE);
frame.setSize(WIDTH, HEIGHT);
frame.setResizable(false);
frame.setLocationByPlatform(true);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
System.out.println(textArea1.getText());
}
}
class EraseAction extends AbstractAction {
EraseAction() {
super("Erase");
}
#Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("Do " + arg0.getActionCommand());
}
}
First let me explain you the Funda of Event Handler....
- First of all there are Event Source, when any action take place on the Event Source, an Event Object is thrown to the call back method.
- Call Back method is the method inside the Listener (Interface) which is needed to be implemented by the Class that implements this Listener.
- The statements inside this call back method will dictate whats needed to be done, when the action is done on the Event Source.
Eg:
Assume
Event Source - Button
When Clicked - Event object is thrown at the call back method
Call back method - actionPerformed(ActionEvent e) inside ActionListener.
Now your case :
Now this can be done in 2 ways.....
1. Let you Display class implements the ActionListener, then Register the button with
the ActionListener, and finally implement the abstract method actionPerformed() of ActionListener.
Eg:
public class Display extends Canvas implements ActionListener{
public Display(){
// Your code....
setComponent(); // Initializing the state of Components
}
public void setComponent(){
// Your code.........
Button b = new Button("Click");
b.addActionListener(this); // Registering the button.
// Your code..........
}
public void actionPerformed(ActionEvent event) {
// Do here whatever you want on the Button Click
}
}
2. Use Anonymous class.
- Anonymous class are declared and initialized simultaneously.
- Anonymous class must implement or extend to only one interface or class resp.
Your Display class will NOT implement ActionListener here....
public class Display extends Canvas {
public Display(){
// Your code....
setComponent(); // Initializing the state of Components
}
public void setComponent(){
// Your code.........
Button b = new Button("Click");
// Registering the button and Implementing it
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event) {
// Do here whatever you want on the Button Click
}
});
// Your code..........
}
}
You need to implement ActionListner :
public class Display extends Canvas implements ActionListener
and add yourself to your button as such:
erase.addActionListener(this);
and then implement the required method:
public void actionPerformed(ActionEvent event) {
//do stuff
}
For more info, check out this tutorial on creating ActionListeners.
You'll find that this observable pattern is widely used the in Java GUI.
A couple high level critiques:
You are using many older AWT components (ie Button) when there are similar, but newer (read: more flexible) Swing components available (ie JButton). Take a look at this for a quick explanation on the difference.
The event model that you have implemented was revamped in 1997 to the observable pattern that I suggested above. If you would like to learn more, you can read this.

Can panels communicate with each other?

I'm trying to call a method from a panel class, however it does not result in anything. Can panels communicate with each other? Or is there another reason why this isn't working?
Calling the method name() in the leftInput class.
ButtonPanel class.
import model.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonPanel extends JPanel implements View
{
private Prison prison;
private JButton button = new JButton("Allocate Cell");
private LeftInputPanel leftInput;
private CrimePanel crimePanel;
public ButtonPanel(Prison prison, LeftInputPanel leftInput)
{
this.prison = prison;
this.leftInput = leftInput;
setup();
build();
}
public void setup()
{
}
public void build()
{
Dimension size = new Dimension(240, 70);
button.setPreferredSize(size);
button.setMinimumSize(size);
button.setMaximumSize(size);
button.addActionListener(new AllocateListener());
add(button);
}
public void update()
{
leftInput.clear();
}
private class AllocateListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Criminal criminal = new Criminal(leftInput.name());
prison.add(criminal);
System.out.println(leftInput.name());
}
}
}
leftInput class.
import model.*;
import java.awt.*;
import javax.swing.*;
public class LeftInputPanel extends JPanel
{
private Prison prison;
public JTextField name = new JTextField();
public JTextField days = new JTextField();
public JTextField months = new JTextField();
public JTextField years = new JTextField();
public LeftInputPanel(Prison prison)
{
this.prison = prison;
setup();
build();
}
public void setup()
{
setLayout(new FlowLayout());
Dimension size = new Dimension(100, 190);
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
}
public void build()
{
JLabel label = new JLabel("Name");
Dimension size = new Dimension(90, 20);
name.setPreferredSize(size);
add(label);
add(name);
Box box = Box.createVerticalBox();
box.add(daysPanel());
box.add(monthsPanel());
box.add(yearsPanel());
add(box);
}
public JPanel daysPanel()
{
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout(FlowLayout.LEFT));
addField(panel, days, " days");
return panel;
}
public JPanel monthsPanel()
{
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout(FlowLayout.LEFT));
addField(panel, months, " months");
return panel;
}
public JPanel yearsPanel()
{
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout(FlowLayout.LEFT));
addField(panel, years, " years");
return panel;
}
public void addField(JPanel panel, JTextField field, String label)
{
Dimension size = new Dimension(30, 20);
field.setPreferredSize(size);
field.setMinimumSize(size);
field.setMaximumSize(size);
panel.add(field);
panel.add(new JLabel(label));
}
public String name()
{
return name.getText();
}
public int days()
{
return Integer.parseInt(days.getText());
}
public int months()
{
return Integer.parseInt(months.getText());
}
public int years()
{
return Integer.parseInt(years.getText());
}
public void clear()
{
name.setText("");
days.setText("");
months.setText("");
years.setText("");
}
}
Do you ever actually construct the LeftInputPanel anywhere? (One would think you'd be getting a null pointer exception in the code at the top).
JPanels are extensions of Component. That means you can always call Component.getParent() to get the immediate container of your component and using that reference, gain access to all sibling components in the container by using Container.getComponents().
More specifically, if you add your panels to the top level container using indexes, then you can specifically request the reference to a sibling component using its index.
This is one way to avoid passing around references to various panels, by using the parent container as a containment context (which is precisely what it is).
And once you have the reference, a class is a class and you obviously can call all visible methods.
What is not working and what are you expecting to happen?
If you expect to be calling a method on an existing object from another object, that is perfectly doable, provided the method is public. The fact that these objects are JPanels are irrelevant.
What you should do is learn how to use the debugger to figure out if your method is being called and the println is occuring but the name is empty, or your method is not called, or any other problem.
If you're using Eclipse, there are some great debugging video tutorials here. But even if you're not using Eclipse you can check them out, and can apply them to whatever IDE you're using. It'll be far more efficient than sprinkling System.out.printlns here and there.
You shouldn't name methods like attributes. For instance, name() should be getName() or something like that. Might solve your problem.
There are a couple things that I see as missing here:
within your actionPerformed method, you declare a field and without trying to initialize it, you try to access it. This will be caught by the compiler.
I dont see anywhere that you create an AllocateListener or attach it to anything in your panel that would trigger the actionPerformed method.

Categories

Resources