Void is invalid for the variable main? - java

How do i fix the error, Void is invalid for the variable main? I tried looking this up online but couldn't find anything. Also I am kind of new to this so please take it easy on me. I am learning as I go.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Text extends JFrame
{
JPanel jp = new JPanel();
JLabel jl = new JLabel();
JTextField jt = new JTextField("Month",30);
JTextField jt2 = new JTextField("Date",30);
JButton jb = new JButton("Enter");
public Text()
{
public static void main (String[] args); {
setTitle("Tutorial");
setVisible(true);
setSize(400, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
jp.add(jt);
jp.add(jt2);
jt.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String input = jt.getText();
jl.setText(input);
}
});
jp.add(jb);
jb.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String input = jt.getText();
String input2 = jt2.getText();
jl.setText(input);
jl.setText(input2);
int day = Integer.parseInt(input2);
if ((input.equals("Test")) && (input2.equals(day >= 26)))//||(input2.equals("27")))))
JOptionPane.showMessageDialog(null, "" , "" ,JOptionPane.PLAIN_MESSAGE,aries);
}
});
add(jp);
}
}
}

You have placed your main method inside the constructor for class Text. It belongs outside the constructor, at the same level as the constructor. Move it outside the constructor.
public class Text extends JFrame
{
JPanel jp = new JPanel();
JLabel jl = new JLabel();
JTextField jt = new JTextField("Month",30);
JTextField jt2 = new JTextField("Date",30);
JButton jb = new JButton("Enter");
public static void main (String[] args); {
setTitle("Tutorial");
setVisible(true);
setSize(400, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
...
}
public Text()
{
...
}
...
}

Java doesnt allow methods to be defined within other methods. Move the main method out of the Text constructor and remove the semi-colon which is terminating the statement early.
In addition you have a number of methods (e.g. setTitle and setVisible) which belong to the JFrame - these need to be moved to an instance code block to make them are accessible.
public class Text extends JFrame {
JPanel jp = new JPanel();
JLabel jl = ...
public Text() {
setTitle("Tutorial");
setVisible(true);
...
add(jp);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Text().setVisible(true);
}
});
}
}

Delete the ; after the main method declaration:
public static void main (String[] args);
^-------- Delete this
And put the main method out of the constructor:
public Text() {
...
}
public static void main(...) {
...
}

Related

Basic Multiply and Divide Java GUI

I am trying to have the number the user inputs into the frame either multiply by 2 or divide by 3 depending on which button they decide to click. I am having an hard time with working out the logic to do this. I know this needs to take place in the actionperformed method.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Quiz4 extends JFrame ActionListener
{
// Global Variable Declarations
// Our list input fields
private JLabel valueLabel = new JLabel("Enter a value between 1 and 20: ");
private JTextField valueField = new JTextField(25);
// create action buttons
private JButton multiButton = new JButton("x2");
private JButton divideButton = new JButton("/3");
private JScrollPane displayScrollPane;
private JTextArea display = new JTextArea(10,5);
// input number
private BufferedReader infirst;
// output number
private NumberWriter outNum;
public Quiz4()
{
//super("List Difference Tool");
getContentPane().setLayout( new BorderLayout() );
// create our input panel
JPanel inputPanel = new JPanel(new GridLayout(1,1));
inputPanel.add(valueLabel);
inputPanel.add(valueField);
getContentPane().add(inputPanel,"Center");
// create and populate our diffPanel
JPanel diffPanel = new JPanel(new GridLayout(1,2,1,1));
diffPanel.add(multiButton);
diffPanel.add(divideButton);
getContentPane().add(diffPanel, "South");
//diffButton.addActionListener(this);
} // Quiz4()
public void actionPerformed(ActionEvent ae)
{
} // actionPerformed()
public static void main(String args[])
{
Quiz4 f = new Quiz4();
f.setSize(1200, 200);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{ // Quit the application
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
} // main()
} // end of class
Here's something simpler, but it essentially does what you want out of your program. I added an ActionListener to each of the buttons to handle what I want, which was to respond to what was typed into the textbox. I just attach the ActionListener to the button, and then in the actionPerformed method, I define what I want to happen.
import java.awt.FlowLayout;
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.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Quizx extends JFrame {
private JPanel panel;
private JTextField textfield;
private JLabel ansLabel;
public Quizx() {
panel = new JPanel(new FlowLayout());
this.getContentPane().add(panel);
addLabel();
addTextField();
addButtons();
addAnswerLabel();
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setTitle("Quiz 4");
this.setSize(220, 150);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setVisible(true);
}
private void addTextField() {
textfield = new JTextField();
textfield.setColumns(9);
panel.add(textfield);
}
private void addButtons() {
JButton multButton = new JButton("x2");
JButton divButton = new JButton("/3");
panel.add(multButton);
panel.add(divButton);
addMultListener(multButton);
addDivListener(divButton);
}
private void addLabel() {
JLabel valueLabel = new JLabel("Enter a value between 1 and 20: ");
panel.add(valueLabel);
}
private void addAnswerLabel() {
ansLabel = new JLabel();
panel.add(ansLabel);
}
private void addMultListener(JButton button) {
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
ansLabel.setText(String.valueOf(Integer.parseInt(textfield.getText().trim()) * 2));
}
});
}
private void addDivListener(JButton button) {
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
ansLabel.setText(String.valueOf(Double.parseDouble(textfield.getText().trim()) /3));
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Quizx();
}
});
}
}
Hope that helps.

