I have been following the How to Print Text tutorial on the Oracle Java Documentation website. However when I have tried to implement some of the code into my code I get an error.
javac PrintableForms.java
PrintableForms.java:165: error: incompatible types: PrintableForms cannot be converted to Component
JOptionPane.showMessageDialog(this, msg, "Printing", type);
My code is
import javax.swing.*;
import java.awt.*;
import java.io.*;
import javax.swing.*;
import java.awt.print.PrinterException;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.*;
import java.text.MessageFormat;
import javax.xml.transform.Source;
public class PrintableForms
{
JFrame myMainWindow = new JFrame("This is my title");
JPanel firstPanel = new JPanel();
JButton btnDoc1 = new JButton();
JButton btnP1 = new JButton();
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String []fontFamilies = ge.getAvailableFontFamilyNames();
Font FontT5 = new Font("SansSerif", Font.BOLD, 50);
///////////
JCheckBox backgroundCheck = new JCheckBox();
JCheckBox interactiveCheck = new JCheckBox();
JTextArea text = new JTextArea();
JTextField headerField = new JTextField();
JTextField footerField = new JTextField();
public void runGUI()
{
myMainWindow.setBounds(10, 10, 1200, 500);
myMainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myMainWindow.setLayout(new GridLayout(1,1));
createFirstPanel();
myMainWindow.getContentPane().add(firstPanel);
myMainWindow.setVisible(true);
load(text, "Athlete.txt");
}
public void createFirstPanel()
{
firstPanel.setLayout(null);
btnDoc1.setLocation(10,120);
btnDoc1.setSize(900,50);
btnDoc1.setText("Update Personal Information");
btnDoc1.setFont(FontT5);
firstPanel.add(btnDoc1);
btnP1.setLocation(910,120);
btnP1.setSize(250,50);
btnP1.setText("Print");
btnP1.setFont(FontT5);
btnP1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
print(evt);
}
});
firstPanel.add(btnP1);
footerField.setText("Page {0}");
headerField.setText("Athlete Form");
backgroundCheck.setSelected(true);
interactiveCheck.setSelected(true);
}
private void load(JTextArea comp, String fileName) {
try {
comp.read(
new InputStreamReader(
getClass().getResourceAsStream(fileName)),
null);
} catch (IOException ex) {
ex.printStackTrace();
}
}
private void print(java.awt.event.ActionEvent evt)
{
MessageFormat header = createFormat(headerField);
MessageFormat footer = createFormat(footerField);
boolean interactive = interactiveCheck.isSelected();
boolean background = backgroundCheck.isSelected();
PrintingTask task = new PrintingTask(header, footer, interactive);
if (background)
{
task.execute();
}
else
{
task.run();
}
}
private class PrintingTask extends SwingWorker<Object, Object>
{
private final MessageFormat headerFormat;
private final MessageFormat footerFormat;
private final boolean interactive;
private volatile boolean complete = false;
private volatile String message;
JTextArea text = new JTextArea();
public PrintingTask(MessageFormat header, MessageFormat footer, boolean interactive)
{
this.headerFormat = header;
this.footerFormat = footer;
this.interactive = interactive;
}
#Override
protected Object doInBackground() {
try {
complete = text.print(headerFormat, footerFormat,
true, null, null, interactive);
message = "Printing " + (complete ? "complete" : "canceled");
} catch (PrinterException ex) {
message = "Sorry, a printer error occurred";
} catch (SecurityException ex) {
message =
"Sorry, cannot access the printer due to security reasons";
}
return null;
}
#Override
protected void done() {
message(!complete, message);
}
}
private MessageFormat createFormat(JTextField source) {
//String text = new Scanner( new File("Athlete.txt") ).useDelimiter("\\A").next();
String text = source.getText();
if (text != null && text.length() > 0) {
try {
return new MessageFormat(text);
} catch (IllegalArgumentException e) {
error("Sorry, this format is invalid.");
}
}
return null;
}
private void message(boolean error, String msg)
{
int type = (error ? JOptionPane.ERROR_MESSAGE :
JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(this, msg, "Printing", type);
}
private void error(String msg)
{
message(true, msg);
}
public static void main(String[] args)
{
PrintableForms pf = new PrintableForms();
pf.runGUI();
}
}
I am trying to get it so when I click a button, btnP1 in this case, it opens a dialog and then allows you to print off a pre-set document. In this code that document is Athlete.txt and all it reads is This is a test
I would any help in fixing this problem, Thanks
You could pass on the frame object which is the main window that you created when you want to show the dialog window.
Like below.
JOptionPane.showMessageDialog(myMainWindow, msg, "Printing", type);
you should extends Component class or create Component type object and pass as argument instead of this because
JOptionPane.showMessageDialog(this, msg, "Printing", type);
first argument is of Component Type and you are passing parameter of type PrintableForms as this .
Try implementing the Printable interface.
Related
I have a JTextArea and a JComboBox to allow me to cycle through various open files - the contents of the JTextArea change as I select a different file. I am trying to maintain a different Undo buffer per file and have defined a separate UndoManager per file.
I have created a simpler SSCCE to demonstrate my problem using two buffers, which I call "One" and "Two" - with a simple button to switch between them. Once an UndoableEdit happens, it checks the active buffer and performs an addEdit() on the respective UndoManager. When the "Undo" button is pressed, then it checks canUndo() and performs an undo() on the respective UndoManager. I have a flag called ignoreEdit, which is used when switching between buffers to ignore those edits from being recorded.
If I never switch between the buffers, then I don't have a problem, Undo works as expected. It is only when I switch between the buffers and appear to "break" the Document, does it fail. The following steps can be used to recreate the problem:
In buffer "One", type:
THIS
IS ONE
EXAMPLE
Switch to buffer "Two", type:
THIS
IS ANOTHER
EXAMPLE
Switch to buffer "One" and press the "Undo" button multiple times. After a few Undo operations, the buffer looks like this (with no way for the cursor to select the first two lines). However, the contents of textArea.getText() are correct as per the System.out.println() - so, it looks like a rendering issue?
THIS
THISIS ONE
This can't be the first time that someone has tried to implement independent Undo buffers per file? I am obviously doing something wrong with the Document model and inherently breaking it, but I looking for some advice on how best to fix this?
The code for the SSCCE is included below:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.undo.*;
public class SSCCE extends JFrame implements ActionListener, UndoableEditListener {
private final JLabel labTextArea;
private final JTextArea textArea;
private final JScrollPane scrollTextArea;
private final Document docTextArea;
private final JButton bOne, bTwo, bUndo;
private final UndoManager uOne, uTwo;
private String sOne, sTwo;
private boolean ignoreEdit = false;
public SSCCE(String[] args) {
setTitle("SSCCE - Short, Self Contained, Correct Example");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300, 200);
setLocationRelativeTo(null);
labTextArea = new JLabel("One");
getContentPane().add(labTextArea, BorderLayout.PAGE_START);
uOne = new UndoManager();
uTwo = new UndoManager();
sOne = new String();
sTwo = new String();
textArea = new JTextArea();
docTextArea = textArea.getDocument();
docTextArea.addUndoableEditListener(this);
scrollTextArea = new JScrollPane(textArea);
getContentPane().add(scrollTextArea, BorderLayout.CENTER);
JPanel pButtons = new JPanel();
bOne = new JButton("One");
bOne.addActionListener(this);
bOne.setFocusable(false);
pButtons.add(bOne, BorderLayout.LINE_START);
bTwo = new JButton("Two");
bTwo.addActionListener(this);
bTwo.setFocusable(false);
pButtons.add(bTwo, BorderLayout.LINE_END);
bUndo = new JButton("Undo");
bUndo.addActionListener(this);
bUndo.setFocusable(false);
pButtons.add(bUndo, BorderLayout.LINE_END);
getContentPane().add(pButtons, BorderLayout.PAGE_END);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(bOne)) {
if (!labTextArea.getText().equals("One")) {
sTwo = textArea.getText();
ignoreEdit = true;
textArea.setText(sOne);
ignoreEdit = false;
labTextArea.setText("One");
}
}
else if (e.getSource().equals(bTwo)) {
if (!labTextArea.getText().equals("Two")) {
sOne = textArea.getText();
ignoreEdit = true;
textArea.setText(sTwo);
ignoreEdit = false;
labTextArea.setText("Two");
}
}
else if (e.getSource().equals(bUndo)) {
if (labTextArea.getText().equals("One")) {
try {
if (uOne.canUndo()) {
System.out.println("Performing Undo for One");
uOne.undo();
System.out.println("Buffer One is now:\n" + textArea.getText() + "\n");
}
else {
System.out.println("Nothing to Undo for One");
}
}
catch (CannotUndoException ex) {
ex.printStackTrace();
}
}
else if (labTextArea.getText().equals("Two")) {
try {
if (uTwo.canUndo()) {
System.out.println("Performing Undo for Two");
uTwo.undo();
System.out.println("Buffer Two is now:\n" + textArea.getText() + "\n");
}
else {
System.out.println("Nothing to Undo for Two");
}
}
catch (CannotUndoException ex) {
ex.printStackTrace();
}
}
}
}
#Override
public void undoableEditHappened(UndoableEditEvent e) {
if (!ignoreEdit) {
if (labTextArea.getText().equals("One")) {
System.out.println("Adding Edit for One");
uOne.addEdit(e.getEdit());
}
else if (labTextArea.getText().equals("Two")) {
System.out.println("Adding Edit for Two");
uTwo.addEdit(e.getEdit());
}
}
}
public static void main(final String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new SSCCE(args);
}
});
}
}
Previously I had attempted to create a new instance of the Document class (each referencing the same Undo listener) and was going to use JTextArea.setDocument() instead of JTextArea.setText(). However, Document is an interface and can't be instantiated, but after reading the reference that mKorbel posted, I tried this using the PlainDocument class instead, which worked.
I have decided to maintain a HashMap<String, Document> to contain my Document classes and switch between them. When I switch the Document, I don't see the Undo/Redo issue - I suppose as I am no longer breaking the Document.
Updated SSCCE below which now uses JTextArea.setDocument() instead of JTextArea.setText(). This also has the advantage of not requiring the ignoreEdit boolean as setDocument() doesn't trigger an UndoableEditEvent, whereas setText() does. Each Document then references the local classes UndoableEditListener.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.undo.*;
public class SSCCE extends JFrame implements ActionListener, UndoableEditListener {
private final JLabel labTextArea;
private final JTextArea textArea;
private final JScrollPane scrollTextArea;
private final Document docTextArea;
private final JButton bOne, bTwo, bUndo;
private final UndoManager uOne, uTwo;
private Document dOne, dTwo;
public SSCCE(String[] args) {
setTitle("SSCCE - Short, Self Contained, Correct Example");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300, 200);
setLocationRelativeTo(null);
labTextArea = new JLabel("One");
getContentPane().add(labTextArea, BorderLayout.PAGE_START);
uOne = new UndoManager();
uTwo = new UndoManager();
dOne = new PlainDocument();
dTwo = new PlainDocument();
dOne.addUndoableEditListener(this);
dTwo.addUndoableEditListener(this);
textArea = new JTextArea();
docTextArea = textArea.getDocument();
docTextArea.addUndoableEditListener(this);
textArea.setDocument(dOne);
scrollTextArea = new JScrollPane(textArea);
getContentPane().add(scrollTextArea, BorderLayout.CENTER);
JPanel pButtons = new JPanel();
bOne = new JButton("One");
bOne.addActionListener(this);
bOne.setFocusable(false);
pButtons.add(bOne, BorderLayout.LINE_START);
bTwo = new JButton("Two");
bTwo.addActionListener(this);
bTwo.setFocusable(false);
pButtons.add(bTwo, BorderLayout.LINE_END);
bUndo = new JButton("Undo");
bUndo.addActionListener(this);
bUndo.setFocusable(false);
pButtons.add(bUndo, BorderLayout.LINE_END);
getContentPane().add(pButtons, BorderLayout.PAGE_END);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(bOne)) {
if (!labTextArea.getText().equals("One")) {
textArea.setDocument(dOne);
labTextArea.setText("One");
}
}
else if (e.getSource().equals(bTwo)) {
if (!labTextArea.getText().equals("Two")) {
textArea.setDocument(dTwo);
labTextArea.setText("Two");
}
}
else if (e.getSource().equals(bUndo)) {
if (labTextArea.getText().equals("One")) {
try {
if (uOne.canUndo()) {
System.out.println("Performing Undo for One");
uOne.undo();
System.out.println("Buffer One is now:\n" + textArea.getText() + "\n");
}
else {
System.out.println("Nothing to Undo for One");
}
}
catch (CannotUndoException ex) {
ex.printStackTrace();
}
}
else if (labTextArea.getText().equals("Two")) {
try {
if (uTwo.canUndo()) {
System.out.println("Performing Undo for Two");
uTwo.undo();
System.out.println("Buffer Two is now:\n" + textArea.getText() + "\n");
}
else {
System.out.println("Nothing to Undo for Two");
}
}
catch (CannotUndoException ex) {
ex.printStackTrace();
}
}
}
}
#Override
public void undoableEditHappened(UndoableEditEvent e) {
if (labTextArea.getText().equals("One")) {
System.out.println("Adding Edit for One");
uOne.addEdit(e.getEdit());
}
else if (labTextArea.getText().equals("Two")) {
System.out.println("Adding Edit for Two");
uTwo.addEdit(e.getEdit());
}
}
public static void main(final String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new SSCCE(args);
}
});
}
}
This is not an answer per se, but a demonstration of a different way of approaching the same problem.
What this does is wraps the UndoableEditListener in a self managed proxy, which has it's own UndoManager and Document.
Tested this with Java 7 and Java 8:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import javax.swing.text.PlainDocument;
import javax.swing.undo.UndoManager;
public class UndoExample {
public static void main(String[] args) {
new UndoExample();
}
private int index = 0;
private Map<String, Undoer> mapUndoers;
private JTextArea ta;
private Undoer current;
public UndoExample() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
mapUndoers = new HashMap<>(2);
mapUndoers.put("One", new Undoer());
mapUndoers.put("Two", new Undoer());
ta = new JTextArea(4, 20);
ta.setWrapStyleWord(true);
ta.setLineWrap(true);
JButton btnOne = new JButton("One");
JButton btnTwo = new JButton("Two");
ActionListener al = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
install(e.getActionCommand());
}
};
btnOne.addActionListener(al);
btnTwo.addActionListener(al);
JButton undo = new JButton("Undo");
undo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (current != null) {
current.undo();
}
}
});
JPanel panel = new JPanel(new GridBagLayout());
panel.add(btnOne);
panel.add(btnTwo);
panel.add(undo);
install("One");
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(ta));
frame.add(panel, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
protected void install(String name) {
Undoer undoer = mapUndoers.get(name);
if (undoer != null) {
current = undoer;
undoer.install(ta);
}
}
public class Undoer implements UndoableEditListener {
private UndoManager undoManager;
private Document doc;
public Undoer() {
undoManager = new UndoManager();
doc = createDocument();
doc.addUndoableEditListener(this);
}
public void undo() {
undoManager.undo();
}
public void undoOrRedo() {
undoManager.undoOrRedo();
}
protected Document createDocument() {
return new PlainDocument();
}
public void install(JTextComponent comp) {
comp.setDocument(doc);
}
#Override
public void undoableEditHappened(UndoableEditEvent e) {
undoManager.addEdit(e.getEdit());
}
}
}
I am calling a method that returns a string (edited text from a webpage) and I want to print that string onto my JTextArea. I know that string I am sending to my JTextArea is correct because it will print correctly to the command line, but will not print to the JTextArea. It must be something I am doing wrong in my adding it to the TextArea. Any help would be appreciated.
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
public class BrowserPanel extends JPanel {
private JTextField textField;
private String urlText;
private JTextArea textArea;
private BrowserPageReader myModel;
private String pageContent;
private BrowserFrame myFrame;
private String pageTitle;
private String pageBody;
public BrowserPanel(JTextField myTextField, BrowserPageReader model,
BrowserFrame frame)
{
myFrame = frame;
myModel = model;
textField = myTextField;
textField.addActionListener(new InputHandler());
/*JScrollPane areaScrollPane = new JScrollPane(textArea);
areaScrollPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
areaScrollPane.setPreferredSize(new Dimension(250,250));*/
textArea = new JTextArea(20,40);
textArea.setEditable(false);
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
JScrollPane scroll = new JScrollPane(textArea);
add(scroll);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
}
private class InputHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
urlText = textField.getText();
//textArea.append(urlText);
myModel.setURL(urlText);
pageTitle = myModel.getTitle();
myFrame.setTitle(pageTitle);
pageBody = myModel.getBody();
textArea.setText(pageBody);
System.out.println(pageBody); //This prints out exactly what Im wanting
// Its just a test
textArea.repaint();
}
}
}
I'm guessing I maybe need to add something to my paintComponent since my TextArea is in a scrollPane that is attached to my Panel. I just really cant figure out what is wrong. If i put textArea.setText("blah"); it does what it should. The variable I am sending in is a very large string, its an entire webpage. Could that be the problem? With the code as is the textArea remains blank and what i'm wanting it to show prints correctly to the command line. HELP!
Edit here is the rest of my code
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
public class BrowserFrame extends JFrame{
public BrowserFrame()
{
BrowserPageReader myModel = new BrowserPageReader();
setTitle("My Browser");
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension screenSize =kit.getScreenSize();
setSize(screenSize.width/2,screenSize.height-500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = getContentPane();
JTextField textField = new JTextField(20);
BrowserPanel myPanel = new BrowserPanel(textField,myModel,this);
contentPane.add(myPanel);
contentPane.add(textField,BorderLayout.PAGE_START);
setVisible(true);
}
}
import javax.swing.*;
import java.io.*;
import java.net.*;
public class BrowserPageReader {
private URL myURL;
//private String webURL;
private String totalWebContent;
private String htmlString;
private String contentToPrint = " ";
private String urlPath;
private String urlHost;
private String pageTitle;
private String pageBody;
private String formattedBody;
public void setURL (String webURL)
{
try{
myURL = new URL(webURL);
urlPath = myURL.getPath();
urlHost = myURL.getHost();
}
catch(MalformedURLException e)
{
JOptionPane.showMessageDialog(null,"URL is incorrectly formatted");
}
}
public void retrieveContent()
{
try{
Socket socket = new Socket(urlHost,80);
PrintWriter out = new PrintWriter(socket.getOutputStream());
BufferedReader in = new
BufferedReader(new InputStreamReader(socket.getInputStream()));
out.print("GET " + urlPath + " HTTP/1.1\n");
out.print("Host: "+ urlHost + "\n");
out.print("\n");
out.flush();
while((totalWebContent = in.readLine()) != null)
{
//System.out.println(totalWebContent);
htmlString = htmlString + totalWebContent;
//System.out.println(contentToPrint);
}
//System.out.println("htmlString\n" + htmlString);
}
catch(Exception e){
e.printStackTrace();
}
}
public String getTitle()
{
retrieveContent();
//System.out.println(htmlString);
pageTitle = htmlString.substring(htmlString.indexOf("<title>")+ 7,
htmlString.indexOf("</title>"));
return pageTitle;
}
public String getBody()
{
String toDelete;
String edited;
retrieveContent();
pageBody = htmlString.substring(htmlString.indexOf("<body")+5,
htmlString.indexOf("</body>"));
toDelete = pageBody.substring(0,pageBody.indexOf('<'));
edited = pageBody.replace(toDelete,"");
pageBody = edited
formattedBody = pageBody.replaceAll("<[^>]*>", "");
//System.out.println(formattedBody);
return formattedBody;
}
Since your posted code is not an SSCCE, a small self-contained program that we can compile, run, and test, I don't think that we answer this without guessing. And so my guess: the JTextArea that you're adding text to is not the same one as is being displayed in a JFrame.
To be able to answer this with confidence though, we need that SSCCE, especially the code showing where you create the class above and where you add it to the JFrame that is displayed.
For instance, if I create a small SSCCE with mock BrowserFrame JFrame and BrowserPageReader model classes, everything seems to work fine:
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
public class BrowserPanel extends JPanel {
private JTextField textField;
private String urlText;
private JTextArea textArea;
private BrowserPageReader myModel;
private String pageContent;
private BrowserFrame myFrame;
private String pageTitle;
private String pageBody;
public BrowserPanel(JTextField myTextField, BrowserPageReader model,
BrowserFrame frame) {
myFrame = frame;
myModel = model;
textField = myTextField;
textField.addActionListener(new InputHandler());
/*
* JScrollPane areaScrollPane = new JScrollPane(textArea);
* areaScrollPane.setVerticalScrollBarPolicy(
* JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
*
* areaScrollPane.setPreferredSize(new Dimension(250,250));
*/
textArea = new JTextArea(20, 40);
textArea.setEditable(false);
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
JScrollPane scroll = new JScrollPane(textArea);
add(scroll);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
}
private class InputHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
urlText = textField.getText();
// textArea.append(urlText);
myModel.setURL(urlText);
pageTitle = myModel.getTitle();
myFrame.setTitle(pageTitle);
pageBody = myModel.getBody();
textArea.setText(pageBody);
System.out.println(pageBody); // This prints out exactly what Im
// wanting
// Its just a test
textArea.repaint();
}
}
private static void createAndShowGui() {
BrowserFrame frame = new BrowserFrame();
JTextField textField = new JTextField(10);
BrowserPageReader myModel = new BrowserPageReader();
BrowserPanel mainPanel = new BrowserPanel(textField, myModel, frame);
frame.add(textField, BorderLayout.NORTH);
frame.add(mainPanel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_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();
}
});
}
}
class BrowserFrame extends JFrame {
}
class BrowserPageReader {
public void setURL(String urlText) {
// does nothing for now. for testing purposes.
}
public String getBody() {
return "body"; // for testing purposes
}
public String getTitle() {
return "title"; // for testing purposes
}
}
Since my code "works" it proves that the error is not in the code you've posted above.
Your job is to post similar code that doesn't work fine, that instead demonstrates your problem. I'm guessing that if you put in the effort to create such a program, you'll isolate the error, you'll see where you've likely got two BrowserPanels, one displayed and one that is not displayed but is getting its text changed in the handler, and you'll be able to solve your error without our direct help.
Edit
SwingWorker e.g.
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
public class BrowserPanel extends JPanel {
private JTextField textField;
private String urlText;
private JTextArea textArea;
private BrowserPageReader myModel;
private String pageContent;
private BrowserFrame myFrame;
private String pageTitle;
private String pageBody;
public BrowserPanel(JTextField myTextField, BrowserPageReader model,
BrowserFrame frame) {
myFrame = frame;
myModel = model;
textField = myTextField;
textField.addActionListener(new InputHandler());
/*
* JScrollPane areaScrollPane = new JScrollPane(textArea);
* areaScrollPane.setVerticalScrollBarPolicy(
* JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
*
* areaScrollPane.setPreferredSize(new Dimension(250,250));
*/
textArea = new JTextArea(20, 40);
textArea.setEditable(false);
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
JScrollPane scroll = new JScrollPane(textArea);
add(scroll);
}
private class InputHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
urlText = textField.getText();
// textArea.append(urlText);
System.out.println(urlText);
myModel.setURL(urlText);
myModel.getContent(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (SwingWorker.StateValue.DONE == evt.getNewValue()) {
pageTitle = myModel.getTitle();
myFrame.setTitle(pageTitle);
pageBody = myModel.getBody();
textArea.setText(pageBody);
System.out.println(pageBody);
}
}
});
// textArea.repaint();
}
}
private static void createAndShowGui() {
BrowserFrame frame = new BrowserFrame();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class BrowserFrame extends JFrame {
public BrowserFrame() {
BrowserPageReader myModel = new BrowserPageReader();
setTitle("My Browser");
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension screenSize = kit.getScreenSize();
setSize(screenSize.width / 2, screenSize.height - 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = getContentPane();
JTextField textField = new JTextField(20);
BrowserPanel myPanel = new BrowserPanel(textField, myModel, this);
contentPane.add(myPanel);
contentPane.add(textField, BorderLayout.PAGE_START);
setVisible(true);
}
}
class BrowserPageReader {
private URL myURL;
// private String webURL;
private String totalWebContent;
private String htmlString;
private String contentToPrint = " ";
private String urlPath;
private String urlHost;
private String pageTitle;
private String pageBody;
private String formattedBody;
public void setURL(String webURL) {
try {
myURL = new URL(webURL);
urlPath = myURL.getPath();
urlHost = myURL.getHost();
} catch (MalformedURLException e) {
JOptionPane.showMessageDialog(null, "URL is incorrectly formatted");
}
}
public void getContent(PropertyChangeListener listener) {
RetrieveWorker worker = new RetrieveWorker();
worker.addPropertyChangeListener(listener);
worker.execute();
}
private void retrieveContent() {
try {
Socket socket = new Socket(urlHost, 80);
PrintWriter out = new PrintWriter(socket.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
out.print("GET " + urlPath + " HTTP/1.1\n");
out.print("Host: " + urlHost + "\n");
out.print("\n");
out.flush();
while ((totalWebContent = in.readLine()) != null) {
// System.out.println(totalWebContent);
htmlString = htmlString + totalWebContent;
// System.out.println(contentToPrint);
}
// System.out.println("htmlString\n" + htmlString);
} catch (Exception e) {
e.printStackTrace();
}
}
public String getTitle() {
// !! retrieveContent();
System.out.println(htmlString);
pageTitle = htmlString.substring(htmlString.indexOf("<title>") + 7,
htmlString.indexOf("</title>"));
return pageTitle;
}
public String getBody() {
String toDelete;
String edited;
// !! retrieveContent();
pageBody = htmlString.substring(htmlString.indexOf("<body") + 5,
htmlString.indexOf("</body>"));
toDelete = pageBody.substring(0, pageBody.indexOf('<'));
edited = pageBody.replace(toDelete, "");
pageBody = edited;
formattedBody = pageBody.replaceAll("<[^>]*>", "");
// System.out.println(formattedBody);
return formattedBody;
}
private class RetrieveWorker extends SwingWorker<Void, Void> {
#Override
protected Void doInBackground() throws Exception {
retrieveContent();
return null;
}
}
}
I bet your input handler is getting called multiple times. The text could be set to the body text, then print, then be set back to empty for some reason. Test this in your system.out.println statment by adding
System.out.println("outputStart: " + pagebody + " :END");
Then you'll be able to tell how many times your input handler ran.
Please have a look at the following code
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
public class Form extends JFrame
{
private JTextPane textPane;
private JLabel results;
private JPanel center,south;
private FlowLayout flow;
private ArrayList array;
private Color color;
private StyledDocument doc;
private Style style, fontSize;
public Form()
{
textPane = new JTextPane();
textPane.setMinimumSize(new Dimension(100,100));
doc = textPane.getStyledDocument();
doc.addDocumentListener(new TextActions());
results = new JLabel("Number of letters: ");
array = new ArrayList();
array.add("public");
array.add("static");
array.add("void");
array.add("private");
array.add("protected");
color = new Color(185,224,247);
//Adding styles
style = doc.addStyle("blue", null);
StyleConstants.setForeground(style, color);
fontSize = doc.addStyle("fontSize", null);
StyleConstants.setFontSize(fontSize, 25);
//Setting the font Size
doc.setCharacterAttributes(0, doc.getLength(), fontSize, false);
center = new JPanel();
flow = new FlowLayout();
center.setLayout(flow);
center.add(textPane);
south = new JPanel();
south.setLayout(new FlowLayout());
south.add(results);
getContentPane().add(textPane,"Center");
getContentPane().add(south,"South");
}
private class TextActions implements DocumentListener
{
#Override
public void insertUpdate(DocumentEvent e)
{
try {
highlighat();
} catch (BadLocationException ex) {
ex.printStackTrace();
}
}
#Override
public void removeUpdate(DocumentEvent e)
{
try {
highlighat();
} catch (BadLocationException ex) {
ex.printStackTrace();
}
}
#Override
public void changedUpdate(DocumentEvent e)
{
}
}
private void highlighat() throws BadLocationException
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
String text = "";
String content = null;
try {
content = doc.getText(0, doc.getLength()).toLowerCase();
} catch (BadLocationException ex) {
ex.printStackTrace();
}
int last=0;
for(int i=0;i<array.size();i++)
{
text = array.get(i).toString();
if(content.contains(text))
{
while((last=content.indexOf(text,last))!=-1)
{
int end = last+text.length();
doc.setCharacterAttributes(last, end, textPane.getStyle("blue"), true);
last++;
}
}
}
}
}
);
}
public static void main(String[]args)
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch(Exception e)
{
}
Form f = new Form();
f.setVisible(true);
f.setSize(800,600);
f.validate();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
In there, I am also trying to set the font size to 25, but as you can see, it is not working. "textPane.setFont()" also didn't work. How can I set the font size correctly? Please help..
Sure, you can create a font object and use it to set the font of your text pane.
Instantiate it like this:
Font f = new Font(Font.SANS_SERIF, 3, 5);
Maybe this code will help you, about Highlighter and StyledDocument, rest is described in the tutorial about JTextPane / EditorPane
I am making an application similar to a chat. For that purpose I have two JTextPanes, one where I'm writing and one that displays messages. This is the code that handles the transferring of text from input to display :
String input = textPane.getText();
if(!input.endsWith("\n")){
input+="\n";
}
StyledDocument doc = displayPane.getStyledDocument();
int offset = displayPane.getCaretPosition();
textPane.setText("");
try {
doc.insertString(offset, input, set);
} catch (BadLocationException ex) {
Logger.getLogger(ChatComponent.class.getName()).log(Level.SEVERE, null, ex);
}
The problem is that if i have colour on some words of the input text , the output is all coloured . So the colour is applied to all of the text when moved to display(while displayed correctly on input). Any suggestions on how i can move text properly?
Notice that same happens with other format as bold , italic etc
The text is already formatted on the input JTextPane . What i need to do
is transfer it as it is on a different JTextPane without having to check
the different style options
example
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class Fonts implements Runnable {
private String[] fnt;
private JFrame frm;
private JScrollPane jsp;
private JTextPane jta;
private int width = 450;
private int height = 300;
private GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
private StyledDocument doc;
private MutableAttributeSet mas;
private int cp = 0;
private Highlighter.HighlightPainter cyanPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.cyan);
private Highlighter.HighlightPainter redPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.red);
private Highlighter.HighlightPainter whitePainter = new DefaultHighlighter.DefaultHighlightPainter(Color.white);
private int _count = 0;
private int _lenght = 0;
public Fonts() {
jta = new JTextPane();
doc = jta.getStyledDocument();
jsp = new JScrollPane(jta);
jsp.setPreferredSize(new Dimension(height, width));
frm = new JFrame("awesome");
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setLayout(new BorderLayout());
frm.add(jsp, BorderLayout.CENTER);
frm.setLocation(100, 100);
frm.pack();
frm.setVisible(true);
jta.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
fnt = ge.getAvailableFontFamilyNames();
mas = jta.getInputAttributes();
new Thread(this).start();
}
#Override
public void run() {
for (int i = 0; i < fnt.length; i++) {
StyleConstants.setBold(mas, false);
StyleConstants.setItalic(mas, false);
StyleConstants.setFontFamily(mas, fnt[i]);
StyleConstants.setFontSize(mas, 16);
dis(fnt[i]);
try {
Thread.sleep(75);
} catch (Exception e) {
e.printStackTrace();
}
StyleConstants.setBold(mas, true);
dis(fnt[i] + " Bold");
try {
Thread.sleep(75);
} catch (Exception e) {
e.printStackTrace();
}
StyleConstants.setItalic(mas, true);
dis(fnt[i] + " Bold & Italic");
try {
Thread.sleep(75);
} catch (Exception e) {
e.printStackTrace();
}
StyleConstants.setBold(mas, false);
dis(fnt[i] + " Italic");
try {
Thread.sleep(75);
} catch (Exception e) {
e.printStackTrace();
}
}
jta.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
public void dis(String s) {
_count++;
_lenght = jta.getText().length();
try {
doc.insertString(cp, s, mas);
doc.insertString(cp, "\n", mas);
} catch (Exception bla_bla_bla_bla) {
bla_bla_bla_bla.printStackTrace();
}
if (_count % 2 == 0) {
try {
jta.getHighlighter().addHighlight(1, _lenght - 1, cyanPainter);
} catch (BadLocationException bla_bla_bla_bla) {
}
} else if (_count % 3 == 0) {
try {
jta.getHighlighter().addHighlight(1, _lenght - 1, redPainter);
} catch (BadLocationException bla_bla_bla_bla) {
}
} else {
try {
jta.getHighlighter().addHighlight(1, _lenght - 1, whitePainter);
} catch (BadLocationException bla_bla_bla_bla) {
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Fonts fs = new Fonts();
}
});
}
}
In the absence of a good SSCCE, I really don't know how you adding colour to the text on your JTextPane, but hopefully this method might sort things out for you :
import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
private void appendToTextPane(String name, Color c, String f)
{
StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);
aset = sc.addAttribute(aset, StyleConstants.FontFamily, f);
int len = Client.nPane.getDocument().getLength();
textPane.setCaretPosition(len);
textPane.setCharacterAttributes(aset, true);
textPane.replaceSelection(name);
}
With this you can give a different Color and Font to each String literal that will be added to your JTextPane.
Hope this new Code might help you in some way :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
public class TextPaneTest extends JFrame
{
private JPanel topPanel;
private JPanel bottomPanel;
private JTextPane tPane1;
private JTextPane tPane2;
private JButton button;
public TextPaneTest()
{
topPanel = new JPanel();
topPanel.setLayout(new GridLayout(1, 2));
bottomPanel = new JPanel();
bottomPanel.setBackground(Color.BLACK);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.BLUE);
aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console");
tPane1 = new JTextPane();
tPane1.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));
tPane1.setCharacterAttributes(aset, false); // Add these settings to the other JTextPane also
tPane2 = new JTextPane();
tPane2.setCharacterAttributes(aset, false); // Mimic what the other JTextPane has
button = new JButton("ADD TO THE TOP JTEXTPANE");
button.setBackground(Color.DARK_GRAY);
button.setForeground(Color.WHITE);
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
tPane1.setText(tPane2.getText());
}
});
add(topPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
topPanel.add(tPane1);
topPanel.add(tPane2);
bottomPanel.add(button);
pack();
tPane2.requestFocusInWindow();
setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TextPaneTest();
}
});
}
}
Regards
This has been solved by merging the document models of the two panes. The solution is in this question: Keeping the format on text retrieval
1) how can I set Cursor to 0 possition without using Caret or Focus wrapped into invokeLater() (confortly can be solved by using #camickr Formatted Text Field Tips), is there somebody who knows another way
2) How to reset Formatter sometimes (by raising Focus by TAB from keyboard), reset doesn't works and on focusLost (empty field) Formatter returns/reincarnated chars or String back (last know before setText("");),
Note: know code or following code is only this way, about how to reset Formatter from OTN, but their terrible search rulles ...., only code (question or answer by Jeanette???)
import java.awt.event.*;
import java.beans.*;
import java.text.ParseException;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.Document;
public class FormattedNull {
private JFormattedTextField field;
private JButton focusButton;
private JComponent createContent() {
JComponent content = new JPanel();
field = new JFormattedTextField(new Integer(55));
field.setColumns(20);
field.addPropertyChangeListener(getPropertyChangeListener());
field.getDocument().addDocumentListener(getDocumentListener());
content.add(field);
focusButton = new JButton("just something focusable");
focusButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
field.setValue(0);
field.requestFocusInWindow();
}
});
content.add(focusButton);
return content;
}
protected void maybeCommitEdit(Document document) {
try {
field.commitEdit();
} catch (ParseException e) {
// uncomment to map empty string to null
if (field.getText().length() == 0) {
field.setValue(null);
}
}
}
/*public void commitEdit() throws ParseException {
if(allowsNull() && isBlank()) {
setValue(null);
}
else {
super.commitEdit();
}
}*/
private PropertyChangeListener getPropertyChangeListener() {
PropertyChangeListener propertyChangeListener = new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if ("value".equals(evt.getPropertyName())) {
matchValueChanged(evt.getNewValue());
}
}
};
return propertyChangeListener;
}
protected void matchValueChanged(Object value) {
System.out.println("got new value: " + value);
}
private DocumentListener getDocumentListener() {
DocumentListener documentListener = new DocumentListener() {
#Override
public void removeUpdate(DocumentEvent e) {
maybeCommitEdit(e.getDocument());
}
#Override
public void insertUpdate(DocumentEvent e) {
maybeCommitEdit(e.getDocument());
}
#Override
public void changedUpdate(DocumentEvent e) {
}
};
return documentListener;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new FormattedNull().createContent());
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
});
}
}
attached images are based on my sscce
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.text.MaskFormatter;
public class TestTest {
private JFormattedTextField myFormattedField1 = new JFormattedTextField(createFormatter("AAAAAAAAAAAA"));
private JFormattedTextField myFormattedField2 = new JFormattedTextField(createFormatter("AAAAAAAAAAAA"));
private JFormattedTextField myFormattedField3 = new JFormattedTextField(createFormatter("AAAAAAAAAAAA"));
private JFormattedTextField myFormattedField4 = new JFormattedTextField(createFormatter("AAAAAAAAAAAA"));
private JButton jb = new JButton("Reset to Default");
private JFrame frame = new JFrame("Text Test");
public TestTest() {
myFormattedField1.setText("ABCDEFGHIJKL");
myFormattedField2.setText("ABCDEFGHIJKL");
myFormattedField3.setText("ABCDEFGHIJKL");
myFormattedField4.setText("ABCDEFGHIJKL");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(150, 150);
frame.setLayout(new GridLayout(5, 0));
frame.add(jb);
frame.add(myFormattedField1);
frame.add(myFormattedField2);
frame.add(myFormattedField3);
frame.add(myFormattedField4);
jb.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
myFormattedField1.setText("");
myFormattedField2.setText("");
myFormattedField3.setText("");
myFormattedField4.setText("");
}
});
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
TestTest textTest = new TestTest();
}
protected MaskFormatter createFormatter(String s) {
MaskFormatter formatter = null;
try {
formatter = new MaskFormatter(s);
} catch (java.text.ParseException exc) {
System.err.println("formatter is bad: " + exc.getMessage());
}
return formatter;
}
}
On Mac OS, the default behavior of the UI delegate, com.apple.laf.AquaTextFieldF, is similar to CaretPositionListener:
Tab or Shift-Tab: place the caret at the beginning of the field.
Click: briefly place the caret at the beginning of the field and then move it to the click point.
IMO, the CaretPositionListener does the latter much more smoothly.
The default behavior of JFormattedTextField on focus lost is COMMIT_OR_REVERT. In the example below, Tab though the first, invalid field to see the effect. The formatter can neither commit nor revert to the invalid value, so it substitutes MASK.length() spaces. This value is valid, if a little obscure.
Addendum: I've updated the code below to allow changing the setFocusLostBehavior().
Code:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.text.MaskFormatter;
/** #see http://stackoverflow.com/questions/7378821 */
public class TrashTest {
private static final String MASK = "########";
private static final String DEFAULT = "01234567";
private static final String BOGUS = "0123456";
private JFormattedTextField jtf1 = createField();
private JFormattedTextField jtf2 = createField();
private JFormattedTextField jtf3 = createField();
private JFormattedTextField jtf4 = createField();
private JButton reset = new JButton("Reset to Default");
private JComboBox combo = new JComboBox();
private JFrame frame = new JFrame("Text Test");
public TrashTest() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(150, 150);
frame.setLayout(new GridLayout(0, 1));
frame.add(reset);
frame.add(jtf1);
frame.add(jtf2);
frame.add(jtf3);
frame.add(jtf4);
frame.add(combo);
this.initFields();
reset.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
initFields();
}
});
for (Edit e : Edit.values()) {
combo.addItem(e);
}
combo.setSelectedIndex(jtf1.getFocusLostBehavior());
combo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Edit current = (Edit) combo.getSelectedItem();
jtf1.setFocusLostBehavior(current.value);
}
});
frame.pack();
frame.setVisible(true);
}
private void initFields() {
jtf1.setText(BOGUS);
jtf2.setText(DEFAULT);
jtf3.setText(DEFAULT);
jtf4.setText(DEFAULT);
}
protected JFormattedTextField createField() {
MaskFormatter formatter = null;
try {
formatter = new MaskFormatter(MASK);
} catch (java.text.ParseException e) {
e.printStackTrace(System.out);
}
JFormattedTextField jtf = new JFormattedTextField(formatter);
return jtf;
}
enum Edit {
COMMIT(JFormattedTextField.COMMIT),
COMMIT_OR_REVERT(JFormattedTextField.COMMIT_OR_REVERT),
REVERT(JFormattedTextField.REVERT),
PERSIST(JFormattedTextField.PERSIST);
private int value;
private Edit(int n) {
this.value = n;
}
public static Edit getEnum(int n) {
for (Edit e : Edit.values()) {
if (e.value == n) {
return e;
}
}
return Edit.COMMIT_OR_REVERT;
}
}
public static void main(String[] args) {
TrashTest textTest = new TrashTest();
}
}