How to change `JTextArea` contents using `JTextArea` instance field? - java

I have an object ReminderGUI which has a JTextArea field. ReminderGUI represents an app which lets save and display reminders. When getReminderButton is clicked I want the app to find the reminder which was previously saved for this date and display it in the JTextArea (I'm not showing this functionality in the code snippet).
I'm having trouble with changing JTextArea text and the code below demonstrates it. Once getReminderButton is clicked then getReminderButtonHandler() is supposed to initialize a new blank JTextArea and then append it to some new text here. Why doesn't this work?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ReminderGUI extends JFrame implements ActionListener{
private JButton getReminderButton;
private JTextArea reminderTextArea;
public ReminderGUI() {
super();
super.setLayout(new BorderLayout());
this.reminderTextArea = new JTextArea("Enter text");
this.getReminderButton = new JButton("Get reminder");
JPanel southPanel = new JPanel();
southPanel.add(getReminderButton, BorderLayout.SOUTH);
super.add(southPanel, BorderLayout.SOUTH);
super.add(reminderTextArea, BorderLayout.CENTER);
this.getReminderButton.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == this.getReminderButton) {
this.getReminderButtonHandler();
}
}
private void getReminderButtonHandler() {
this.reminderTextArea = new JTextArea("");
this.reminderTextArea.append("some new text here");
}
public static void main(String[] args) {
ReminderGUI rmg = new ReminderGUI();
rmg.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
rmg.setSize(500, 300);
rmg.setVisible(true);
}
}

The problem is in this line: this.reminderTextArea = new JTextArea("Enter text"); you're creating a new TextArea
You can set it using the set method, like this: reminderTextArea.setText(text);

Related

How do I create an array of JTextField and retrieve the text from an array of String?

