Text align in JLabel [duplicate] - java

This question already has answers here:
Align text in JLabel to the right
(3 answers)
Closed 9 years ago.
I've got GridLayout-JPanel. In every cell there is a JLabel with some String. How can I right-align this text in my cells?

#Noran In response to your comment on #mre's answer, you could initialize all the JLabels into an array. Then, all you'd have to do is loop through the array and set the alignment that way.
for (JLabel label: arrayOfJLabels) {
label.setHorizontalAlignment(SwingConstants.LEFT);
}

A couple JLabel constructors take horizontal alignment arguments. These constants are inherited from SwingConstants.

I have read your question and I have a suggestion. There are a few methods to fulfill your requirement. Since you didn't mention the exact requirement, I can give you a simple example as I understand it:
//create a JLabel and name it as jLabel2
javax.swing.JLabel jLabel2 = new javax.swing.JLabel();
jLabel2.setText("Dehans Label");
jLabel2.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
Please refer following methods # JLabel class in JavaSE API through following links:
public void setHorizontalAlignment(int alignment)
public void
setVerticalAlignment(int alignment)
public void
setVerticalTextPosition(int textPosition)

Related

how to add the same JLabel to multiply JLabels in java?

i writing gui for my program in java, and i want to show some jlabel in multiply jlabels. im using gridlayout.
parts of code:
protected JLabel myLbl = new JLabel("1");
protected JLabel first = new JLabel("2");
protected JLabel second = new Jlabel("3");
in the constructor:
this.first.add(myLbl);
this.second.add(myLbl);
I saw a few questions on the subject, here in StackOverFlow, but I could not find a solution there without creating a duplicate JLabels.. And without creating another layout.
Is there a way to do this without creating a new layout or duplicate JLabels?
Thanks

only one JLabel displaying at a time (Java Swing) [duplicate]

This question already has an answer here:
Only one component shows up in JFrame
(1 answer)
Closed 6 years ago.
I created one JLabel as a heading and customised it, which displayed with no issue. The problem came when I attempted to create a second JLabel, as only the second JLabel would display. When I created a third one, only that would display but not the first and second.
Basically, only the latest JLabel is being displayed. How can I have multiple JLabel's displayed simultaneously.
Here is my code.
public class MainForm extends JFrame {
EmployeeDAO dao = new EmployeeDAO();
private static JLabel label, name;
MainForm()
{
super("Employee Database");
GUI();
}
private void GUI()
{
JLabel label = new JLabel("Enter Employee Information");
label.setVerticalAlignment(JLabel.TOP);
label.setHorizontalAlignment(JLabel.CENTER);
label.setFont(new Font("Serif", Font.PLAIN, 20));
label.setForeground(Color.red);
add(label);
JLabel name = new JLabel("Name: ");
add(name);
}
}
Usually, when you want to add more than one component to a container (as you're doing with the JLabels in the JFrame) you must decide which layout manager do you want to use so that components are displayed in the positions you want.
You should probably take a look at the tutorials related to laying out components in containers.
You will need to select a Layout Manager, and call setLayout accordingly.
Use .setBounds for each element you are adding to your scene, or use another layout such as grid layout to position your UI elements. The problem stems from when you add a new element, it goes on top of previous one.

How to display a default message in JTextField java [duplicate]

This question already has answers here:
Java JTextField with input hint
(9 answers)
Adding a watermark to an empty JCombobox
(2 answers)
Closed 10 years ago.
I want to create a JTextField with a message inside as a deafult. But not as a proper text but as a comment about what to type inside the JTextField.
So if i type jtf.getText() it returns null or empty because it is just a comment that was printed there. When you click on it then it disappears and you can write whatever you want on it. Is there any method to do such a thing?
A possible technique is to first set the default string as the text of the textField:
JTextField myField = new JTextField("Default Text");
Then use a FocusListener, so that when the user put the focus in the element, the text disappears:
myField.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
myField.setText("");
}
public void focusLost(FocusEvent e) {
// nothing
}
});
But you have to be careful: if the user never put the focus in the text field, getText() will return the default string. Therefore, you'd better manage a boolean that tells if the text field has ever had the focus.
I believe what you want is input hint in the text field, something like the image below:
Check xswingx library which can do this.
Would textFieldInstance.setToolTip help:
textFieldInstance.setToolTip("Tool tip for text field");

Overriding the paint method in JTextField to draw text

