I'm trying to make a text editor with a JTextPane, but i'm having trouble with setting the selected texts color. Here is the best could come up with (but, obviously, not working):
JMenuItem button = new JMenuItem("Set Color");
toolbar.add(button);
button.addActionListener(new ActionListener( ) {
public void actionPerformed(ActionEvent e) {
Color c = JColorChooser.showDialog(frame,"Choose a color", getBackground());
textPane.getSelectedText().StyledEditorKit.ForegroundAction("color",c);
}
});
Any suggestions on how to get that to work? Or a better method of doing it?
Thanks
getSelectedText() just returns a normal string containing the selected text; you cannot use it to modify the attributes of the text.
I would start by using SimpleAttributeSet and StyleConstants to generate the colour attribute, then apply it to the selected portion of your text:
SimpleAttributeSet attr = new SimpleAttributeSet();
StyleConstants.setForeground(attr, c);
textPane.setCharacterAttributes(attr, false);
Related
I am trying to figure out why my text isn't being displayed here. I assume it isn't being colored white, and simply doesn't show up against the black background. So, I'm trying to figure out why the background is being colored black, but the text isn't being shown.
I am using JavaFX 12.
How can I color the letters white?
public class MCVE extends Application {
private static Stage gameStage = new Stage();
#Override
public void start(Stage primaryStage) {
gameStage.setScene(new Scene(createScreen(), 1280.0, 800.0));
// adjust window settings.
gameStage.setTitle("my game");
gameStage.setResizable(false);
gameStage.show();
}
private Pane createScreen() {
Text welcome = new Text("Welcome,");
welcome.setFont(new Font("Old_Style", 22.0));
welcome.setStyle("-fx-text-fill: whitesmoke");
Text toMyGame = new Text(" to my game.");
toMyGame.setFont(new Font("System", 14.0));
toMyGame.setStyle("-fx-text-fill: whitesmoke");
TextFlow tf = createTextFlow();
ObservableList list = tf.getChildren();
list.addAll(welcome, toMyGame);
return tf;
}
private TextFlow createTextFlow() {
String style = "-fx-background-color: black;";
style += " -fx-text-fill: whitesmoke;";
TextFlow tf = new TextFlow();
tf.setStyle(style);
return tf;
}
}
-fx-text-fill is a CSS property of Labeled, not Text. Text is a type of shape, and Shape supports -fx-fill rather than -fx-text-fill.
Changing every occurrence of -fx-text-fill to -fx-fill should give you the appearance you want.
This may end up being noted as a formerly asked question, however the other questions have yet to answer the question that I have asked properly, to what I need them to do.
I want it to be that whenever I click the ToggleButton it will set the color of the ToggleButton to black (in this case), and then when I unclick the button it will return to the default color.
Here is the code for the individual button, its possible Ill have to create a new class (I am using Eclipse) but if anyone could help id be extremely thankful. (I also have Jigloo)
jToggleButton4 = new JToggleButton();
getContentPane().add(jToggleButton4);
FlowLayout jToggleButton4Layout = new FlowLayout();
jToggleButton4.setLayout(jToggleButton4Layout);
jToggleButton4.setText("Black");
jToggleButton4.setPreferredSize(new java.awt.Dimension(133, 249));
You can take the default color/ the color you keep initially and can toggle the background color with an ActionEvent,
JToggleButton jtb = new JToggleButton("My Button");
Color defaultColor=jtb.getBackground();
jtb.addActionListener(new ActionListener( ) {
public void actionPerformed(ActionEvent ev) {
if(jtb.getBackground()==defaultColor)
jtb.setBackground(Color.BLACK);
else
jtb.setBackground(defaultColor);
repaint();//repaint your frame
System.out.println("BackGround color changed!");
}
});
I am doing a simple text editor and have a combo box filled with the font names. However I can't manage to make the program change the font of the text area when a new font is selected form the combo box. I was using this line of code to try and make it work.
txtArea.setFont(new Font("Serif", Font.ITALIC, 16));
I need to replace "Serif" with some kind of variable to change from the font from the selected font type from the combo box.
All help will be really appreciated.
OK, if your combo box is filled with available font names, you can try like this:
fontComboBox.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
txtArea.setFont(new Font((String) fontComboBox.getSelectedItem(), Font.ITALIC, 16));
}
}
});
How can I remove OR change colour of the border surrounding these tabs?
ALSO, is it possible to have the tab text change colour when the mouse is hovering over it?
Is it possible to have the tab text change colour when the mouse is
hovering over it?
As stated in this answer you can set a custom component for rendering the tab title, through JTabbedPane.setTabComponentAt(int index, Component component) method. So you can do something like this:
final JTabbedPane tabbedPane = new JTabbedPane();
MouseListener mouseListener = new MouseAdapter() {
Color defaultColor;
#Override
public void mouseEntered(MouseEvent e) {
JLabel label = (JLabel)e.getSource();
defaultColor = label.getForeground();
label.setForeground(Color.BLUE);
}
#Override
public void mouseExited(MouseEvent e) {
JLabel label = (JLabel)e.getSource();
label.setForeground(defaultColor);
}
#Override
public void mouseClicked(MouseEvent e) {
JLabel label = (JLabel)e.getSource();
Point point = SwingUtilities.convertPoint(label, e.getPoint(), tabbedPane);
int selectedTab = tabbedPane.getUI().tabForCoordinate(tabbedPane, point.x, point.y);
switch(e.getButton()){
case MouseEvent.BUTTON2: tabbedPane.removeTabAt(selectedTab); break;
default: tabbedPane.setSelectedIndex(selectedTab);
}
}
};
JLabel tab1 = new JLabel("Tab1");
tab1.addMouseListener(mouseListener);
tabbedPane.addTab(null, new JPanel());
tabbedPane.setTabComponentAt(0, tab1);
How can I remove OR change colour of the border surrounding these
tabs?
It's up to the Look and Feel decide the border color in this case. You should look into the L&F default properties and see if it's allowed change this color. For instance you could execute the following code to see L&F default properties (of course after setting the L&F):
for(Object key : UIManager.getLookAndFeelDefaults().keySet()){
System.out.println(key + " = " + UIManager.get(key));
}
I want to show error(text) in result in red color after compiling exec file
and display it in textarea of gui using swing in java.
A normal JTextArea doesn't support fancy things like different colors of text. However, there are similar components that do. See http://java.sun.com/docs/books/tutorial/uiswing/components/text.html
JEditorPane can get content formatted in HTML. The official Sun tutorial also gives some insight:
The JTextArea class provides a component that displays multiple lines of text and optionally allows the user to edit the text. If you need to obtain only one line of input from the user, you should use a text field. If you want the text area to display its text using multiple fonts or other styles, you should use an editor pane or text pane. If the displayed text has a limited length and is never edited by the user, use a label.
Here's a quick example of adding text to a JEditorPane using AttributeSet and StyleConstants.
This brings up a little frame with a JEditorPane and you can use it to add text of lots of colors without using HTML.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.text.*;
import javax.swing.border.*;
public class TextColor extends JFrame implements ActionListener {
JTextPane myTextPane;
JTextArea inputTextArea;
public TextColor() {
super();
JPanel temp = new JPanel(new BorderLayout());
inputTextArea = new JTextArea();
JButton btn = new JButton("Add");
btn.addActionListener(this);
temp.add(btn, BorderLayout.SOUTH);
temp.add(inputTextArea, BorderLayout.NORTH);
this.getContentPane().add(temp, BorderLayout.SOUTH);
myTextPane = new JTextPane();
myTextPane.setBorder(new EtchedBorder());
this.getContentPane().add(myTextPane, BorderLayout.CENTER);
this.setSize(600, 600);
this.setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
Color newTextColor = JColorChooser.showDialog(this, "Choose a Color", Color.black);
//here is where we change the colors
SimpleAttributeSet sas = new SimpleAttributeSet(myTextPane.getCharacterAttributes());
StyleConstants.setForeground(sas, newTextColor);
try {
myTextPane.getDocument().insertString(myTextPane.getDocument().getLength(),
inputTextArea.getText(), sas);
} catch (BadLocationException ble) {
ble.printStackTrace();
}
}
public static void main(String args[]) {
new TextColor();
}
}
Smita,
take care to paste snippet of your code so that one can understand where exactly problem is or help is required.
Coming to your problem,
To the best of my knowledge, there is no way to set different colors for different text elements in textArea in java. You can set only one color for all.
Alternative is to use JTextPane.
See if following code helps your cause.
String text = "Some Text..."; //This can be any piece of string in your code like
output of your program...
JTextPane myTextPane = new JTextPane();
SimpleAttributeSet sas = new SimpleAttributeSet(myTextPane.getCharacterAttributes());
// As what error you were referring was not clear, I assume there is some code in your
program which pops out some error statement. For convenience I use Exception here..
if( text.contains("Exception") ) //Checking if your output contains Exception...
{
StyleConstants.setForeground(sas, Color.red); //Changing the color of
StyleConstants.setItalic(sas, true);
try
{
myTextPane.getDocument().insertString
(
myTextPane.getDocument().getLength(),
text + "\n",
sas
);
}
catch( BadLocationException ble )
{
text.append(ble.getMessage());
}
}
else
{
StyleConstants.setForeground(sas, Color.GREEN);
try
{
myTextPane.getDocument().insertString
(
myTextPane.getDocument().getLength(),
text + "\n",
sas
);
}
catch(BadLocationException ble)
{
text.append(ble.getMessage());
}
}
I guess this will solve your problem with few modifications.
Thanks.
Sushil