I would like to make a gui where after i click a button i can paste a text with a lot of lines and submit that text.
Example of the code i have for create the button:
public class SimpleGui implements ActionListener {
JButton button;
SimpleGui g;
public static void main (String[] args) {
SimpleGui g = new SimpleGui();
g.go();
}
public void go(){
JFrame frame = new JFrame();
button = new JButton("Insert Player");
frame.getContentPane().add(button);
button.addActionListener(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
button.setText("Now paste the data! ");
}
}
Now where i have button.setText("Now paste the data! ");, what i want is to:
Create some kind of widget that allow me to insert 20 lines of text i've copied from a .txt document.
2) receive and manage the data that the user did put on the widget.
Can you help me?
Though your question is unclear but probably you're asking about a component where you can set your text. Use JTextArea as follows:
JTextArea textarea = new JTextArea("The initial text");
your_container.add(textarea);
Then whenever you want to get the text from your text area, use:
String data = textarea.getText();
If at runtime you want to set the textarea to some data you can:
textarea.setText("Your data here");
EDIT :
After the OP added the code, I think this is what he wants to achieve:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class SimpleGui implements ActionListener
{
JButton button;
SimpleGui g;
JTextArea textarea;
JFrame frame;
String data;
public static void main (String[] args)
{
SimpleGui g = new SimpleGui();
g.go();
}
public void go()
{
frame = new JFrame();
button = new JButton("Insert Player");
textarea = new JTextArea("Paste data here!");
frame.setLayout(new BorderLayout());
frame.getContentPane().add(button, BorderLayout.SOUTH);
button.addActionListener(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("Insert Player"))
{
button.setText("Now paste the data!");
frame.getContentPane().add(textarea, BorderLayout.CENTER);
}
else if(e.getActionCommand().equals("Now paste the data!"))
{
data = textarea.getText();
System.out.println(data);
}
}
}
Your text data is in the data variable. You can use it as you like. I've simply demonstrated that by printing it.
Related
I have made a program, which allows users to have as many text boxes as they want in which they can input a text string. I want to save each user input into different variables. I also want to print all of those variable or access the data stored in them when ever I want.
If you can help me that it would be really nice, thanks in advance. If you have any question please let me know in comment and I will answer them.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI
{
private JFrame frame;
private JButton button;
private JTextField tfield;
private String nameTField;
private int count;
public GUI()
{
nameTField = "tField";
count = 0;
}
private void displayGUI()
{
frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(0, 1, 2, 2));
button = new JButton("Add Another");
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
tfield = new JTextField();
tfield.setName(nameTField + count);
count++;
frame.add(tfield);
frame.revalidate();
frame.repaint();
}
});
frame.add(button);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new GUI().displayGUI();
}
});
}
}
What you're looking for is an ArrayList<String>.
Declare a private ArrayList<String> userStrings; where you have your private fields.
In your constructor, add userStrings = new ArrayList<String>();
And then when you receive a string, just add it into your list with userStrings.add(myNewString). (Use your String instead of myNewString)
ArrayLists are indexed like an array, but using a method get, so you can get the first item in your list by using userStrings.get(0).
Hello I would like to ask how can I call my Main menu screen from MainScreen? and kindly explain a little more details about Listener.
below is my prepared code:
public class MainScreen {
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.add(panel);
placeComponents(panel);
frame.setVisible(true);
}
private static void placeComponents(JPanel panel) {
JLabel WelcomeNote = new JLabel("Welcome");
panel.add(WelcomeNote);
JButton Start = new JButton("Start");
panel.add(Start);
//Insert action for Start button here
}
}
public class MainMenu {
public static void main(String[] args){
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.add(panel);
placeComponents(panel);
frame.setVisible(true);
}
private static void placeComponents(JPanel panel) {
JLabel menuLbl = new JLabel("Main Menu");
panel.add(menuLbl);
}
}
What is wrong?
You cannot have two main methods in a single file in Java.
Program
Here is a demo program to change windows.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
class First extends JFrame
{
JLabel jlb = new JLabel("Label in First Window");
JButton jb = new JButton("Next Window");
First()
{
super("First Windows");
//Set this frame
this.setSize(350,250);
this.setLayout(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Setting size of components
jlb.setBounds(10,10,200,40);
jb.setBounds(10,120,150,40);
add(jlb);
add(jb);
jb.addActionListener((e)->{
this.setVisible(false);
new Second();
});
setVisible(true);
}
}
class Second extends JFrame implements ActionListener
{
JLabel jlb = new JLabel("Label in Second Window");
JButton jb = new JButton("Prev. Window");
Second()
{
super("Second Window");
this.setSize(350,250);
this.setLayout(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Setting size of components
jlb.setBounds(10,10,200,40);
jb.setBounds(10,120,150,40);
add(jlb);
add(jb);
jb.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
this.setVisible(false);
new First();
}
}
class StartHere
{
public static void main(String[] args) {
Runnable r = ()->{
new First();
};
r.run();
}
}
Understanding the above program.
The StartHere class has a main method. It is just used for calling the first window you like. I could even call Second using new Second().
First and Second are similar codes.
Both of them have buttons. On each button (or JButton) I have added a method named addActionListner(this). This method fires up an ActionEvent which as you can see in Second class is captured by actionPerformed method. This method is declared in Functional Interface, ActionListener. The 'this' passed in Second class is you telling where the actionPerformed method is present in your code. The parameter is an ActionListener. Hence, you have to implement ActionListener for the class where you define actionPerformed.
Bonus
The First class doesn't seem to follow the norms described above. I passed a strange syntax. It is a new feature included in Java 8.
See this Oracle tutorial about Lambda Expressions.
I have a text game which has buttons. When a button is clicked, text appears. My text appears inside a jPanel, which is inside a jScrollPane. I would like my jPanel to automatically make more vertical space for my lines of text to be added. I have been doing it by hand but it is a lot more time consuming. Is there anyway to do this, or maybe pack a jPanel somehow. I am pretty new to this so if any extra information is needed for you to help me out feel free to ask. Thanks.
I would use a component that can do this automatically -- a JTextArea. It will automatically enlarge as more text is added.
If you need more specific help or a code example, please post your own small compilable and runnable test example program, and I can try to modify it.
You state:
I don't want to use a JTextArea because I don't want the user to be able to highlight or delete any of the text that was there in the first place.
No problem. Just make the JTextArea non-focusable and non-editable.
I have been using jLabels which are equal to "" and when a button is pressed, that jLabel is given a new value.
Try something like this:
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class AddNewLines extends JPanel {
private JTextArea textArea = new JTextArea(10, 15);
private JButton addLineBtn = new JButton(new AddLineAction("Add Line", KeyEvent.VK_A));
public AddNewLines() {
textArea.setEditable(false);
textArea.setFocusable(false);
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
textArea.setOpaque(false);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
add(scrollPane);
add(addLineBtn);
}
class AddLineAction extends AbstractAction {
private int count = 0;
public AddLineAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
if (count != 0) {
textArea.append("\n");
}
textArea.append("Line of Text: " + count);
count++;
}
}
private static void createAndShowGui() {
AddNewLines mainPanel = new AddNewLines();
JFrame frame = new JFrame("Add New Lines");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
How can i remove lines from a JTextArea one by one instead of all together?
I have a JTextArea which gets appended with string results from a thread, now i would like to remove one line at a time while the thread is executing.
You first need to decide what should trigger the line removal.
Should it be the addition of a new line, so that total line number is constant. If so then you should write your code to call the line removal code in the same location that where a new line is added.
Or should it be at a constant rate -- and if so, then you will want to use a Swing Timer for this.
Then you need to decide which line to remove. If not the first line, then you'll need to figure out how to calculate which line. The javax.swing.text.Utilities class can help you find out the start and finish location of every line of text in your JTextArea.
Edit
You ask:
the main concern is about how to remove it from the JTextArea, i have already calculated the start and end positions of a line that has to be deleted.But what function can assist in removing just that one line?
You would first get the JTextArea's Document by calling, getDocument()
Then you could call remove(int offs, int length) on the Document as per the Document API.
Try This :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class SwingControlDemo {
String [] m;
int i=0;
String append="";
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
Timer t;
public SwingControlDemo(){
prepareGUI();
}
public static void main(String[] args){
SwingControlDemo swingControlDemo = new SwingControlDemo();
swingControlDemo.showTextAreaDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java Swing Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showTextAreaDemo(){
headerLabel.setText("Control in action: JTextArea");
JLabel commentlabel= new JLabel("Comments: ", JLabel.RIGHT);
final JTextArea commentTextArea =
new JTextArea("This is a Swing tutorial "
+"\n to make GUI application in Java."+"\n to make GUI application in Java"+"\n to make GUI application in Java",5,20);
JScrollPane scrollPane = new JScrollPane(commentTextArea);
JButton showButton = new JButton("Show");
showButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s=commentTextArea.getText();
m=s.split("\n");
t.start();
}
});
t=new Timer(1000,new ActionListener(){
public void actionPerformed(ActionEvent e)
{
i++;
append="";
if(i<=m.length)
{
for(int j=i;j<m.length;j++)
{
append=append+m[j];
}
commentTextArea.setText(append);
}
else
{
t.stop();
}
}});
controlPanel.add(commentlabel);
controlPanel.add(scrollPane);
controlPanel.add(showButton);
mainFrame.setVisible(true);
}
}
I have created a frame in Java which has some textfields and buttons in it. Assuming that user wants more textfields (for example to add more data), I want to put a button and when a user clicks the button, then a new textfield should appear. then user can fill data in it and again by clicking that button another textfield should appear.
How can I do this ? What code I need to write for the button to show more and more text fields by clicking button?
Thank you !
It would be wise that instead of adding components to your JFrame directly, you add them to a JPanel. Though related to your problem, have a look at this small example, hopefully might be able to give you some hint, else ask me what is out of bounds.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JFrameExample
{
private JFrame frame;
private JButton button;
private JTextField tfield;
private String nameTField;
private int count;
public JFrameExample()
{
nameTField = "tField";
count = 0;
}
private void displayGUI()
{
frame = new JFrame("JFrame Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(0, 1, 2, 2));
button = new JButton("Add JTextField");
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
tfield = new JTextField();
tfield.setName(nameTField + count);
count++;
frame.add(tfield);
frame.revalidate(); // For JDK 1.7 or above.
//frame.getContentPane().revalidate(); // For JDK 1.6 or below.
frame.repaint();
}
});
frame.add(button);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new JFrameExample().displayGUI();
}
});
}
}
Supposing that you have a main container called panel and a button variable button which is already added to panel, you can do:
// handle the button action event
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// create the new text field
JTextField newTextField = new JTextField();
// add it to the container
panel.add(newTextField);
panel.validate();
panel.repaint();
}
});
When adding the new text field, you may need to mention some layout related characteristics, depending on the layout manager you are using (for instance if you use GridBagLayout, you will need to specify the constraints).