I have two java classes
SortsGui.java
import javax.swing.*;
import java.awt.*;
import net.miginfocom.swing.MigLayout;
import Sorts.*;
import javax.swing.event.*;
import java.awt.event.*;
public class SortsGui
{
JFrame myMainWindow = new JFrame("Sorts");
JPanel sortPanel = new JPanel();
MyMenuBar mbr = new MyMenuBar();
//first panel components
JTextField txtField = new JTextField();
JTextField txtField2 = new JTextField();
JTextField txtField3 = new JTextField();
JTextField txtField4 = new JTextField();
JTextField txtField5 = new JTextField();
JTextField txtField6 = new JTextField();
JTextField txtField7 = new JTextField();
JTextField txtField8 = new JTextField();
JTextField txtField9 = new JTextField();
String sortsArray[]={"01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20"};
JComboBox sortComboBox = new JComboBox(sortsArray);
//end first panel
public void runGUI()
{
myMainWindow.setBounds(10, 10, 800, 800);
myMainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myMainWindow.setLayout(new GridLayout(1,1));
createSortTestPanel();
myMainWindow.getContentPane().add(sortPanel);
myMainWindow.setJMenuBar(mbr);
myMainWindow.setVisible(true);
}
public void createSortTestPanel()
{
MigLayout layout = new MigLayout("" , "[grow]");
sortPanel.setLayout(layout);
sortPanel.add(txtField,"growx");
sortPanel.add(txtField2,"growx");
sortPanel.add(txtField3,"growx");
sortPanel.add(txtField4,"growx");
sortPanel.add(txtField5,"wrap,growx");
sortPanel.add(txtField6,"growx");
sortPanel.add(txtField7,"growx");
sortPanel.add(txtField8,"growx");
sortPanel.add(txtField9,"growx");
selectNothing();
}
public void selectNothing()
{
sortPanel.addAncestorListener(new RequestFocusListener(false));
}
public static void main(String[] args)
{
SortsGui sG = new SortsGui();
sG.runGUI();
}
class RequestFocusListener implements AncestorListener
{
private boolean removeListener;
public RequestFocusListener()
{
this(true);
}
public RequestFocusListener(boolean removeListener)
{
this.removeListener = removeListener;
}
#Override
public void ancestorAdded(AncestorEvent e)
{
JComponent component = e.getComponent();
component.requestFocusInWindow();
if (removeListener)
component.removeAncestorListener( this );
}
#Override
public void ancestorMoved(AncestorEvent e) {}
#Override
public void ancestorRemoved(AncestorEvent e) {}
}
}
MyMenuBar.java
package Sorts;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.io.*;
import java.lang.*;
public class MyMenuBar extends JMenuBar
{
JLabel lblSorts = new JLabel("Select amount of numbers to sort");
String sortsArray[]={"01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20"};
JComboBox sortComboBox = new JComboBox(sortsArray);
SortsGui sG= new SortsGui();
public MyMenuBar()
{
setBorderPainted(true);
makePopUpMenu();
}
void makePopUpMenu()
{
add(lblSorts);
sortComboBox.addItemListener(new sortComboBoxChanged());
add(sortComboBox);
}
class sortComboBoxChanged implements ItemListener
{
#Override
public void itemStateChanged(ItemEvent e)
{
System.out.println(sortComboBox.getSelectedItem());
sG.selectNothing();
System.out.println("Losing Focus");
}
}
}
In this you can see that I have tried to call SortsGui into MyMenuBar however that produces a cannot find symbol error for SortsGui. So is it possible to call a class from a parent directory? And if it is could someone please correct my error?
Parent Directory
Sorts Directory
You need create a new package for SortsGui as it is in the default package and there is ambiguity.
e.g.:
package abc;
class sortGui {
}
Then you have to import the package in Mymenubar
Classes in the default package cannot be imported by classes in packages.
Related
What I want to design is with this code is when I enter any text into the Textfield, then hit the button to save it. So I've been trying few ways, but I could not solve that command prompt shows me an empty space...
When I tried the source code into the "main" method, it was working well like what I expected..
Here is my source code:
package test;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
class testListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String s = new TxtField().savedTxt();
System.out.println("ActionPerformed :" + s);
}
}
public class TxtField {
static JTextField jtf;
JFrame jf;
JButton jbtn;
static String temp;
public TxtField() {
jtf = new JTextField(10);
jf = new JFrame("JFrame");
jbtn = new JButton("OK");
jf.add(jtf);
jf.add(jbtn);
jf.setVisible(true);
jf.setSize(300, 300);
jf.setLayout(new GridLayout(2, 0));
jf.setLocationRelativeTo(null);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jtf.addActionListener(new testListener());
jbtn.addActionListener(new testListener());
}
public String savedTxt() {
temp = jtf.getText();
System.out.println("Temp is :" + temp);
return temp;
}
public static void main(String[] args) {
new TxtField();
}
}
You are creating a new TxtField when the action is called, instead of referencing the one that invoked the action:
String s = new TxtField().savedTxt();
Try making TxtField itself the ActionListener:
public class TxtField implements ActionListener
Then reference the current instance:
jtf.addActionListener(this);
jbtn.addActionListener(this);
Then reference the JTextField in the current instance:
String s = savedTxt();
You are close...You can do something like this:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class Test {
Test t;
static JTextField jtf;
JFrame jf;
JButton jbtn;
static String temp;
public Test() {
t = this;
class testListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String s = jtf.getText();
t.savedTxt();
System.out.println("ActionPerformed :" + s);
}
}
jtf = new JTextField(10);
jf = new JFrame("JFrame");
jbtn = new JButton("OK");
jf.add(jtf);
jf.add(jbtn);
jf.setVisible(true);
jf.setSize(300, 300);
jf.setLayout(new GridLayout(2, 0));
jf.setLocationRelativeTo(null);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jtf.addActionListener(new testListener());
jbtn.addActionListener(new testListener());
}
public String savedTxt() {
temp = jtf.getText();
System.out.println("Temp is :" + temp);
return temp;
}
public static void main(String[] args) {
Test t1 = new Test();
}
}
The problem is you are creating a new Instance of your class in the actionPerformed event instead of using the one you already have...
String s = new TxtField().savedTxt();
This is calling savedTxt() on the new instance instead of the one you already have which has the text you typed.
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.
I want to display a list of strings in a window and i tried to use a JPanel surounded by JScrollPane because the size of the strings list is unknown. The problem is that the window is displaying the text Horizontally and i want to be displayed line after line. How to fix this? This is the code i've written so far.
package interface_classes;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
public class ErrorMessageW {
private JFrame errorMessageW;
private ArrayList<String> errors;
private JPanel panel;
private JScrollPane scrollPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
final ArrayList<String> err = new ArrayList<>();
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ErrorMessageW window = new ErrorMessageW(err);
window.errorMessageW.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ErrorMessageW(ArrayList<String> err) {
errors = err;
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
errorMessageW = new JFrame();
errorMessageW.setTitle("Unfilled forms");
errorMessageW.setBounds(100, 100, 367, 300);
errorMessageW.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btnOk = new JButton("OK");
btnOk.setBounds(239, 208, 89, 23);
btnOk.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
errorMessageW.dispose();
}
});
errorMessageW.getContentPane().setLayout(null);
errorMessageW.getContentPane().add(btnOk);
scrollPane = new JScrollPane();
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setBounds(10, 10, 330, 175);
errorMessageW.getContentPane().add(scrollPane);
panel = new JPanel();
for(String s : errors){
JTextArea text = new JTextArea(1,20);
text.setText(s);
text.setFont(new Font("Verdana",1,10));
text.setForeground(Color.RED);
panel.add(text);
}
scrollPane.setViewportView(panel);
}
public JFrame getErrorMessageW() {
return errorMessageW;
}
public void setErrorMessageW(JFrame errorMessageW) {
this.errorMessageW = errorMessageW;
}
}
This is what i get
This is what i want, but using the JScrollPane:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.util.ArrayList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class ErrorMessageW {
private JFrame errorMessageW;
private ArrayList<String> errors;
private JPanel panel;
private JScrollPane scrollPane;
private JTextArea errorMessage = new JTextArea(3, 30);
/**
* Launch the application.
*/
public static void main(String[] args) {
final ArrayList<String> err = new ArrayList<String>();
err.add("Short String");
err.add("A very very very very very very very very very very very "
+ "very very very very very very very very very very very "
+ "very very very very very very very very long String");
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ErrorMessageW window = new ErrorMessageW(err);
window.errorMessageW.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ErrorMessageW(ArrayList<String> err) {
errors = err;
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
errorMessageW = new JFrame();
JPanel contentPane = new JPanel(new BorderLayout(5, 15));
contentPane.setBorder(new EmptyBorder(10, 10, 10, 10));
errorMessage.setLineWrap(true);
errorMessage.setWrapStyleWord(true);
JScrollPane jsp = new JScrollPane(
errorMessage,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER
);
contentPane.add(jsp, BorderLayout.PAGE_START);
errorMessageW.add(contentPane);
errorMessageW.setTitle("Unfilled forms");
errorMessageW.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JButton btnOk = new JButton("OK");
btnOk.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
errorMessageW.dispose();
}
});
JPanel btnConstrain = new JPanel(new FlowLayout(FlowLayout.TRAILING));
btnConstrain.add(btnOk);
contentPane.add(btnConstrain, BorderLayout.PAGE_END);
scrollPane = new JScrollPane();
scrollPane.setVerticalScrollBarPolicy(
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPane.setHorizontalScrollBarPolicy(
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
contentPane.add(scrollPane, BorderLayout.CENTER);
DefaultListModel<String> listModel = new DefaultListModel<String>();
for (String s : errors) {
listModel.addElement(s);
}
final JList<String> errorList = new JList<String>(listModel);
Dimension preferredSize = new Dimension(errorMessage.getPreferredSize().width,200);
errorList.setPreferredSize(preferredSize);
ListSelectionListener errorSelect = new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
errorMessage.setText(errorList.getSelectedValue());
}
};
errorList.addListSelectionListener(errorSelect);
scrollPane.setViewportView(errorList);
errorMessageW.pack();
}
public JFrame getErrorMessageW() {
return errorMessageW;
}
public void setErrorMessageW(JFrame errorMessageW) {
this.errorMessageW = errorMessageW;
}
}
First of all, you could try, instead of creating multiple instances of JTextArea, using only one and appending each error to it like this:
JTextArea text = new JTextArea(1, 20);
text.setFont(new Font("Verdana",1,10));
text.setForeground(Color.RED);
for(String s : errors) {
text.append(s + "\n");
}
panel.add(text);
However, if you do need to create more than one JTextArea, you can use a BoxLayout like this:
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
You just need to write a function that adds a new line character as an element of your ArrayList after every other element in your ArrayList of errors. Below i did a test program that shows how that can be done. I also checked the oputput. Just paste the code and understand the working of code. All the best!
import java.util.ArrayList;
public class TestingArraylist {
static ArrayList<String> errors = new ArrayList<String>();
static final String[] warnings = new String[]{"Error 0 occured","Error 1 occured","Error 2 occured","Error 3 occured","Error 4 occured"};;
public static void addNewLineToArrayList(String[] elementofarraylist){
for(int i =0;i<elementofarraylist.length;i++){
errors.add(elementofarraylist[i]);
errors.add("\n"); //this is what you need to do!
}
}
public static void main(String[] args) {
addNewLineToArrayList(warnings);
//checking below if our work has really succeded or not!!
for(int j =0;j<errors.size();j++){
System.out.print(errors.get(j));
}
}
}
This is my program below and I am trying to figure out where my main method should be. I have seen a few examples of it being implemented at the very end of the program but there main is different from mine.
Main method (to be implemented):
public class JFrame
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setTitle("Components File");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
My Program
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;
public class Lab_10 extends JFrame
{
private final double EARTHQUAKE_RATE= 8.0;
private final int FRAME_WIDTH= 300;
private final int FRAME_HEIGHT= 200;
private JLabel rLabel;
private JTextField eField;
private JButton button;
private JLabel earthLabel;
public Lab_10()
{
JLabel earthLabel = new JLabel("Most structures fall");
makeTextField();
makeButton();
makePanel();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
private void makeTextField()
{
JLabel rLabel = new JLabel("Richter");
final int FIELD_WIDTH = 10;
eField = new JTextField(FIELD_WIDTH);
eField.setText("" + EARTHQUAKE_RATE);
}
class AddLabelListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
earthLabel.setText("Most structures fall");
}
}
private void makeButton()
{
JButton button = new JButton("Enter");
ActionListener listener = new AddLabelListener();
button.addActionListener(listener);
}
private void makePanel()
{
JPanel panel = new JPanel();
panel.add(rLabel);
panel.add(eField);
panel.add(button);
panel.add(earthLabel);
add(panel);
}
}
Updated Code (which is compiling but and running but with logic errors because it implements an empty frame [guess as much from the main method I have]):
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;
public class Lab_10 extends JFrame
{
private final double EARTHQUAKE_RATE= 8.0;
private final int FRAME_WIDTH= 300;
private final int FRAME_HEIGHT= 200;
private JLabel rLabel;
private JTextField eField;
private JButton button;
private JLabel earthLabel;
public Lab_10()
{
JLabel earthLabel = new JLabel("Most structures fall");
makeTextField();
makeButton();
makePanel();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
private void makeTextField()
{
JLabel rLabel = new JLabel("Richter");
final int FIELD_WIDTH = 10;
eField = new JTextField(FIELD_WIDTH);
eField.setText("" + EARTHQUAKE_RATE);
}
class AddLabelListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
earthLabel.setText("Most structures fall");
}
}
private void makeButton()
{
JButton button = new JButton("Enter");
ActionListener listener = new AddLabelListener();
button.addActionListener(listener);
}
private void makePanel()
{
JPanel panel = new JPanel();
panel.add(rLabel);
panel.add(eField);
panel.add(button);
panel.add(earthLabel);
add(panel);
}
public static void main(String[] args){
javax.swing.SwingUtilities.invokeLater(new Runnable(){
#Override
public void run()
{ JFrame frame = new JFrame();
frame.setTitle("Components File");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
Your 'main' probably looks different because you are not using SwingUtilities.invokeLater(Runnable doRun) ?
Well, to put it simply, you must use it always. So, modify your code and use this:
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run(){
// copy-paste your main() code
}
});
Also, why is your class named JFrame ? Refrain from using names that are already used by Java classes already.
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