Home > OS >  How to display HTML content and password field in a single frame?
How to display HTML content and password field in a single frame?

Time:02-25

I am having a HTML page displayed in a JEditorPane inside a JScrollPane. I need to make a JPasswordField in the same window to take the user's password.

How can I implement that?

CodePudding user response:

How can I implement that?

Many different ways. Here's one.

import java.awt.Dimension;
import java.awt.EventQueue;
import java.io.IOException;

import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;

public class PswdHtml implements Runnable {

    @Override
    public void run() {
        createAndShowGui();
    }

    private void createAndShowGui() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(createPane());
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private JScrollPane createPane() {
        try {
            JEditorPane editPane = new JEditorPane("https://www.google.com");
            JScrollPane scrollPane = new JScrollPane(editPane);
            scrollPane.setColumnHeaderView(createPassword());
            scrollPane.setPreferredSize(new Dimension(450, 300));
            return scrollPane;
        }
        catch (IOException x) {
            throw new RuntimeException(x);
        }
    }

    private JPanel createPassword() {
        JPanel panel = new JPanel();
        JLabel label = new JLabel("Password");
        panel.add(label);
        JPasswordField passwordField = new JPasswordField(10);
        panel.add(passwordField);
        return panel;
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new PswdHtml());
    }
}

Refer to Creating a GUI With Swing which is one of the trails in Oracle's Java tutorials.

  • Related