ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

如何将背景图像设置为JPanel中的JTextArea

2019-08-25 00:00:37  阅读:251  来源: 互联网

标签:jtextarea java swing background-image


我想在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 .

标签:jtextarea,java,swing,background-image
来源: https://codeday.me/bug/20190824/1713250.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有