Everything works, except for buttons. GUI Java

Okay I can get text fields and normal text and even images to show but I can not get a button to show. I am not sure what I am doing wrong because I have done the same steps for the rest. Any help would be great thanks!
package EventHandling2;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import EventHandling.GUITest;
public class EventMain extends JFrame{
private JLabel label;
private JButton button;
public static void main(String[] args) {
EventMain gui = new EventMain ();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // when click x close program
//gui.setSize(600, 300);
gui.setVisible(true);
gui.setTitle("Button Test");
}
public void EventMain(){
setLayout(new FlowLayout());
button = new JButton ("click for text");
add(button);
label = new JLabel ("");
add(label);
Events e = new Events();
button.addActionListener(e);
}
public class Events implements ActionListener {
public void actionPerformed(ActionEvent e) {
label.setText("Now you can see words");
}
}
}
The problem is with the method: void EventMain()
Constructor has NO return type. Just remove "void". The code will work just fine.
Your actionListener(e) contains a minor control structure error:
public void actionPerformed(ActionEvent e) {
label.setText("Now you can see words");
}
Change to:
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
label.setText("Now you can see words");
}
}
First off, you have to remove void keyword in EventMain's constructor. Then, creating JPanel and add components into it, then add the JPanel to the JFrame.contentPane.
The following code should work:
public class EventMain extends JFrame {
private final JLabel label;
private final JButton button;
public static void main(String[] args) {
EventMain gui = new EventMain();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // when click x
// close program
gui.setSize(600, 300);
gui.setTitle("Button Test");
gui.setVisible(true);
}
public EventMain() {
// setLayout(new FlowLayout());
JPanel panel = new JPanel(new FlowLayout());
button = new JButton("click for text");
panel.add(button);
label = new JLabel("");
panel.add(label);
Events e = new Events();
button.addActionListener(e);
this.getContentPane().add(panel);
}
public class Events implements ActionListener {
public void actionPerformed(ActionEvent e) {
label.setText("Now you can see words");
}
}
}

How to handle Submit button of JFrame

