Input from JOptionPane, output in JTextArea in JFrame? - java

How do you make a JTextArea in the JFrame that accepts multiple input from JOptionPane? Is that even possible? Thanks to whoever helps!

Create a new class and extend JFrame
add a JTextArea to it. Make it a member variable
add a button to the frame. In the action method call open the input dialog
when the dialog returns, append the text to the JTextArea using its append method (don't forget to check for empty/null string)
Here is a sample program:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class InputTest extends JFrame {
private final JTextArea textarea;
private final JButton button;
public InputTest(String title) {
super(title);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textarea = new JTextArea(5,30);
button = new JButton("new input");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String input = JOptionPane.showInputDialog(InputTest.this, "Please enter some text");
if((input != null) && !input.isEmpty()) {
textarea.append(input);
textarea.append(System.getProperty("line.separator"));
}
}
});
JPanel p = new JPanel(new BorderLayout());
p.add(textarea, BorderLayout.NORTH);
p.add(button, BorderLayout.SOUTH);
this.getContentPane().add(p);
}
public static void main(String[] args) {
InputTest it = new InputTest("Input Test");
it.setSize(200, 200);
it.setVisible(true);
}
}

Related

How to call this method into my other file?

I want to be able to call the Introduction.Intro() method into my main file code, but it tells me I am unable to call a non-static method intro from a static context. Since I am still fairly new to coding I'm not entirely sure what the problem is. I've added my codes down below. I've tried countless online methods but sadly none have seemed to work.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Start extends JFrame implements ActionListener
{
private JFrame Main;
private JPanel PanelA, PanelB, PanelC;
private JLabel Text, ImageL;
private JButton Button;
private ImageIcon Image;
public Start ()
{
//Button
Button = new JButton("Start");
Button.addActionListener(new ButtonListener());
//Text
Text = new JLabel("Welcome To The Game"); //ADD NAME OF THE GAME
//Image
Image = new ImageIcon(getClass().getResource("download.jfif")); //ADD THE IMAGE FOR WELCOME
ImageL = new JLabel(Image);
//Top Panel (PanelA) - Image
PanelA = new JPanel();
PanelA.setBorder(BorderFactory.createEmptyBorder(0,200,150,200));
PanelA.setLayout(new FlowLayout(FlowLayout.CENTER));
PanelA.add(ImageL);
//Middle Panel (PanelB) - Text
PanelB = new JPanel();
PanelB.setBorder(BorderFactory.createEmptyBorder(50,200,10,200));
PanelB.setLayout(new FlowLayout(FlowLayout.CENTER));
PanelB.add(Text);
//Bottom Panel (PanelC) - Buttons
PanelC = new JPanel();
PanelC.setBorder(BorderFactory.createEmptyBorder(0,200,20,200));
PanelC.setLayout(new FlowLayout(FlowLayout.CENTER));
PanelC.add(Button);
//Main Frame
Main = new JFrame ();
Main.add(PanelA, BorderLayout.NORTH);
Main.add(PanelB, BorderLayout.CENTER);
Main.add(PanelC, BorderLayout.SOUTH);
Main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Main.setTitle("GAME TITLE"); //ADD THIS LATER
Main.pack();
Main.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent ae)
{
}
public class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == Button)
{
Introduction.Intro1(); //THESE LINE RIGHT HERE
return null; //THESE LINE RIGHT HERE
}
}
}
public static void main(String[] args)
{
new Start();
}
}
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Introduction
{
private JFrame Main;
private JPanel PanelD;
private JLabel Text, ImageL;
private JButton Button;
private ImageIcon Image;
public void Intro()
{
Image = new ImageIcon(getClass().getResource("guy.jfif"));
ImageL = new JLabel(Image);
PanelD = new JPanel();
PanelD.setBorder(BorderFactory.createEmptyBorder(0,100,10,100));
PanelD.setLayout(new FlowLayout(FlowLayout.CENTER));
PanelD.add(ImageL);
PanelD.setVisible(true);
Main.add(PanelD, BorderLayout.NORTH);
}
}
EDIT: So I made another method in the Introduction class where I added this line of code, it managed to fix the error, however, the panel isn't being saved and my JFrame is outputting blank.
public static JFrame Intro1()
{
Introduction M = new Introduction();
return M;
}
If you are looking to initialize the Introduction class in main method of Start class, You can add belo code in main method after Start()
Introduction M = new Introduction();
You main method becomes :
public static void main(String[] args)
{
new Start();
Introduction M = new Introduction();
m.Intro
}
Looking at this set of code, It looks like there is incompatible issue, as you have declare JFrame as return type, while you are returning instance of Introduction.
public static JFrame Intro1()
{
Introduction M = new Introduction();
return M;
}

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

How do i print a line of text when typing a certain number/word with a JTextField and JTextArea (JAVA)

MY CODE
package pack.TAgame;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class AL_Test {
public static void main(String[] args){
//JFrame
JFrame Frame = new JFrame("AL Test");
Frame.setSize(720,480);
Frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Frame.setVisible(true);
Frame.setResizable(false);
//Text Area
JTextArea textArea = new JTextArea();
textArea.setBackground(Color.BLACK);
textArea.setForeground(Color.GRAY);
JLabel jl = new JLabel();
Frame.add(textArea);
textArea.setEditable(false);
//Text Field
JTextField jt = new JTextField(50);
JPanel jp = new JPanel();
jp.add(jt);
Frame.add(jt, BorderLayout.SOUTH);
class UserInput extends JFrame implements ActionListener{
public UserInput() {
}
public void actionPerformed(ActionEvent e) {
JTextField jt = new JTextField();
JTextArea textArea = new JTextArea();
jt.addActionListener(this);
String text = jt.getText();
textArea.append("\n>What does the scouter say about his power level?");
}
}
}
}
This maybe a little like my other post...(In my code for the actionlistener part I gave up and I might have some useless code in it)
so basically I want a JTextField that when I type a certain command to print something into my JTextArea. (Without the use of a button (i.e. Press enter))
Start with the TextDemo.java code from the Swing tutorial on How to Use Text Fields. This example does exactly what you want:
it adds an ActionListener to the text field. The ActionListener is invoked when Enter is pressed and focus is on the text field.
The ActionListener will take the text from the text field and append it to a text area.
As a bonus you will also learn how to better structure your code by adding the components to a panel and then add the panel to the frame. The variables will be defined in the class as well.

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