簡體   English   中英

如何將背景圖像設置為JPanel中的JTextArea

[英]How to set Background image to a JTextArea in a JPanel

我想在JTextArea上設置自定義背景圖像。 我曾經看過谷歌,但沒有結果,背景可能是一個標志,我也想知道如何設置背景的分辨率。

我在一個包中只有一個班級。 我有一個MySQL連接器驅動程序作為Referenced Library,我的工作台是Eclipse,使用Fat-jar插件導出jar

碼:

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's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

這很簡單,你只需要創建自己的TextArea類,它從JTextArea擴展,然后覆蓋paintComponent方法以包含你的背景圖像,這里是類:

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);
    }
}

然后在面板中,您仍然可以在代碼中使用JTextArea類型:

protected static JTextArea textArea;

但是在初始化時調用最近創建的類的構造函數:

textArea = new MyTextArea(30, 100);

像這樣,文本不會讓你在后台看到圖像,所以我們需要讓它透明:

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

我沒有詳細看到你的代碼,但一個很好的編程實踐是CamelCase類的名稱,但由於“Panel”是一個Java關鍵字(Panel是一個AWT組件),那么你可以將它命名為MyPanel或SQLPanel 。

你可能想到的第一個想法是在文本區域的paintComponent方法中繪制圖像,雖然這似乎有效,但是一旦你開始嘗試輸入文本,你會發現,假設是背景圖像,實際上是一個前景圖像並在文本上繪畫。

好吧,那么,您可以先繪制圖像,然后調用它super.paintComponent ,但背景顏色實際上是繪制為paintComponent調用的一部分...

你需要做的是欺騙組件不要繪制背景顏色。 最簡單的解決方案是使組件透明,例如......

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();
    }

}

這基於此在JTextArea答案下插入圖像

另一種選擇是在scrollPane中渲染圖像,這為您提供了如何控制圖像滾動(使用組件或粘性)的選項,例如,請參閱在JTable中添加背景圖像

如果您使用HTML,這並不是很難。 您的代碼可能如下所示:

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>");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM