I am trying to make the input from a JTextField get split into an array of words when I press a button. When I press the button the program gives me a huge list of errors. The line of code that splits the sentence and where I call the class in the action listener is where eclipse says the error is coming from. I do not know why I am getting this error and I don't know how to fix. I have tried a lot of different things but they don't work. If you could explain why this isn't working or how to fix that would be great. Here is my code. Thank you for your help.
Main Class:
public class Control {
public static void main(String[] args) {
OpenWindow ow = new OpenWindow();
ow.window();
}
}
Second Class:
public class OpenWindow extends JFrame{
//Making variables
String input;
String firstWord2;
JButton jb = new JButton("Button");
JLabel jl = new JLabel();
JTextField jtf = new JTextField(40);
JPanel jp1 = new JPanel(new GridLayout(3,1));
SentenceSplitter ss = new SentenceSplitter();
public void window() {
//Make window pop up
setTitle("Project");
setSize(600, 300);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//Action Listener
jb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
input = jtf.getText();
//Error from line below
ss.split();
firstWord2 = ss.getFirstWord();
jl.setText(firstWord2);
}
});
//Add JFrames
jp1.add(jtf);
jp1.add(jb);
jp1.add(jl);
add(jp1);
}
//Make input accesible from other classes
String getInput() {
return input;
}
}
Third Class:
public class SentenceSplitter {
String firstWord;
public void split() {
OpenWindow ow2 = new OpenWindow();
//Get input
String sentence = ow2.getInput();
//Error from line below
String[] splitSentence = sentence.split(" ");
firstWord = splitSentence[0];
}
String getFirstWord() {
return firstWord;
}
}
In your code you
creating OpenWindow
In The OpenWindow object you are creating a SentenceSplitter and listening for a click
On the click you are calling the split method on the previously created SentenceSplitter
In split you are creating a new OpenWindow
What you maybe should do is pass the String as an input parameter to the split method
Related
I've been having some difficulty with this. Basically I want a user to enter a name in one Java class and have that data displayed in another. I try using gets but I keep getting 'null'. Also how would you do this if I wanted to get an int from my class (exampl) to display in my second class. Would it basically be the same?
Here's an example to show what I mean
1st class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Exampl extends JFrame implements ActionListener {
JLabel intro = new JLabel("Welcome What is your name?");
JTextField answer = new JTextField(10);
JButton button = new JButton("Enter");
final int WIDTH = 330;
final int HEIGHT = 330;
JLabel greeting = new JLabel("");
JButton next =new JButton("Next");
String name = answer.getText();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Exampl() {
super("Welcome");
setSize(WIDTH, HEIGHT);
setLayout(new FlowLayout());
add(intro);
add(answer);
add(button);
add(greeting);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == button) {
String greet = "Hello there" + name;
greeting.setText(greet);
add(next);
next.addActionListener(this);
if(source==next)
dispose();
new Hello();
}
}
public static void main(String[] args) {
Exampl frame= new Exampl();
frame.setVisible(true);
}
}
2nd class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Hello extends JFrame implements ActionListener {
String name;
JLabel hi = new JLabel("Nice to see you "+name);
JButton button = new JButton("Enter");
final int WIDTH = 330;
final int HEIGHT = 330;
JLabel greeting = new JLabel("");
JButton next =new JButton("Next");
public Hello() {
super("Welcome");
setSize(WIDTH, HEIGHT);
setLayout(new FlowLayout());
add(hi);
add(button);
add(greeting);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == button) {
String greet = "example " + name;
greeting.setText(greet);
add(next);
}
}
public static void main(String[] args) {
Exampl frame= new Exampl();
frame.setVisible(true);
}
}
My recommendations for you:
Don't extend JFrame, instead extend JPanel. See: Extends Frame vs creating it inside the program and Why shouldn't you extend JFrame and other components
Don't use multiple JFrames. See The use of multiple JFrames, good / bad practice? (BAD) instead you might want to try using Card Layout or JDialogs
What do you mean by extend? do you mean "public class Hello extends Exampl"? I'm new to java so I don't know much.
From that comment on another answer, you might want to learn the basics first in console applications before going into a GUI application which adds more complexity to your programs and thus your learning.
I'm planning on doing a project where I add the inputted name and a random int into a file so I can store it. Or would it make more sense to add that code into the same class?
From that comment, you can create a public method which returns the value in a JTextField in the format you need, then call that method from the other class, for example:
public String getUserName() {
return userNameField.getText();
}
public int getDigit() {
try {
return Integer.parseInt(digitField.getText());
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
return -1; //In case it's not a number, or return 0, or whatever you need
}
//------In another class------//
int digit = object1.getDigit(); //Where object1 is an instance of the other class where those methods are defined
Make a getter in first class and extends second one class then use super.getter();
im new to java but when I try to create a new frame all I get is a new window open with a white background on and none of the buttons or text boxes or labels get added. I don't know what im doing wrong?
private static void MainGui(){
MainInterfaces MainGui = new MainInterfaces();
MainGui.setTitle(name+ "'s Inbox");
MainGui.setSize(600,600);
MainGui.setVisible(true);
MainGui.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
MainInterfaces Class
class MainInterfaces extends JFrame implements ActionListener
{
private JButton send;
private JTextField to, subject, message;
private JLabel toLbl, subjectLbl, messageLbl;
public MainInterfaces() {
setLayout(new FlowLayout());
toLbl = new JLabel("Recipient: ");
subjectLbl = new JLabel("Subject: ");
messageLbl = new JLabel("Message: ");
to = new JTextField(32);
subject = new JTextField(32);
message = new JTextField(32);
send = new JButton("SEND");
add(toLbl);
add(to);
add(subjectLbl);
add(subject);
add(messageLbl);
add(message);
add(send);
}
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
}
}
Your code doesn't compile because you have a lot of errors (you have no main method, private static void MainGui(){ makes no sense etc.). Try this code instead which compiles and opens the GUI fine for me, showing everything as you want to (the buttons, the labels, etc.):
1) Class MainGui.java
class MainGui{
public static void main(String[] args) {
MainInterfaces MainGui = new MainInterfaces();
MainGui.setTitle("'s Inbox");
MainGui.setSize(600,600);
MainGui.setVisible(true);
MainGui.setDefaultCloseOperation(MainGui.EXIT_ON_CLOSE);
}
}
2) Class MainInterfaces.java
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class MainInterfaces extends JFrame implements ActionListener
{
private JButton send;
private JTextField to, subject, message;
private JLabel toLbl, subjectLbl, messageLbl;
public MainInterfaces() {
setLayout(new FlowLayout());
toLbl = new JLabel("Recipient: ");
subjectLbl = new JLabel("Subject: ");
messageLbl = new JLabel("Message: ");
to = new JTextField(32);
subject = new JTextField(32);
message = new JTextField(32);
send = new JButton("SEND");
add(toLbl);
add(to);
add(subjectLbl);
add(subject);
add(messageLbl);
add(message);
add(send);
}
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
}
}
I fixed it with one line of code. Just switch the "setVisible(true)" method to being inside the MainInterface class. However, make sure you put it as the last line of code inside the constructor, or it won't work. Basically, what was happening is that while the frame itself was being set to be true, the components were being added afterwards and were consequently not being shown. Putting "setVisible(true)" last makes sure all the components are added when you display the frame.
As a side note, you can add all methods you typed in the MainGUI class inside of MainInterface.
Here's MainGUI:
public class MainGUI
{
public static void main(String[] args)
{
new MainInterfaces();
}
}
Here's what MainInterfaces looks likes:
public class MainInterfaces extends JFrame implements ActionListener
{
private JButton send;
private JTextField to, subject, message;
private JLabel toLbl, subjectLbl, messageLbl;
public MainInterfaces()
{
setTitle("(Name)'s Inbox");
setSize(600,600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
toLbl = new JLabel("Recipient: ");
subjectLbl = new JLabel("Subject: ");
messageLbl = new JLabel("Message: ");
to = new JTextField(32);
subject = new JTextField(32);
message = new JTextField(32);
send = new JButton("SEND");
add(toLbl); add(to);
add(subjectLbl);
add(subject);
add(messageLbl);
add(message);
add(send);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
}
}
I am new to Java events, listeners and handlers. I can write code to create a button click event and a working result. However, I cannot get a simple enter event within a TextField to work.
Notice I do declare and call action listeners, input handlers, and define a resulting method execution. (I import java.awt and javax.swing libraries not shown below.)
public convertStringToCapitalLetters() {
setTitle("Convert String to All Capital Letters");
Container c = getContentPane();
c.setLayout(new GridLayout(2, 2));
inputLabel = new JLabel("Enter String: ", SwingConstants.LEFT);
stringTextField = new JTextField(50);
outputLabel = new JLabel("Capitalized String: ", SwingConstants.LEFT);
newStringLabel = new JLabel("", SwingConstants.RIGHT);
c.add(inputLabel);
c.add(stringTextField);
c.add(outputLabel);
c.add(newStringLabel);
inputHandler = new InputHandler();
stringTextField.addActionListener(inputHandler);
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
private class InputHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
String str, newStr;
str = stringTextField.getText();
newStr = str.toUpperCase();
newStringLabel.setText(String.format("", newStr));
}
}
public static void main(String[] args) {
convertStringToCapitalLetters capitalConv = new convertStringToCapitalLetters();
}
I think you just made a very small mistake which is to forget to specify the placeholder %s in String.format()
Try this:
newStringLabel.setText(String.format("%s", newStr));
You don't need the String.format("", newStr) call when setting the label's text, you can simply use
newStringLabel.setText(newStr);
.....
public void launchFrame(){
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(500,500);
f.setVisible(true);
f.setLocationRelativeTo(null);
JLabel nameL=new JLabel("Title", SwingConstants.LEFT);
String[] FormOptions = {"Choose","Text Field","Password Field","Button","Radio Button","Check Box","Drop Down Menu"};
String[] NormalOptions = {"Choose","Write Text", "Upload Picture", "Frame", "I-Frame"};
JTextField nameTF=new JTextField(10);
final JPanel comboPanel = new JPanel();
JLabel comboLbl = new JLabel("Form:");
JComboBox forms=new JComboBox(FormOptions);
comboPanel.add(comboLbl);
comboPanel.add(forms);
comboPanel.add(nameL);
comboPanel.add(nameTF);
final JPanel comboPanel1 = new JPanel();
comboPanel1.setVisible(false);
JLabel comboLbl1 = new JLabel("Normal HTML:");
JComboBox Normals = new JComboBox(NormalOptions);
comboPanel1.add(comboLbl1);
comboPanel1.add(Normals);
JButton HTML = new JButton( "Form or Normal");
HTML.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
comboPanel1.setVisible(!comboPanel1.isVisible());
comboPanel.setVisible(!comboPanel.isVisible());
}
});
f.add(comboPanel, BorderLayout.NORTH);
f.add(comboPanel1, BorderLayout.CENTER);
f.add(HTML,BorderLayout.SOUTH);
f.setVisible(true);
static String[] info = new String[500];//Here i need help
}
public static void main(String args[]){
BasicGuiTest gui = new BasicGuiTest();
gui.launchFrame();
}
//What Should i do here? I want to get whether the user is choosing form or Normal as
//well as its options..
private class GetInfo implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
info[i]=comboPanel.getSelectedItem
}
//Then i will output the string array to a text file..
or, you could avoid reinventing the wheel and use the built in java Preferences API?
http://docs.oracle.com/javase/1.4.2/docs/guide/lang/preferences.html
Okay, so first thing I would do is make info an ArrayList, instead of String Array.
public static List<String> info = new ArrayList<String>();
So you don't have to worry about the length of the string. Then you can append to the list using
info.append(comboPanel.getSelectedItem());
And here's code to write the list to a file.
FileWriter writer = new FileWriter(new File("C:/filename.txt"));
for(String line : info){
writer.write(line + "\n");
}
writer.close();
Does this answer your question?
How can I get chosen line from JTA ?
I suppose you can use getLineStartOffset(int line), and getLineEndOffset(int line) to substring out a particular line from the string returned from getText()
If you mean that you want to know what the user has selected (using the mouse/keyboard):
getSelectedText() should give you that.
Why not break the lines up into tokens. then if you know the line number you want, you can just access it via an array of Strings
public class JTALineNum extends JFrame{
JTextArea jta = null;
JButton button = null;
public JTALineNum(){
jta = new JTextArea();
button = new JButton("Hit Me");
button.addActionListener(new ButtonListener());
add(jta, BorderLayout.CENTER);
add(button, BorderLayout.SOUTH);
setSize(200,200);
setVisible(true);
}
private class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String text = jta.getText();
String[] tokens = text.split("\n");
for(String i : tokens){
System.out.println("Token:: " + i);
}
}
}
public static void main(String args[]){
JTALineNum app = new JTALineNum();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}