I'm trying to call a method from a class called Circle in my project which displays some basic information about the object in a JLabel. For some reason the text won't go to a new line even when I use HTML to try and format it:
#Override
public String toString(){
return "<html>Type: " + this.getClass().getSimpleName() + "<br>Radius: " + getRadius() + "<br>Area: " + df.format(getArea()) + "<br>Perimeter: </html>" + df.format(getPerimeter());
}
I'm trying to display the info with this code:
#Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource()==btnCalc && x==1){
//create object
double R = Double.parseDouble(Txt1.getText());
Circle circ = new Circle(R);
lblResult.setText(circ.toString());
}
When I run the program it just returns this:<html>Type: Circle<br>Radius: 4.0<br>Area: 50.27<br>Perimeter:</html> 25.13
edit: I tried just setting the text as an exception message instead of calling the method and it didn't work this way either
edit: Now this happens when I try to run the cylinder-sphere classes, but it doesn't do that when I don't have any html in the toString() method.
Turns out I was using a DecimalFormat in the last four classes which was what was giving me the exception. Once I got rid of that, the strings formatted nicely using a JTextPane instead of a JtextField.
From the image you pasted, it looks like it is a text INPUT control (under Show Info button), like JTextField and not a JLabel.
You can use HTML content with JLabel constructor as well as with its setText method too. It works fine.
JLabel lbl = new JLabel("<html>Type: Circle<br>Some info<br>More info</html>")
JLabel lbl2 = new JLabel();
lbl2.setText("<html>Type: Circle<br>Some info<br>More info</html>")
But if you want to have an INPUT control (as in your image), you can not use HTML with JTextField. You have to use JTextPane for this.
JTextPane txt = new JTextPane();
txt.setContentType("text/html");
txt.setText("<html>Type: Circle<br>Some info<br>More info</html>");
Related
I am trying to make a simple word processor that edits the text to make it bold, italic, underline, background color and foreground color. The problem is I want to set the contents/text of the JTextPane with all its edited attributes to a single object to save it to another class as a data field which have other data fields like date created and the name of the document given by the user.
I think the best approach its using html as content type for the Text Pane and string builders.
for example,
TextPane tp = new JTextPane();
tp.setContentType("text/html");
StringBuilder sb = new StringBuilder();
sb.append("<span style=\"color:red\">" + Hello red + "</span>");
sb.append("<span style=\"color:blue\">" + Hello blue + "</span>");
...
tp.setText(sb); // will print text with the style
works the same in the other way,
String txt = tp.getText();
System.print(txt); //wil show html code
You can reference http://www.java2s.com/Tutorials/Java/Swing_How_to/JTextPane/Style_JTextPane_with_HTML_and_CSS.htm
I'm working on a program that serves as a hypothetical email system in which users can be created and can send messages to other users that have been created.
The message will be stored in a "Message" class, and the text is typed in a JTextArea in a GUI. What I want to know is how I would go about storing the text typed into the JTextArea, in the exact same layout (indentations and all), within the Message class. I thought about text files but then there would have to be one for each message, potentially creating an infinite number of them, and I don't like the concept of having to make a system for coming up with unique names for each text file.
Can you please give me some advice?
Simply implement the DocumentListener interface, then do the following:
JTextArea someMessage = new JTextArea();
someMessage.getDocument().addDocumentListener(new MyDocumentListener());
someMessage.getDocument().putProperty("name", "Text Area");
Here, we assume the name of the listener you implement is called MyDocumentListener, and the implementation could be as simple as:
class MyDocumentListener implements DocumentListener {
String newline = "\n";
#Override
public void insertUpdate(DocumentEvent e) {
updateLog(e, "inserted into");
}
#Override
public void removeUpdate(DocumentEvent e) {
updateLog(e, "removed from");
}
#Override
public void changedUpdate(DocumentEvent e) {
//Plain text components do not fire these events
}
public void updateLog(DocumentEvent e, String action) {
Document doc = (Document)e.getDocument();
int changeLength = e.getLength();
displayArea.append(
changeLength + " character" +
((changeLength == 1) ? " " : "s ") +
action + doc.getProperty("name") + "." + newline +
" Text length = " + doc.getLength() + newline);
}
}
Examples taken from Oracle website. I recommend reading the rest of that article as it goes into much depth of how to effectively listen for updates to the internal document model.
How to get text that was inserted
insertUpdate is what notifies you when new text has been typed into the textarea. You can get the freshly inserted text by calling off to the DocumentEvent#getOffset and DocumentEvent#getLength. Using both methods, you can get the offset (index) within document where the insertion happened, as well as the length of the change.
Then to get the actual text that was inserted, you call DocumentEvent#getDocument#getText and supplying the offset and length you got from the event.
How to get all the text in the textarea
You can use this similar method to get the entire text in the document by making use of Document#getStartPosition and Document#getEndPosition, then calling Document#getText.
Or even easier, JTextArea#getText
I'm working on a application which takes pizza orders. Once the user clicks the order summary button the program would display the order summary. The application looks like this:
I would like to print out the order summary(only not the error) in a new penal with a JTextArea like such:
But I don't know how. This is what my application displays right now:
Here is the Code related to the display:
orderSummary = "Customer Name: " + name +
"\nPhone Number: " + phoneNumber +
"\nSize: " + size +
"\nToppings: " + toppings +
"\nTotal: $" + total;
if(error)
JOptionPane.showMessageDialog(null, ErrorString);
else
JOptionPane.showMessageDialog(null, orderSummary);
Error display:
I'm not 100% sure of what you are asking, but if you are looking for a dialog to popup (not just a panel), then you could try something like:
JDialog zMessageDialog = new JDialog((java.awt.Frame) null, true);
zMessageDialog.setTitle("Order summary");
zMessageDialog.setLayout(new BorderLayout());
JTextArea zTextArea = new JTextArea("Blah blah\nblah blah\nblah blah");
zTextArea.setEditable(false);
zTextArea.setColumns(40);
zTextArea.setRows(10);
zTextArea.setBackground(null);
JScrollPane zScrollPane = new JScrollPane(zTextArea);
zMessageDialog.add(zScrollPane, BorderLayout.CENTER);
zMessageDialog.revalidate();
zMessageDialog.pack();
zMessageDialog.setVisible(true);
This just puts a JTextArea in a JDialog. It makes the JTextArea non-editable, and sets its background color to null (which makes it look less editable).
Of course, this may not be the best way to go in terms of a user interface, but that is a different question. If you are using an IDE like Netbeans, you can easily create a separate class based on JDialog and add a panel at the bottom with an "OK" button, and whatever other customizations you desire.
I have a piece in my code that formats a string, appends html/css tags and then adds the text to a JTextPane. I create the textPane in some panel's constructor with the following:
public PnlSmartCommands(ServerLogFormatter formatter, ServerCommandsComponent container){
setLayout( new java.awt.BorderLayout() );
this.container = container;
txtServerCommands = new JTextPane();
txtServerCommands.setContentType("text/html");
scpServerCommands = new JScrollPane( );
this.formatter = formatter;
scpServerCommands.setViewportView( txtServerCommands );
scpServerCommands.getVerticalScrollBar().setUnitIncrement(16);
scpServerCommands.getHorizontalScrollBar().setUnitIncrement(50);
add( scpServerCommands, java.awt.BorderLayout.CENTER );
txtServerCommands.setEditable(false);
loadRules(txtServerCommands);
and I add text to the pane with a formatting function that takes all previous requests from an ArrayList, deletes all found HTML tags, formats it and then adds new HTML and BODY tags, and then use .setText(String arg0) to set the text to a JTextPane.
public String formatMemoryString(){
StringBuilder sb = new StringBuilder();
sb.append("<html>");
sb.append("<body>");
for(int i=0;i<logMemoryHolder.size(); i++){
sb.append(logMemoryHolder.get(i));
if(!(i==logMemoryHolder.size())){
sb.append("<br>");
}
}
sb.append("</body>");
sb.append("</html>");
return sb.toString();
Now here's the problem - the response is always fit into the box over multiple lines, not on a single line. While this is actually good, I need to add functionality to span it over a single line. ! http://i.stack.imgur.com/zy4yC.jpg - this is what it looks like currently. I would like to add a checkbox that formats the value as a single line, or allows the textPane to do so. Any idea how I go about doing that? The HTML that I put into the pane is as follows : http://www.upload.ee/files/3501071/testHtml.html.html
Thanks in advance!
I have a form for the user to fill out in a JFrame which then writes the collected data to a JTable in a different class.
I'm trying to configure it that when the user selects "Submit" that the JFrame will close, but not close down the program. What would be the command I need to achieve this?
The code for the submit button is as follows is as follows:
JButton bMark = new JButton("Submit");
bMark.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String start = tbStart.getText();
String end = tbEnd.getText();
String[] marking = {start, end, active, body, dysk, trem, brady};
//This is just for me to ensure the collected data is correct
System.out.println(marking[0] + " " +marking[1] + " " +marking[2] + " " +
marking[3] + " " + marking[4] + " " + marking[5] + " " + marking[6]);
//This is is the class the form data is being sent to
markTable.main(marking);
//This is where I would like the close the current window
}
});
bMark.setBounds(308, 191, 86, 23);
The class name is createMark and the method is public createMark
Thanks to anyone who replies,
Jared.
//This is where I would like the close the current window
there are these ways
JFrame#setVisible(false), but not terminating current JVM, this session exist until PC restarted,
JFrame#dispose() terminating current JVM,
System#exit(int); terminating current JVM,
better would be to JFrame#setDefaultCloseOperation
don't suplly JOptionPane, maybe will be better use that directly
You need to set the default close operation on the JFrame as such:
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
This will take care of the case where the user closes the window using the title bar or hits something like Alt+F4.
Next, simply call setVisible(false) when the submit button is pressed.