jcarlos
jcarlos

Reputation: 135

Is there any way to display text without JLabel or JTextField in java swing?

I'm creating Swing project, but I'm wondering if there's any way to print text without using JLabel or JTextField.

I found out text field could be the one but it isn't as tidy as JLabel. (there's a border around the text).

Can a border in the text field be removed? Or are there other methods I can use?

Upvotes: 0

Views: 2680

Answers (3)

Paul Samsotha
Paul Samsotha

Reputation: 209072

"I'm wondering if there's any way to print text without using JLable or JtextField"

You could always draw the text in a JPanel. Takes a lot more work, but you can do a lot more with your text.

public class TextPanel extends JPanel{
    protected void paintComponent(Graphics g){
        super.paintComponent(g);
        g.drawString("Hello, Stackoverflow!", xLocation, yLocation);
    }
}

See Drawing Text with Graphics

Upvotes: 1

Andrew Thompson
Andrew Thompson

Reputation: 168835

You seem to be looking for JComponent.setBorder(null). However there are a number of ways to achieve the effect you seem to want..

  1. Opaque JLabel with a BG color.
  2. A custom painted component..

Here is an example of the two standard components.

enter image description here

import java.awt.*;
import javax.swing.*;

class TextFieldNoBorder {

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                String s = "Text without borders..";
                JPanel gui = new JPanel(new GridLayout(0,1,5,5));

                JTextField tf = new JTextField(s, 20);
                tf.setBorder(null);

                gui.add(tf);

                JLabel l = new JLabel(s);
                l.setOpaque(true);
                l.setBackground(Color.YELLOW);
                gui.add(l);

                JOptionPane.showMessageDialog(null, gui);
            }
        };
        // Swing GUIs should be created and updated on the EDT
        // http://docs.oracle.com/javase/tutorial/uiswing/concurrency
        SwingUtilities.invokeLater(r);
    }
}

Upvotes: 1

Keerthivasan
Keerthivasan

Reputation: 12890

You can use this!

JTextField textField = new JTextField();
textField.setBorder(javax.swing.BorderFactory.createEmptyBorder());

This will set the empty border to your TextField

Upvotes: 0

Related Questions