I am quite new to Java and learning as a student. I hope you can understand me.
As you can see from the code below, I've only coded the frame and the label. The user should be able to write some song recommendations. There should be at least a few text fields created by an array. When the user makes changes, the new text should be displayed using JOptionPane.WARNING_MESSAGE.
I need some guidance on how I can create an array of JTextField and retrieve the text from an array of String. In addition, how can I use JOptionPane to display all of the text?
Thank you.
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
class TextFrame extends JFrame
{
private final JLabel cLabel;
public TextFrame()
{
super("Hello there!");
setLayout(new FlowLayout());
cLabel = new JLabel("Please write some song recommendations.");
cLabel.setToolTipText("Write below.");
add(cLabel);
}
}
public class TestFrame
{
public static void main (String [] args)
{
TextFrame frame = new TextFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 400);
frame.setVisible(true);
}
}
You should make an actionListener that checks to see if you have typed anything. You could have another listener or Mnemonic so when you hit enter it will update everything. When you hit enter, you could get the text from the JTextField or JTextArea and then save that into an array of Strings (ie String[] stringArray = new String[<num of items>] This way you could just have one textField and you will be able to store everything in a String[] instead of an array of Text Fields? I hope this helps!
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class framearray2 extends JFrame implements ActionListener
{
JCheckBox c1[];
JTextField t1[];
int i;
framearray2(String p)
{
super(p);
c1=new JCheckBox[2];
t1=new JTextField[2];
for(i=0;i<2;i++)
{
t1[i]=new JTextField(40);
c1[0]=new JCheckBox("Singing");
c1[0].setBackground(Color.red);
c1[1]=new JCheckBox("Cricket",true);
}
for(i=0;i<2;i++)
{
add(t1[i]);
add(c1[i]);
t1[i].addActionListener(this);
}
setLayout(new FlowLayout());
setFont(new Font("Arial",Font.ITALIC,40));
}
public void actionPerformed(ActionEvent e)
{
for(i=0;i<2;i++)
{
if(e.getSource().equals(t1[0]))
{
t1[0].setBackground(Color.red);
}
if(e.getSource().equals(t1[1]))
{
t1[1].setBackground(Color.blue);
}
}
}
public static void main(String s[])
{
framearray2 f1=new framearray2("hello");
f1.setSize(600,500);
f1.setVisible(true);
}
}

How to copy JButton action and change its references to underlying objects?

The following example creates a JFrame with JButton, JTextField and JLabel.
When the button is pressed it increments the value in the text field and label.
This example also creates a 2nd JFrame that is a copy of the first.
The button, text field and label is copied as well.
The issue at hand is the button on the copied frame still updates the text field and label on the original. The 'why' is fairly obvious and is because the code makes specific reference to the text field and label.
Although this isn't written in the best manner but it is a great example of the scenario in which I am addressing.
The objective is, without a major rewrite, what would be the least invasive way to have the copied button action update the copied test field and label instead of the original?
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.JTextField;
class ButtonTextFieldLabel extends JFrame
{
JButton bnt1 = new JButton("B1");
JTextField tf1 = new JTextField("1");
JLabel lbl1 = new JLabel("100");
public ButtonTextFieldLabel()
{
super("Main Frame");
setLayout(null);
bnt1.setBounds(50,100,120,40);
tf1.setBounds(300,100, 80,40);
lbl1.setBounds(200,100,80,40);
bnt1.addActionListener(new ListenerHolder(this));
add(bnt1);
add(tf1);
add(lbl1);
setSize(500,500);
makeCopy(this);
setVisible(true);
}
private void makeCopy(ButtonTextFieldLabel originalObj)
{
JFrame copyFrame = new JFrame();
copyFrame.setTitle("Copy of " + originalObj.getTitle());
copyFrame.setSize(originalObj.getSize());
copyFrame.setLocation(originalObj.getX()+100, originalObj.getY()+100);
copyFrame.setLayout(null);
JButton copyBnt1 = new JButton();
copyBnt1.setBounds(originalObj.bnt1.getBounds());
copyBnt1.setLabel(originalObj.bnt1.getLabel());
copyFrame.add(copyBnt1);
for (ActionListener al : originalObj.bnt1.getActionListeners())
{
copyBnt1.addActionListener(al);
}
JTextField copyTf1 = new JTextField();
copyTf1.setBounds(originalObj.tf1.getBounds());
copyTf1.setText(originalObj.tf1.getText());
JLabel copyLbl1 = new JLabel();
copyLbl1.setBounds(originalObj.lbl1.getBounds());
copyLbl1.setText(originalObj.lbl1.getText());
copyFrame.add(copyBnt1);
copyFrame.add(copyTf1);
copyFrame.add(copyLbl1);
copyFrame.setVisible(true);
}
public void runThis()
{
tf1.setText( Integer.toString(Integer.parseInt(tf1.getText())+1) );
lbl1.setText( Integer.toString(Integer.parseInt(lbl1.getText())+1) );
}
}
class ListenerHolder implements ActionListener
{
ButtonTextFieldLabel ph;
public ListenerHolder(ButtonTextFieldLabel ph)
{
this.ph = ph;
}
#Override
public void actionPerformed(ActionEvent arg0)
{
ph.runThis();
}
}
public class TestBTL
{
public static void main(String[] args){
new ButtonTextFieldLabel();
}
}
You already know the reason for the problem -- you're copying the original ActionListener, complete with its reference to the original GUI components. The overall solution is not to copy the action listener but rather to create your GUI's to hold and maintain their own unique state. One solution is rather than try to copy components via kludge, to create a self-contained GUI object that holds and updates its own state. You can create multiple GUI's using a factory method if desired.
For example:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class TestBtl2 {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndDisplayFrame("Frame 1").setVisible(true);
createAndDisplayFrame("Frame 2").setVisible(true);
});
}
// Factory method
private static JFrame createAndDisplayFrame(String text) {
BtlPanel btlPanel = new BtlPanel();
JFrame frame = new JFrame(text);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(btlPanel);
frame.pack();
frame.setLocationByPlatform(true);
return frame;
}
}
class BtlPanel extends JPanel {
private int value = 0;
private JButton button1 = new JButton(new ButtonAction("Button 1"));
private JLabel label1 = new JLabel("00");
private JTextField textField1 = new JTextField("00");
public BtlPanel() {
textField1.setFocusable(false);
add(button1);
add(Box.createHorizontalStrut(20));
add(label1);
add(Box.createHorizontalStrut(20));
add(textField1);
setPreferredSize(new Dimension(300, 100));
}
public void incrementValue() {
value++;
String text = String.format("%02d", value);
label1.setText(text);
textField1.setText(text);
}
private class ButtonAction extends AbstractAction {
public ButtonAction(String name) {
super(name);
}
#Override
public void actionPerformed(ActionEvent e) {
incrementValue();
}
}
}
Side Recommendations:
While null layouts and setBounds() might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.
Check out: The Use of Multiple JFrames, Good/Bad Practice?

Content not displaying in JFrame