I have a problem, I have been making a Swing application.
My question is about how to handle Jbutton like a JOptionPane, if it's possible?
I want handle all of the buttons similarly to JOptionpane button, but our message written in main function System.out.println("this line executes...how to prevent..");
This function is to display the message, until Jframe is visible.
Can anyone let me know how to prevent & how to handle button functionality? Especially when it executes further when I click the button.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.Border;
#SuppressWarnings("serial")
public class InputVerifierExample extends JPanel {
public static final Color WARNING_COLOR = Color.red;
private JTextField firstNameField = new JTextField(10);
private JTextField middleNameField = new JTextField(10);
private JTextField lastNameField = new JTextField(10);
JLabel name=new JLabel("Name:");
private JTextField[] nameFields = {
firstNameField,
middleNameField,
lastNameField };
private JLabel warningLabel = new JLabel(" ");
public InputVerifierExample() {
warningLabel.setOpaque(false);
JPanel namePanel = new JPanel();
namePanel.add(name);
MyInputVerifier verifier = new MyInputVerifier();
for (JTextField field : nameFields) {
field.setInputVerifier(verifier);
namePanel.add(field);
}
namePanel.add(new JButton(new SubmitBtnAction()));
setLayout(new BorderLayout());
add(namePanel, BorderLayout.CENTER);
warningLabel.setForeground(Color.red);
add(warningLabel, BorderLayout.NORTH);
}
private class SubmitBtnAction extends AbstractAction {
public SubmitBtnAction() {
super("Submit");
}
#Override
public void actionPerformed(ActionEvent e) {
// first check all fields aren't empty
for (JTextField field : nameFields) {
if (field.getText().trim().isEmpty()) {
return ; // return if empty
}
}
String name = "";
for (JTextField field : nameFields) {
name += field.getText() + " ";
field.setText("");
}
name = name.trim();
JOptionPane.showMessageDialog(InputVerifierExample.this, name, "Name Entered",
JOptionPane.INFORMATION_MESSAGE);
}
}
private class MyInputVerifier extends InputVerifier {
#Override
public boolean verify(JComponent input) {
JTextField field = (JTextField) input;
if (field.getText().trim().isEmpty()) {
warningLabel.setText("Please do not leave this field empty :"+name.getText());
warningLabel.setBackground(WARNING_COLOR);
//firstNameField.setText("sorry");
return false;
}
warningLabel.setText("");
warningLabel.setBackground(null);
return true;
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("InputVerifier Example");
frame.setSize(200, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new InputVerifierExample());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
createAndShowGui();
System.out.println("this line executes...how to prevent..");
}
}
Basically, you have something like this:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class TestButton {
protected void createAndShowGUI() {
JFrame frame = new JFrame("Test button");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Click me");
frame.add(button);
frame.setSize(200, 200);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestButton().createAndShowGUI();
}
});
System.err.println("Executed once the button has been clicked");
}
}
And you want the line System.err.println("Executed once the button has been clicked"); to be executed when the button is pressed (which is not the case here above).
The solution is actually very simple: you move the code to execute after the button click in another method (see below the proceed() method) and you invoke that line from an ActionListener:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class TestButton {
protected void createAndShowGUI() {
JFrame frame = new JFrame("Test button");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Click me");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
proceed();
}
});
frame.add(button);
frame.setSize(200, 200);
frame.setVisible(true);
}
protected void proceed() {
System.err.println("Executed once the button has been clicked");
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestButton().createAndShowGUI();
}
});
}
}
Well, the question is not very much clear,but from your comment,you dont want to do any thing till a JButton is clicked? Or you want to preform a task after clicking of a button?
If that is so, dont put your further code inside your main block, call a function from actionPerformed block.Something like this:
public void actionPerformed(ActionEvent e) {
// first check all fields aren't empty
for (JTextField field : nameFields) {
if (field.getText().trim().isEmpty()) {
return ; // return if empty
}
}
String name = "";
for (JTextField field : nameFields) {
name += field.getText() + " ";
field.setText("");
}
name = name.trim();
JOptionPane.showMessageDialog(InputVerifierExample.this, name, "Name Entered",
JOptionPane.INFORMATION_MESSAGE);
display();///////////this is the function containing further code
}
}
//this is display
public void display()
{
System.out.println("this line executes...how to prevent..");
}

Adding text to a label from another class - Simple Logic Issue

