TextArea text style does not change to plain from italic in Java - java

I have two RadioButton to select either Italic or Plain Style for a TextArea.(They are added to ButtonGroup so only one can be selected)
I have the actionPerformed method as
public void actionPerformed(ActionEvent ae) {
Font currentFont = taText.getFont(); //taText is TextArea
Font fontToSet;
String command = ae.getActionCommand();
if (command.equals("Italic")) {
System.out.println("Italic clicked");
fontToSet = new Font(currentFont.getFontName(),Font.ITALIC,currentFont.getSize());
}
else {
System.out.println("Plain clicked");
fontToSet = new Font(currentFont.getFontName(), Font.PLAIN, currentFont.getSize());
}
taText.setFont(fontToSet);
}
The problem is that when I click on "Italic", the text becomes italic, but when clicking Plain, text does not become plain. Yet the message Plain Clicked gets displayed on command line.
What is the problem?

change your code to
public void actionPerformed(ActionEvent ae) {
Font currentFont = taText.getFont(); //taText is TextArea
Font fontToSet;
String command = ae.getActionCommand();
if (command.equals("Italic")) {
System.out.println("Italic clicked");
fontToSet =currentFont .deriveFont(Font.ITALIC);
else {
System.out.println("Plain clicked");
fontToSet = currentFont .deriveFont(Font.PLAIN);
}
taText.setFont(fontToSet);
}
the problem is , getFontName() calls Font2D to get the name and it returns the value based on the current applied styles, but getName() will still return the same font name. but better to use deriveFont();

Related

How to detect changes in text in many JTextPane

I would like to create simply text editor with dynamic amount of tabs. Every tab consist of text field, where someone can load text file and edit or write own text.
I would like to detect changes in tabs, I mean when someone change file and wants close then I'd like to show a dialog about whether you want save changes or no. this is reason why I'd like to follow changes which user committed.
So I have
JTabbedPane tabbedPane with JtextPane textPane
private LinkedList<Boolean> changedList = new LinkedList<Boolean>(); // here I thought of collecting information about changes but it was silly idea.
This is function which I create new Tab
public void newTab()
{
tabbedPane.addTab("tab-" + counter++, new JTextPane());
int totalTabs = tabbedPane.getTabCount();
selected = tabbedPane.getComponentAt(totalTabs-1);
changedList.add( totalTabs-1, false);
textPane = (JTextPane)selected;
textPane.getDocument().addDocumentListener(this);
}
these are function from interface
#Override
public void insertUpdate(DocumentEvent e)
{
changedList.add(tabbedPane.getSelectedIndex(), true);
}
#Override
public void removeUpdate(DocumentEvent e)
{
changedList.add(tabbedPane.getSelectedIndex(), true);
}
#Override
public void changedUpdate(DocumentEvent e)
{
changedList.add(tabbedPane.getSelectedIndex(), true);
}
This is how I've tried to save
public void saveAfterChange()
{
if (changedList.get(tabbedPane.getSelectedIndex()))
{
int reply = JOptionPane.showConfirmDialog(null, "Save?", null, JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_NO_OPTION)
{
save();
}
}
}

How to combine and validate two text fields for a swt dialog?

i have another question. I use a ModifyListener for one textfield to activate and deactivate the OK-Button in a swt dialog. It works great.
Now I want to add a ModifyListener for another textfield. I want that the OK-Button only is activated if in both text fields is min one char.
This is the code of the two fields:
descriptionText.addModifyListener(new ModifyListener(){
public void modifyText(ModifyEvent e) {
Text text = (Text) e.widget;
if (text.getText().length() == 0) {
getButton(IDialogConstants.OK_ID).setEnabled(false);
}
if (text.getText().length() >= 1) {
getButton(IDialogConstants.OK_ID).setEnabled(true);
}
}
});
}
the second field:
ccidText.addModifyListener(new ModifyListener(){
public void modifyText(ModifyEvent e) {
Text text = (Text) e.widget;
if (text.getText().length() == 0) {
getButton(IDialogConstants.OK_ID).setEnabled(false);
}
if (text.getText().length() >= 1){
getButton(IDialogConstants.OK_ID).setEnabled(true);
}
}
});
}
I know that it doesn´t work because there are no dependencies between the two buttons.
How can i combine it?
I want to set the ok-button false while both modifylistener detect a char.
If i delete all chars in one testfield the button must be deactivated again.
Thank u.
You can use the same Listener for both Text fields and add it for SWT.KeyUp:
public static void main(String[] args)
{
final Display display = new Display();
Shell shell = new Shell(display);
shell.setText("StackOverflow");
shell.setLayout(new FillLayout(SWT.VERTICAL));
final Text first = new Text(shell, SWT.BORDER);
final Text second = new Text(shell, SWT.BORDER);
final Button button = new Button(shell, SWT.PUSH);
button.setText("disabled");
button.setEnabled(false);
Listener listener = new Listener()
{
#Override
public void handleEvent(Event e)
{
String firstString = first.getText();
String secondString = second.getText();
button.setEnabled(!isEmpty(firstString) && !isEmpty(secondString));
button.setText(button.isEnabled() ? "enabled" : "disabled");
}
};
first.addListener(SWT.KeyUp, listener);
second.addListener(SWT.KeyUp, listener);
shell.pack();
shell.setSize(300, shell.getSize().y);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
private static boolean isEmpty(String input)
{
if(input == null)
return true;
else
return input.trim().isEmpty();
}
Looks like this:
The code will basically (on each key stroke) check if both Texts are empty. If so, disable the Button, else enable it.

Getting information from Event

I'm using ModifyListener to get information from Text that changes.
Is there a way to get the Text's text in the listener (like a method of Event e)?
Thank you!
Next example helps you :
Text text = new Text(shell, SWT.SINGLE);
text.addModifyListener(new ModifyListener() {
#Override
public void modifyText(ModifyEvent e) {
Text source = (Text) e.getSource();
System.out.println("text = " + source.getText());
}
});
text.pack();
According to docs e.getSource() return:
The object on which the Event initially occurred.

Add colored String with italic font style to Tool Tip Text

How to add colored String with italic font style to Tool Tip Text?
Actually I have overridden the getToolTipText(MouseEvent e) method from JComponent in Core java and added some tooltiptext Strings in to it, now i want to add one more String to it with Italic font and Red color . Can you please tell me how to add colored string to ToolTipText in Java, I tried using HTML but i did not get the result.
String message= "<html><p style='font-style:italic;color:red;'> Minor </p> </html> ";
I tried above HTML for the 'Minor' string to add that in to ToolTipText but it displaying all the HTML content in the ToolTipText.
..overridden the getToolTipText(Mouseevent e)
Why not just set the tool tip text? A strategy which seems to work just fine here. E.G.
import javax.swing.*;
class StyledToolTip {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
String s= "<html><p style='font-style:italic;color:red;'>" +
"Minor</p></html> ";
JLabel lbl = new JLabel(s);
lbl.setToolTipText(s);
JOptionPane.showMessageDialog(null, lbl);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}

Keeping the format on text retrieval

I am making a network application that has a chat function. On the chat I have one JTextPane
for displaying messages and one more for input. Then I have some buttons that allow to add style on the input text(bold,italic,font size,colour). The text is formatted correctly on input pane , although when moved to the display pane(once the correct JButton is pressed) it only has the format of last character. How can I move the text while keeping its original format?For example if I write "Hello Worl d" on the input , display shows "Hello Worl d"
textPane is the input pane
Where set :
final SimpleAttributeSet set = new SimpleAttributeSet();
Code for making input text bold(same of adding other styles) :
bold.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
StyledDocument doc = textPane.getStyledDocument();
if (StyleConstants.isBold(set)) {
StyleConstants.setBold(set, false);
bold.setSelected(false);
} else {
StyleConstants.setBold(set, true);
bold.setSelected(true);
}
textPane.setCharacterAttributes(set, true);
}
});
code for moving text from the input pane to the display pane :
getInput.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String input = textPane.getText();
textPane.setText("");
if(!input.endsWith("\n")){
input+="\n";
}
StyledDocument doc = displayPane.getStyledDocument();
int offset = displayPane.getCaretPosition();
try {
doc.insertString(offset, input, set);
} catch (BadLocationException ex) {
Logger.getLogger(ChatComponent.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
Use the example to merge both Documents
http://java-sl.com/tip_merge_documents.html

Categories

Resources