I am wishing to draw a number onto a JTextField by overwriting the paint method. So that when the user edits the text field the number doesn't disappear. However, at the moment, the number isn't appearing at all, I have tried:
public void paintComponent(Graphics g) {
super.paintComponent(g);
if(number != 0){
g.setColor(Color.RED);
g.drawString(String.valueOf(number),0,0);
}
}
Any ideas, is this even possible?
Try to play with Y position in the g.drawString(String.valueOf(number),0,0); call. E.g. use getHeight()/2
..when the user edits the text field the number doesn't disappear.
As pointed out by #mKorbel, there is no need to override a JTextField in order to get red numbers, simply configure it using the public methods. OTOH..
g.drawString(String.valueOf(number),0,0);
If this is really all about numbers, perhaps the best approach is to use a JSpinner with a SpinnerNumberModel, and set a custom SpinnerUI.
Why don't you just add a small JLabel to the front of the JTextField? The JLabel could contain the number, and because it isn't editable it will always be there no matter what the user changes in the JTextField. You could also format the JLabel to make it red by calling setForeground(Color.RED);. This might be a much simpler solution?
For example, instead of doing this...
JPanel panel = new JPanel(new BorderLayout());
JTextField textfield = new JTextField("Hello");
panel.add(textfield,BorderLayout.CENTER);
You might do something like this...
JPanel panel = new JPanel(new BorderLayout());
JTextField textfield = new JTextField("Hello");
panel.add(textfield,BorderLayout.CENTER);
JLabel label = new JLabel("1.");
label.setForeground(Color.RED);
panel.add(label,BorderLayout.WEST);
Which adds a red JLabel to the left of the JTextField, and because you're using BorderLayout for the JPanel then it automatically makes the JLabel the smallest it can possibly be.
maybe there no reason override paintComponent() for JTextField, instead of use
JTextField.setBackground()
JTextField.setForeground()
JTextField.setFont()
JTextField.setHorizontalAlignment(javax.swing.SwingConstants.LEFT)
some hacks are possible by put there Html colored or special formatted text
EDIT
maybe this question is about
filtering KeyEvents in the Document / DocumentListener
or
JFormattedTextField with Number Formatter

Java swing: Multiline labels? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Multiline text in JLabel
I want to do this:
JLabel myLabel = new JLabel();
myLabel.setText("This is\na multi-line string");
Currently this results in a label that displays
This isa multi-line string
I want it to do this instead:
This is
a multi-line string
Any suggestions?
Thank you
EDIT: Implemented solution
In body of method:
myLabel.setText(convertToMultiline("This is\na multi-line string"));
Helper method:
public static String convertToMultiline(String orig)
{
return "<html>" + orig.replaceAll("\n", "<br>");
}
You can use HTML in JLabels. To use it, your text has to start with <html>.
Set your text to "<html>This is<br>a multi-line string" and it should work.
See Swing Tutorial: JLabel and Multiline label (HTML) for more information.
public class JMultilineLabel extends JTextArea{
private static final long serialVersionUID = 1L;
public JMultilineLabel(String text){
super(text); // According to Mr. Polywhirl, this might improve it -> text + System.lineSeparator()
setEditable(false);
setCursor(null);
setOpaque(false);
setFocusable(false);
setFont(UIManager.getFont("Label.font"));
setWrapStyleWord(true);
setLineWrap(true);
//According to Mariana this might improve it
setBorder(new EmptyBorder(5, 5, 5, 5));
setAlignmentY(JLabel.CENTER_ALIGNMENT);
}
}
It totally looks the same for me, but its ugly
Another easy way (but changes the text style a bit) is to use a <pre></pre> html block.
This will persist any formatting the user entered if the string you are using came from a user input box.
Example:
JLabel label = new JLabel("<html><pre>First Line\nSecond Line</pre></html>");
The direct procedure of writing a multi-line text in a jlabel is:
JLabel label = new JLabel("<html>First Line<br>Second Line</html>");
The problem with using html in JLabel or any Swing component is that you then have to style it as html, not with the usual setFont, setForeground, etc. If you're ok with that, fine.
Otherwise you can use something like MultilineLabel from JIDE, which extends JTextArea. It's part of their open source Commom Layer.
JLabel can accept html code. Maybe you can try to use the <br> tag.
Example:
JLabel myLabel = new JLabel();
myLabel.setText("<html> This is a <br> multi-line string </html>");
http://java.sun.com/docs/books/tutorial/uiswing/components/html.html

Categories

Resources