I have a label and a button in a class called FrameTest, when i press the button, a method named buttonpressed get's executed from the class Test. In this buttonpressed method i will set a text to the label found in the FrameTest class.
The problem i have is that, the text for the label is not getting set. The reason is that i am creating a separate object to call the buttonpressed method;
public void actionPerformed(ActionEvent arg0) {
Test t = new Test();
t.buttonpress();
}
and i am creating a separate object in the main method of the Test class to create the UI.
public static void main(String[] args) {
FrameTest f = new FrameTest();
f.mainScreen();
}
The full code as follows;
public class FrameTest extends JFrame {
private JPanel contentPane;
private JLabel lblLabel;
private FrameTest ft = this;
//private FrameTest frame;
/**
* Launch the application.
*/
public void mainScreen() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
//FrameTest frame = new FrameTest();
//setVisible(true);
FrameTest frame = ft;
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void writeLabel(String k){
this.lblLabel.setText(k);
}
public FrameTest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setExtendedState(JFrame.MAXIMIZED_BOTH);
//setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
lblLabel = new JLabel("LABEL");
contentPane.add(lblLabel, BorderLayout.CENTER);
JButton btnNewButton = new JButton("Press");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Test t = new Test();
t.buttonpress();
}
});
contentPane.add(btnNewButton, BorderLayout.WEST);
//pack();
setLocationByPlatform(true);
}
}
Test Class
public class Test {
public static void main(String[] args) {
FrameTest f = new FrameTest();
f.mainScreen();
}
public void buttonpress(){
FrameTest f = new FrameTest();
f.writeLabel("Button was pressed");
}
1) Dont extend JFrame class unnecessarily.
2) dont use setContentPane() unless thats what you want. Rather just simply JFrame#add(..).
3) Steer away from EventQueue and use SwingUtilities block rather
4) Dont forget to call JFrame#pack(); before setting JFrame visible.
5) Java naming convention is CamelCase so buttonPress() is correct not buttonpress()
Here is an example I made (basically your code fixed):
Test.java: (This is the main class which will create an instance of your FrameTest and has the method to change JLabel text)
import javax.swing.SwingUtilities;
public class Test {
private static FrameTest f;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
f = new FrameTest();
f.mainScreen();
}
});
}
void buttonPress() {
f.writeLabel("Hello");
}
}
FrameTest.java: (This class will show the JFrame and create a new instance of class Test to call buttonPress()):
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.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class FrameTest {
private JPanel panel;
private JLabel lblLabel;
private JFrame frame;
private void initComponents() {
frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
panel = new JPanel();
panel.setBorder(new EmptyBorder(5, 5, 5, 5));
panel.setLayout(new BorderLayout(0, 0));
lblLabel = new JLabel("LABEL");
panel.add(lblLabel, BorderLayout.CENTER);
JButton btnNewButton = new JButton("Press");
btnNewButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Test t = new Test();
t.buttonPress();
}
});
panel.add(btnNewButton, BorderLayout.WEST);
frame.add(panel);
frame.setLocationByPlatform(true);
frame.pack();
frame.setVisible(true);
}
public void writeLabel(String k) {
this.lblLabel.setText(k);
}
void mainScreen() {
initComponents();
}
}
Pass your FrameTest object to the buttonpress method and use it there, instead of creating a new object:
public void buttonpress(FrameTest f) {
f.writeLabel("Button was pressed");
}
Change the invocation of the method like so:
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Test t = new Test();
t.buttonpress(FrameTest.this);
}
});
You have to use FrameTest.this here, as you're inside of an anonymous class implementing ActionListener, so the normal this would reference to that anonymous class.
- Well the first approach is using Composition Principle, where you create an instance of FrameTest.java in Test.java class and then access the Label (use Getter Setters for this label in FrameTest) in FrameTest.java class using this instance.
- Second approach is a dirty and quick fix one, make the Label static in FrameTest.java class and directly set the value from Test.java class. Voila its done.....
- The reason your code is not working, cause you have created a very new instance of the FrameTest class. So now you either pass the FrameTest Object Reference Variable to buttonpress() method or make the label static.
Eg:
public class FrameTest extends JFrame {
private JPanel contentPane;
public static JLabel lblLabel;
.....
.....
}
Or
public void buttonpress(FrameTest f) {
f.writeLabel("Button was pressed");
}
/////////////////////////// Edited Part ///////////////////////////////////
import java.awt.BorderLayout;
import java.awt.EventQueue;
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.JPanel;
import javax.swing.border.EmptyBorder;
class FrameTest extends JFrame {
private JPanel contentPane;
private JLabel lblLabel;
private FrameTest ft = this;
public void mainScreen() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FrameTest frame = ft;
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void writeLabel(String k) {
this.lblLabel.setText(k);
}
public FrameTest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setExtendedState(JFrame.MAXIMIZED_BOTH);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
lblLabel = new JLabel("LABEL");
contentPane.add(lblLabel, BorderLayout.CENTER);
JButton btnNewButton = new JButton("Press");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Test t = new Test();
t.buttonpress(FrameTest.this); // Passing the current object to
// the Test class
// You can use just "this" , but
// as we are in an Anonymous
// Inner Class here,
// we have to use
// "Class_name.this"
}
});
contentPane.add(btnNewButton, BorderLayout.WEST);
// pack();
setLocationByPlatform(true);
}
}
public class Test {
public static void main(String[] args) {
FrameTest f = new FrameTest();
f.mainScreen();
}
public void buttonpress(FrameTest f) { // Receiving the reference to the
// current frame, but remember
// THOUGH IT SEEMS that we are passing the
// reference but still in
// Here and in Java its always pass
// by copy.( ie pass by value).
f.writeLabel("Button was pressed");
}
}
Just change your Test class like below
package com.test;
public class Test {
private static FrameTest f;
public static void main(String[] args) {
f = new FrameTest();
f.mainScreen();
}
public void buttonpress() {
f.writeLabel("Button was pressed");
}
}
The actual problem was
You created a FrameTest variable f in main and shown the UI to user.
Then on button press you again created another FrameTest instance f, which does not map the original/first f
Now i treat the variable as a class variable and it works as expected

