Why is my JPanel empty after button is clicked? - java

I'm learning how to create event listeners in Java for a button click. I want a panel to popup with form items. I've built the panel in the action listener's contructor, but it's empty when it opens. I thought it makes sense to only build this one, then just show it when the button is clicked (actionPerformed). Obviously not :)
Below is my ActionListener class:
package biz.martyn.budget;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class NewTransaction implements ActionListener {
protected JPanel panel = new JPanel(new GridLayout(0, 1));
public void NewTransaction() {
String [] category = {"Internet", "Clothes", "Rent", "Salary", "Groceries"};
JComboBox combo = new JComboBox(category);
panel.add(combo);
panel.add(new JLabel("Description:"));
JTextField desc = new JTextField();
panel.add(desc);
panel.add(new JLabel("Date:"));
JTextField date = new JTextField();
panel.add(date);
panel.add(new JLabel("Amount:"));
JTextField amount = new JTextField();
panel.add(amount);
}
#Override
public void actionPerformed(ActionEvent arg0) {
int result = JOptionPane.showConfirmDialog(null, panel, "New transaction",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
}
}
Here is how I'm attaching the event:
JButton newTransactionButton = new JButton("New transaction");
newTransactionButton.addActionListener(new NewTransaction());
toolbar.add(newTransactionButton);
I'd appreciate any additional advice on conventions when doing this sort of thing coz I'm quite the beginner, thanks.

I've built the panel in the action listener's contructor, but it's empty when it opens
The following...
public void NewTransaction() {
...is a method, not a Constructor. You need to explicitly call it, or change it to a constructor
public NewTransaction() {

Related

Java GUI ButtonHandler issue

I'm not sure what exactly I am doing wrong but I keep getting an error with the ButtonHandler. I have a GUI class and a GUI Test class. The GUI class is the first one and the GUI_Test class is at the bottom. I am using NetBeans IDE 11.0. Everything else works on here but the ButtonHandler. I believe I followed the directions wrong or something because it just keeps telling me to create a new class for the ButtonHandler or break it up. But neither of those things are what I want.
The checkboxes also will not appear in the output text area when you run it.
package javaapplication20;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
public class Week3GUI extends JFrame {`
//variables
private JRadioButton radCoffee, radTea;
private JCheckBox chkFootball, chkBasketball, chkBaseball;
private JTextArea txtMessage;
public Week3GUI()
{
//instantiate the GUI components
// this sets 5 rows, 20 columns as default size
txtMessage = new JTextArea(5,20);
radCoffee =new JRadioButton("Coffee");
radTea =new JRadioButton("Tea");
//instantiate checkboxes
chkFootball =new JCheckBox("football");
chkBasketball =new JCheckBox("basketball");
chkBaseball =new JCheckBox("baseball");
//create panel for the radio buttons
JPanel p1 =new JPanel();
JPanel p2 =new JPanel();
//set layout for the panel and add the components
p1.setLayout(new FlowLayout());
p1.add(radCoffee);
p1.add(radTea);
// set layout for the panel and add the components
p2.setLayout(new FlowLayout());
p2.add(chkFootball);
p2.add(chkBasketball);
p2.add(chkBaseball);
//need to group the buttons together
ButtonGroup b =new ButtonGroup();
b.add(radCoffee);
b.add(radTea);
//add event handlers for radio buttons
RBHandler rb =new RBHandler();
radCoffee.addItemListener(rb);
radTea.addItemListener(rb);
//use grid layout for the frame
//1 column, multiple rows
setLayout(new GridLayout(0,1));
//first "row" of the frame is the label
add(new JLabel("Which do you like?"));
//next "row" is the panel p1 with radio buttons
add(p1);
//third "row" is the textfield
add(p2);
// fourth "row" is the textfield
add(txtMessage);
} //end constructor
private class RBHandler implements ItemListener
{
#Override
public void itemStateChanged(ItemEvent e)
{
if(radCoffee.isSelected())
txtMessage.setText("You like coffee");
else if(radTea.isSelected())
txtMessage.setText("You like tea");
}
private void processChoices()
{
//"read" the radio buttons first
if(radCoffee.isSelected())
txtMessage.setText("You like\ncoffee");
else if (radTea.isSelected())
txtMessage.setText("You like\ntea");
else
{
JOptionPane.showMessageDialog(null,"Must select a beverage",
"Error",JOptionPane.ERROR_MESSAGE);
return; //do NOT continue this method
}
//now read the check boxes and APPEND to textarea
if(chkFootball.isSelected())
txtMessage.append("\nfootball");
if(chkBasketball.isSelected())
txtMessage.append("\nbasketball");
if(chkBaseball.isSelected())
txtMessage.append("\nbaseball");
}
private class ButtonHandler implements ActionListener
{
ButtonHandler h = new ButtonHandler();
#Override
public void actionPerformed(ActionEvent actionEvent)
{
processChoices();
radCoffee.addActionListener(h);
radTea.addActionListener(h);
chkFootball.addActionListener(h);
chkBaseball.addActionListener(h);
chkBasketball.addActionListener(h);
}
}
}
} //end class
package javaapplication20;
import javax.swing.JFrame;
public class Week3GUI_Test {
public static void main(String[] args)
{
Week3GUI g =new Week3GUI();
g.setSize(300,200);
g.setVisible(true);
g.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Duplication child JFrame on click

I have a window, which is the main window in my app and it contains buttons. On clicking on one of them, a child JFrame appears and if I click again another frame appears and this can be continuous depending on how many clicks are made. What I want, is when I click on the JButton once only one frame should open and since this frame is open no other similar frames can be opened upon clicking on the button for the second time until the first child frame is closed.
This can be done by opening a Modal dialog box instead of a jFrame. See How to Use Modality in Dialogs for more information.
Here is a simple example from A Simple Modal Dialog:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class AboutDialog extends JDialog implements ActionListener {
public AboutDialog(JFrame parent, String title, String message) {
super(parent, title, true);
if (parent != null) {
Dimension parentSize = parent.getSize();
Point p = parent.getLocation();
setLocation(p.x + parentSize.width / 4, p.y + parentSize.height / 4);
}
JPanel messagePane = new JPanel();
messagePane.add(new JLabel(message));
getContentPane().add(messagePane);
JPanel buttonPane = new JPanel();
JButton button = new JButton("OK");
buttonPane.add(button);
button.addActionListener(this);
getContentPane().add(buttonPane, BorderLayout.SOUTH);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
setVisible(false);
dispose();
}
public static void main(String[] a) {
AboutDialog dlg = new AboutDialog(new JFrame(), "title", "message");
}
}

Swing - Changing different JLabels with the same Component Popup menu

I am pretty new to Swing, any help appreciated.
I have the following situation:
A "Main" Class where I define my main JPanel and default Label text.
A "GUILabel" Class (extends JLabel) where I define the look of the Text Labels.
A "popupmenu" Class (extends JPopupMenu) where I define the content of the popupmenu.
Target:
When I right-click on a panel the popupMenu should appear (this already works).
When I choose a menu item of this popupMenu, the text of the label I clicked on should change.
I guess its currently not working (I am sorry this code isn't complete - this is my 5th attempt), because I create the popup menu Once in the Main Class. Then I am adding this popup menu to each Label. So I guess thats why getInvoker() returns null in the popup menu class.
But do I really have to create a new popupmenu for each JLabel? Cant this single menu just handle all Components assigned to?
Main Frame:
package popupshit;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.border.BevelBorder;
public class Model implements ActionListener {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(0, 3));
frame.setVisible(true);
GUIPopupMenu popup = new GUIPopupMenu(9);
JLabel label1 = new GUILabel();
label1.setComponentPopupMenu(popup);
JLabel label2 = new GUILabel();
label2.setComponentPopupMenu(popup);
JLabel label3 = new GUILabel();
label3.setComponentPopupMenu(popup);
frame.add(label1);
frame.add(label2);
frame.add(label3);
frame.pack();
}
#Override
public void actionPerformed(ActionEvent e) {
((JLabel) e.getSource()).setText("" + e.getActionCommand());
}
}
PopupMenu:
package popupshit;
import java.awt.event.ActionListener;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
public class GUIPopupMenu extends JPopupMenu {
public GUIPopupMenu(int numbers) {
for (int i = 1; i < numbers; i++) {
JMenuItem popMenuItem = new JMenuItem("" + i);
popMenuItem.addActionListener ((ActionListener) this.getInvoker());
System.out.println(this.getParent());
this.add(new JMenuItem("" + i));
}
this.addSeparator();
this.add(new JMenuItem("remove"));
}
}
GUILabel:
package popupshit;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.border.BevelBorder;
import javax.swing.border.BevelBorder;
public class GUILabel extends JLabel implements ActionListener {
public GUILabel() {
this.setBorder(new BevelBorder(BevelBorder.LOWERED));
this.setVisible(true);
this.setPreferredSize(new Dimension(50, 50));
this.setText("0");
}
#Override
public void actionPerformed(ActionEvent e) {
this.setText((String) e.getActionCommand());
JOptionPane.showMessageDialog(null, "worked!" );
}
}
invoker is null because until the popup menu is a actually invoked, it has no invoker.
Instead, add a simple ActionListener to the menu item which, when invoked, uses the invoker property to determine which should occur.
My personal preference would be to create a new instance of the popup menu for each component separately, passing a reference of the component in question or some other controller as required...but that's me...
Add an ActionListener to the menu item something like:
#Override
public void actionPerformed(ActionEvent e)
{
Component c = (Component)e.getSource();
JPopupMenu popup = (JPopupMenu)c.getParent();
JLabel label = (JLabel)popup.getInvoker();
...
}
Don't extend JPopupMenu just to add a few menu items to the popup.

Pass value from one JtextField to another?

//New to java swing and need help getting the text in the first Jtextfield to display in the //second second jtextfield???? Im young and just starting out in java and need some help. below is the code i have done already thanks
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class lab4 extends JFrame implements ActionListener {
int numClicks = 0;
String text = null;
public lab4() {
setSize(1200, 700);
setVisible(true);
JButton button = new JButton("Hello i am a button");
button.addActionListener(this);
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
panel.add(button);
this.add(panel);
JMenuBar menubar = new JMenuBar();
this.setJMenuBar(menubar);
JMenu file = new JMenu("File");
menubar.add(file);
JMenuItem open = new JMenuItem("Open File");
file.add(open);
final JTextField myField = new JTextField(10);
myField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String text = myField.getText();
//System.out.println("Hello");
}
});
final JTextField myField2 = new JTextField(10);
yField2.setText(myField.getText());
panel.add(myField);
panel.add(myField2);
setVisible(true);
}
}
public static void main(String[] args) {
new lab4();
}
public void actionPerformed(ActionEvent e) {
numClicks++;
System.out.println("The button has been clicked " + numClicks + " times");
}
}
Yes, you are doing ok. If more then one work going to happen in sequence on one action event, then you need to put the sequence inside the corresponding actionPerformed function. So:
myField.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String text = myField.getText();
myField2.setText(text);
}
});
JComponents listeners mean that they will listen and respond only when an action event occur. They will be notified by the instance of ActionListener registered to event source(JCompnent) with addActionListener() function as you have done.
One more thing to note: you can't access a field in any statement before even declaring it. Compiler's need to know the information about the field before doing anything with it. So you must declare myField2 before the accessing-code of it, such as, myField1's anonymous class ActionListener actionPerformed function.
Tutorial Resources:
Writing Event Listeners
Anonymous Class
You can share the model:
JTextField textField1 = new JTextField(...);
JTextField textField2 = new JTextField(...);
textField2.setDocument( textField1.getDocument() ):
Now whenever you type text in either text field the other will also be updated.

get text from jtextarea split it and pass it to jlabel on new line?

hi friends im new here i write a code in two classes where in one class i declare a jtextarea and a button when we click the button then text will split and it display in the jlabel but here is problem is that the text is written in jtext area and button also working but when jlabel frame open it show nothing here is my code
the first class
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
public class Try extends JFrame {
JTextArea text;
String string;
public Try(){
super("survey");
Container container=getContentPane();
container.setLayout(new FlowLayout());
text=new JTextArea();
text.setLineWrap(true);
text.setWrapStyleWord(true);
text.setPreferredSize(new Dimension(350,150));
string=text.getText();
JButton showDialogBtn = new JButton("Add Text");
container.add(text);
container.add( showDialogBtn);
showDialogBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
jlabel l=new jlabel();
l.setSize(700,700);
l.setVisible(true);
}
});
}
public static void main(String[] args) {
// TODO code application logic here
Try t=new Try();
t.setSize(400,500);
t.setVisible(true);
}
String getArray()
{
return string ;
}
}
But the second class that is jlabel class is not showing the required result plz help in this regard
import java.awt.Container;
import java.awt.Font;
import javax.swing.*;
class jlabel extends JFrame {
Try t=new Try();
public jlabel(){
JFrame frame=new JFrame("jlabel");
JPanel jp1=new JPanel();
String string=t.getArray();
String[] labelStrings = string.split(" \\s*");
for (String labelString : labelStrings)
{
// create JLabels and add
JLabel label = new JLabel(labelString);
jp1.add(label);
frame.add(jp1);
}
}
}
waiting for reply thanks in advance
Regards,
The first class is decent, but the "jLabel" class had so many bugs. Please see below the one that works.
A summary of the issues in the jlabel class:
Another Try object was instantiated and this instance was used
You were creating a new JFrame even though you were subclassing it already.
No layout manager.
And so on...
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
class Label extends JFrame {
public Label(String string) {
super("jlabel");
JPanel jp1 = new JPanel();
jp1.setLayout(new BoxLayout(jp1, BoxLayout.Y_AXIS));
String[] labelStrings = string.split(" \\s*");
for (String labelString : labelStrings) {
// create JLabels and add
JLabel label = new JLabel(labelString);
jp1.add(label);
}
getContentPane().add(jp1);
}
}
In the Try class, initialize it this way:
Label l = new Label(text.getText());
The problem is that you call the getText() outside the actionPerformed() method. This method is run when the button is pressed, so if you want to get text then, you should call the method getText() within actionPerformed().
Your code gets text as soon as it is run and all it can find is nothing! So, that's what is pastes into the JLabel.

Categories

Resources