I have just started working on a small GUI for an assignment, but upon launching it, nothing apart from the title is visible.
My code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Property extends JFrame
{
/*private String propertyType;
private String propertyAddress;
private double propertyArea;
private int numOfBedrooms;
private int numOfGarages;
private int numOfToilets;
private String ownerGivenName;
private String ownerSurname;
private String ownerdateOfBirth;*/
JButton PropertySaleButton = new JButton("Add New Property");
JButton PurchaseOfferButton = new JButton("Submit Purchase Offer");
public Property()
{
setLayout (new FlowLayout());
add(PropertySaleButton);
add(PurchaseOfferButton);
}
public static void main(String[] args)
{
EventQueue.invokeLater(() ->
{
JFrame frame = new JFrame("CQ Real Estate");
/*Image img = new ImageIcon("icon.gif").getImage();
setIconImage(img);*/
frame.setSize(450, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
}
}
If anyone can tell me what I'm missing it would be greatly appreciated.
Property is the class that hold your "GUI design" but didn't use it. You build a JFrame. Instead, create a Property instace
JFrame frame = new Property();
You will need to adapt a bit your code (to add the title).
Try changing your code to:
this.getContentPane.add(PropertySaleButton);
this.getContentPane.add(PurchaseOfferButton);

Using two Frames in a GUI

I'm developing a GUI that is kinda like a menu to control an assembly line. When the program runs, it shows up the window with the first set of buttons. Clicking in a button should make this window disappear and should make another window appear with the previously chosen menu. How do I implement the action on the button? Both menus are in different classes and there's an extra class with the main function that, for now, only creates new objects and set the visibility of the first window to true.
Here are both of them:
Main one:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class InfInd {
public static void main(String[] args) {
Cliente c = new Cliente();
c.setVisible(true);
}
}
The first Menu:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Cliente extends JFrame implements ActionListener {
public JLabel titulo;
public JButton ordens;
public JButton listaordens;
public JButton stats;
public JButton desc;
public JButton sair;
public Cliente() {
titulo = new JLabel("Menu Cliente");
ordens = new JButton ("Ordens");
listaordens = new JButton("Lista Ordens");
stats = new JButton ("Estatísticas");
desc = new JButton ("Peças Descarregadas");
sair = new JButton ("Sair");
setLayout(null);
Dimension size1 = titulo.getPreferredSize();
Dimension size2 = ordens.getPreferredSize();
Dimension size3 = listaordens.getPreferredSize();
Dimension size4 = stats.getPreferredSize();
Dimension size5 = desc.getPreferredSize();
Dimension size6 = sair.getPreferredSize();
titulo.setBounds(100, 50, size1.width, size1.height);
ordens.setBounds(100, 100, size2.width, size2.height);
listaordens.setBounds(100, 150, size3.width, size3.height);
stats.setBounds(100, 200, size4.width, size4.height);
desc.setBounds(100, 250, size5.width, size5.height);
sair.setBounds(100, 300, size6.width, size6.height);
sair.addActionListener(this);
add(titulo);
add(ordens);
add(listaordens);
add(stats);
add(desc);
add(sair);
setSize(500, 500);
setTitle("Teste");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent out){
System.exit(0);
}
}
The second menu is similar to this one, only with different names for the buttons. The idea is to, for now, just show up the second menu by clicking on the "Ordens" button. Sorry of this seems quite noobish but I've only started with Java GUIs yesterday. Thank you all.
You could do something like this
public class MyFrame extends JFrame {
private JButton jbt = new JButton("Open Window");
private AnotherFrame jfrm = new AnotherFrame(); // another frame
public MyFrame(){
add(jbt);
add(jfrm); // add frame
jbt.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
jfrm.setVisibility(true); // when button clicked, set
} // visibility for other frame true
});
}
private AnotherFrame extends JFrame {
public AnotherFrame(){
}
}
}

ActionListener to call another Jpanel from a Jpanel

I am trying to make a Wizard without using libraries that I Have seen to easily make wizards lol its for a project, I have done the layout and frames and panels, what am having trouble with is when I click the "-->" it does not go to panel2 , nothing happens, it does store the name but thatt is it. Could anybody help me out?
EDIT it works now :) now am having trouble displaying the second "panel2" it goes into nothing after i click the arrow. lol
package project4;
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class WizardGUI extends JFrame implements ActionListener {
private JLabel enterName;
private JTextField name;
private JButton prev, fow;
private String storeName = "";
WizardGUI(){
super("Wizard");
name();
}
void name()
{
JPanel FPanel = new JPanel();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new FlowLayout());
// JLabel textLabel = new JLabel("lol");
//textLabel.setPreferredSize(new Dimension(300, 100));
// frame.getContentPane().add(textLabel);
//prev = new JButton("<--");
fow = new JButton ("-->");
this.add(FPanel);
enterName = new JLabel("Enter Your Name: ");
name = new JTextField(10);
enterName.setBounds(60, 30,120,30);
name.setBounds(80,60,130,30);
this.setSize(300,390); //set frame size
this.setVisible(true);
FPanel.add(enterName);
FPanel.add(name);
//FPanel.add(prev);
FPanel.add(fow);
fow.addActionListener(this);
}
void enter()
{
JPanel panel2 = new JPanel();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new FlowLayout());
//prev = new JButton("<--");
fow = new JButton ("-->");
this.add(panel2);
enterName = new JLabel("Enter Your Name: ");
name = new JTextField(10);
enterName.setBounds(60, 30,120,30);
name.setBounds(80,60,130,30);
this.setSize(300,390); //set frame size
this.setVisible(true);
panel2.add(enterName);
panel2.add(name);
//FPanel.add(prev);
panel2.add(fow);
fow.addActionListener(this);
this.getContentPane().removeAll();
validate();
repaint();
this.add(panel2);
}
void add()
{
}
void select()
{
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == fow) {
storeName = name.getText();
enter();
//JOptionPane.showMessageDialog(null, "hello " + storeName);
}
}
}
Thanks :)
You both extend JFrame and you create your own JFrame. This means you have two instances of JFrame. One is your WizardGUI class which I'm guessing is referenced in your main somewhere and the other is a local variable named frame.
In the constructor you are building everything in the frame instance. In the Sscreen method you are modifying the this instance so nothing that you've done to the frame instance is modified.
You should get rid of the local variable frame and replace all references to it with this.
Also, you should call super("Wizard") as your first line in the WizardGUI constructor. Calling parent constructors is important and everyone forgets to do that.

Categories