How to set background image to JTextArea in JPanel

I want to set a custom background image to JTextArea

. I looked on google but no result, the background could be the logo, also I want to know how to set the background resolution.

I only have one class per package. I have a MySQL connector driver as a reference library, my desktop is Eclipse exporting a jar of Fat-jar plugin

Code:

public class  panel extends JPanel implements ActionListener {
    protected JTextField textField, textField2;
    protected static JTextArea textArea;
    private final static String newline = "\n";

    public panel() {
        super(new GridBagLayout());
        textField = new JTextField(30);
        textField.addActionListener(this);
        textField.setBackground(Color.LIGHT_GRAY);

        textField2 = new JTextField(30);
        textField2.addActionListener(this);
        textField2.setEnabled(false);



        textArea = new JTextArea(30, 100);
        textArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(textArea);

        //Add Components to this panel.
        GridBagConstraints c = new GridBagConstraints();
        c.gridwidth = GridBagConstraints.REMAINDER;

        c.fill = GridBagConstraints.HORIZONTAL;
        add(textField, c);
        add(textField2, c);

        c.fill = GridBagConstraints.BOTH;
        c.weightx = 1.0;
        c.weighty = 1.0;
        add(scrollPane, c);
    }

    public void actionPerformed(ActionEvent evt) {
        String select = textField.getText();
        if(textField.getText().equalsIgnoreCase("connect")){
            textArea.setForeground(Color.BLACK);
            connect();
            textField.setText("");
        }else if(textField.getText().equalsIgnoreCase("select test")){
            textArea.setForeground(Color.BLACK);
            viewTest();
            textField.setText("");;
        }else if(textField.getText().equalsIgnoreCase("clear")){
            textArea.setForeground(Color.BLACK);
            textField.setText("");
            clear();
        }else if(textField.getText().equalsIgnoreCase("commands")){
            textArea.setForeground(Color.BLACK);
            commandsmenu();
            textField.setText("");
        }else if(textField.getText().equalsIgnoreCase("insertinto test")){
            textField2.setEnabled(true);
            if(textField2.getText().equals("")){

            textArea.append("Please add the VALUES of the table on the second textfield! Syntax: 'Agevaulue', namevalue, adressvalue !" + newline);
            }else{

                textArea.setForeground(Color.BLACK);
                InsertIntoTest();
                textField2.setText("");
                textField2.setEnabled(false);
            }

        }



        else {
            clear();
            textArea.setForeground(Color.RED);
            textArea.append("Uknown Command -- use: commands --  to see all commands!");
            textField.selectAll();
        }

        //Make sure the new text is visible, even if there
        //was a selection in the text area.
        textArea.setCaretPosition(textArea.getDocument().getLength());
    }

    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event dispatch thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("Java + MySQL Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Add contents to the window.
        frame.add(new panel());

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }
    public void connect(){
        Connection conn = null;
        try
        {
          String url = "jdbc:mysql://localhost/users";

          Class.forName("com.mysql.jdbc.Driver");
          textArea.append("Database connection established");
          conn = DriverManager.getConnection(url, "root", "kristian76");

        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
    public void viewTest()
          {
            Connection conn = null;
            try{
            String url = "jdbc:mysql://localhost/users";

            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, "root", "kristian76");

            String query = "SELECT * FROM test";
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(query);
            while (rs.next()){
                int age = rs.getInt("age");
                String name = rs.getString("name");
                String adress = rs.getString("adress");
                textArea.append("AGE: " + age + " |Name: " + name + " |Adress: " + adress + newline);
            }
          }catch(Exception e){
              textArea.setForeground(Color.RED);
              textArea.append("Got an Exception!" + newline);
              textArea.append(e.getMessage());
          }
            }public void InsertIntoTest() {
                Connection conn = null;
                try{
                    String url = "jdbc:mysql://localhost/users";
                    Class.forName("com.mysql.jdbc.Driver");
                    conn = DriverManager.getConnection(url, "root", "kristian76");

                    String query = "INSERT INTO test(age, name, adress)VALUES(" + textField2.getText() + ")";
                    Statement stmt = conn.createStatement();
                    stmt.executeUpdate("INSERT INTO test(age, name, adress)VALUES(" + textField2.getText() + ")");
                    textArea.append("Data Imported!" + newline);
                }catch(Exception e){
                    textArea.setForeground(Color.RED);
                    textArea.append("Got an Exception" + newline);
                    textArea.append(e.getMessage());

                }
            }
    public void clear(){
        textArea.setText("");
    }
    public void commandsmenu() {
        textArea.append("select <table> -  read a <table>" + newline);
        textArea.append("clear - clear output" + newline);
        textArea.append("commands - see Commands" + newline);
        textArea.append("insertinto <table> - insert data into <table>" + newline);

    }

    public static void main(String[] args) {
        //Schedule a job for the event dispatch thread:
        //creating and showing this application GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

      

+3


source to share


3 answers


It's very simple, you just need to create your own TextArea class that extends from the JTextArea and then override the paintComponent method to include a background image, here is the class:

public class MyTextArea extends JTextArea {

    private Image img;

    public MyTextArea(int a, int b) {
        super(a,b);
        try{
            img = ImageIO.read(new File("background.jpg"));
        } catch(IOException e) {
            System.out.println(e.toString());
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        g.drawImage(img,0,0,null);
        super.paintComponent(g);
    }
}

      

Then in the panel you can use JTextArea type in your code:

protected static JTextArea textArea;

      

But on initialization, call the constructor of your newly created class:



textArea = new MyTextArea(30, 100);

      

This way, the text won't let you see the image in the background, so we need to make it transparent:

textArea.setBackground(new Color(1,1,1, (float) 0.01));

      

I haven't seen your code in detail, but it is good programming practice to have a CamelCase class name, but since Panel is a Java keyword (panel is an AWT component), then you can call it something like MyPanel or SQLPanel.

+3


source


The first thought that might come up is drawing the image in the paintComponent

textarea method , while this may seem to work, once you start typing you will find that being the background image is actually a foreground image and is drawing text.

So you can draw the image first and then call super.paintComponent

after it, but the background color is actually drawn as part of the call paintComponent

...

What you need to do is trick the component to not paint the background color. The simplest solution would be to make the component transparent, for example ...



public class CustomTextArea extends JTextArea {

    private BufferedImage image;

    public CustomTextArea() {
        super(20, 20);
        setOpaque(false);
        try {
            image = ImageIO.read(new File("..."));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D) g.create();
        g2d.setColor(getBackground());
        g2d.fillRect(0, 0, getWidth(), getHeight());
        if (image != null) {
            int x = getWidth() - image.getWidth();
            int y = getHeight() - image.getHeight();
            g2d.drawImage(image, x, y, this);    
        }
        super.paintComponent(g2d);
        g2d.dispose();
    }

}

      

This is based on this Insert Image below JTextArea answer

Another option would be to render the image in a scrollPane, this will give you options for how you want to control the scrolling of the image (with a component or sticky), for example see Add background image to JTable

+2


source


It is not difficult if you are using HTML. Your code might look like:

textPane = new JTextPane(30, 100);
textPane.setEditable(false);

// load image
ByteArrayOutputStream out = new ByteArrayOutputStream();
FileInputStream in = new FileInputStream("/path/to/your/image.png");
byte[] buf = new byte[4096]; int read;
while ((read = in.read(buf)) != -1)
   out.write(buf, 0, read);
in.close();

// set image
textPane.setContentType("text/html");
textPane.setText("<html><head><style type=\"text/css\"> body {"
    + "background-image: url(data:image/png;base64,"
    + Base64.getEncoder().encodeToString(out.toByteArray())
    + "); } </style></head><body>ENTER YOUR TEXT HERE</body></html>");

      

+1


source







All Articles