Convert Java program with TextField to swing JTextField

This piece of code is a simplified version of a program I would convert to swing (using JTextField and DocumentListener). I have read some tutorials but I can't do it...
I shouldn't use global variables and I have to use some like getSource() (getDocument() in this case?), because in the original program the number of JTextField is variable (they are generated inside a for, so they haven't a "name"). This number depends on a value written in a text file.
import java.awt.*;
import java.awt.event.*;
class TestWindow extends Frame {
public TestWindow() {
Panel p = new Panel(new FlowLayout());
Label l = new Label("Temp");
TextField tf1 = new TextField();
TextField tf2 = new TextField();
tf1.addTextListener(new myTextListener(l));
tf2.addTextListener(new myTextListener(l));
p.add(tf1);
p.add(tf2);
tf1.setColumns(10);
tf2.setColumns(10);
p.add(l);
add(p);
pack();
setVisible(true);
}
class myTextListener implements TextListener {
Label input;
myTextListener(Label input) {
this.input = input;
}
public void textValueChanged(TextEvent e) {
input.setText(((TextField)(e.getSource())).getText());
}
}
}
public class Test {
public static void main(String[] args) {
new TestWindow();
}
}
This is a direct conversion of the code you posted to Swing that performs exactly the same task:
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import java.awt.FlowLayout;
public class TestWindow extends JFrame {
public TestWindow() {
JPanel p = new JPanel(new FlowLayout());
JLabel l = new JLabel("Temp");
JTextField tf1 = new JTextField(10);
JTextField tf2 = new JTextField(10);
tf1.getDocument().addDocumentListener(new MyDocumentListener(l));
tf2.getDocument().addDocumentListener(new MyDocumentListener(l));
p.add(tf1);
p.add(tf2);
p.add(l);
add(p);
pack();
setVisible(true);
}
class MyDocumentListener implements DocumentListener{
private JLabel label;
MyDocumentListener(JLabel label) {
this.label = label;
}
#Override
public void insertUpdate(DocumentEvent e) {
handleTextChange(e);
}
#Override
public void removeUpdate(DocumentEvent e) {
handleTextChange(e);
}
#Override
public void changedUpdate(DocumentEvent e) {
handleTextChange(e);
}
private void handleTextChange(DocumentEvent e) {
try {
label.setText(e.getDocument().getText(0,e.getDocument().getLength()));
} catch (BadLocationException ignored) {
//todo: handle exception properly although this should never happen
}
}
}
public static void main(String[] args) {
new TestWindow();
}
}
Please note that DocumentListener provides more control for handling text change events than the TextListener, but I chose to handle them with one single method in order to exactly match your example's functionality

Categories

Resources