【问题标题】:Jtable showing wrong (old) results from DBJtable 显示来自 DB 的错误(旧)结果
【发布时间】:2018-04-16 18:05:31
【问题描述】:

我正在编写一个代码,它将一个单词(棋盘游戏的名称)或一个字母作为输入并在我的数据库中搜索它。

如果有任何条目,我会在表格中显示它们,否则我不想显示空表,我想显示一个标签“未找到结果”,该标签会在 1500 毫秒后消失。

if 语句正常工作。例如,如果我写 't',我会在一个表格中找到所有以 't' 开头的游戏。

else 语句有时会出现问题:

  1. 如果我运行我的程序并且我首先写入输入“b”(在我的数据库中没有以“b”开头的条目)--> 它显示标签“未找到结果”,然后它消失了(它有效!)
  2. 如果我运行我的程序并写为输入“t”(如前所述),然后我写“a”(我有带有“a”的条目,它可以工作)[.....] 然后最后我写为输入'b'(在我的数据库中没有以'b'开头的条目)这是问题所在:它显示标签“未找到结果”但它也显示了带有我第一个输入结果的表(即以“t”开头的游戏)。

我做错了什么?谢谢!

点击“搜索”按钮后的代码如下:

btnCerca.addActionListener(new ActionListener() 
    {
        public void actionPerformed(ActionEvent e) 
        {
            /*Connect to DB:*/
            Database db = new Database();
            Connection connection = null;
            try 
            {
                connection = db.connectToDB();
            } 
            catch (SQLException ex)
            {
                ex.printStackTrace();
            }

            /*Create a query which search in the DB the word/letter entered by the user*/
            Query query = new Query (connection);
            query.search(textField.getText());  //execute the query 

            /*Get results:*/
            ResultSet rs = query.getResults();

            /* check if rs is empty */          
            boolean res = false;
            try 
            {
                res = rs.isBeforeFirst();
            } 
            catch (SQLException e1) 
            {
                e1.printStackTrace();
            }

            ListTableModel model = null;
            JScrollPane scrollPane = new JScrollPane();             

            if (res) //there is something in rs
            {   
                try 
                {
                    model = ListTableModel.createModelFromResultSet(rs);
                } 
                catch (SQLException e1) 
                {
                    e1.getMessage();
                }

                /*The table which will show the results*/
                JTable table_1 = new JTable(model);
                scrollPane.setBounds(10, 75, 1200, 300);
                panelRicerca.add(scrollPane);
                scrollPane.setViewportView(table_1);

            }
            else //rs is empty
            {
                JLabel lblNoGiochi = new JLabel("No results found.");
                lblNoGiochi.setBounds(448, 30, 400, 14);
                panelRicerca.add(lblNoGiochi);
                panelRicerca.repaint();

                /*...I want the label disappear after 1500ms:*/
                int delay = 1500; 
                ActionListener taskPerformer = new ActionListener() 
                {
                    public void actionPerformed(ActionEvent evt) 
                    {
                        panelRicerca.remove(lblNoGiochi);
                        panelRicerca.repaint();
                    }
                };
                new Timer(delay, taskPerformer).start();                
            }
        }
    });

------------编辑--------------- ---------

我做了一个更简单的例子,它受到相同问题的影响,因此您可以更快地编译和检查。

如果我写“你好”,我想显示一个表格。 如果我写其他东西,我希望表格显示一个标签。

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JLabel;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class Test {

    private JFrame frame;
    private JTextField textField;
    private JTable table;
    private JLabel lbl;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Test window = new Test();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public Test() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {

        lbl = new JLabel("Hey");
        lbl.setBounds(378, 236, 46, 14);

        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        textField = new JTextField();
        textField.setBounds(102, 48, 86, 20);
        frame.getContentPane().add(textField);
        textField.setColumns(10);

        JButton btnOk = new JButton("ok");
        btnOk.addMouseListener(new MouseAdapter() 
        {
            @Override
            public void mouseClicked(MouseEvent arg0) 
            {
                JScrollPane scrollPane = new JScrollPane();
                scrollPane.setBounds(20, 20, 50, 50);


                table = new JTable();

                if (textField.getText().equals("hello"))
                {
                    System.out.println("I'm in the if statement");

                    //show the table:
                    frame.getContentPane().add(scrollPane);
                    scrollPane.setViewportView(table);

                }
                else
                {
                    System.out.println("I'm in the else statement");

                    //don't show the table:
                    scrollPane.remove(table);
                    /* Already tried to use: 
                     - revalidate and repaint the scrollPane
                     - revalidate and repaint the contentPane
                     - remove the entire scrollPane from the ContentPane
                     - remove the table from the scrollPane, then remove the scrollPane from the ContentPane
                    */

                    //and show a label instead:
                    frame.getContentPane().add(lbl);
                    frame.getContentPane().repaint();
                }
            }
        });
        btnOk.setBounds(211, 47, 89, 23);
        frame.getContentPane().add(btnOk);
    }
}

【问题讨论】:

  • 如果您在添加表格时跟踪,我相信您需要在 else 条件下删除表格。
  • 谢谢!我在添加标签之前尝试了 panelRicerca.remove(table_1) ,但结果是一样的。还有其他想法吗?
  • 或许可以试试 scrollPane.remove(table_1)
  • 没办法:/我从scrollPane中删除了表格,从面板中删除了表格,从面板中删除了scrollPane以及两者之间的组合。我还写了一个更简单的例子,只是为了排除数据库的问题,但没有任何改变。一旦我展示了表格,我就无法删除它。
  • 我认为你应该看到这个stackoverflow.com/questions/6232355/…

标签: java swing


【解决方案1】:

您将表格添加到面板中:

panelRicerca.add(scrollPane);

稍后您将标签添加到面板:

panelRicerca.add(lblNoGiochi);

您无法从面板中移除表格窗格,因此它将始终显示。

您需要:

  1. 在添加标签之前删除表格窗格
  2. 使用CardLayoutCardLayout 允许您在同一面板中交换组件,因此只有一个可见。阅读How to Use CardLayout 上的 Swing 教程了解更多信息。

编辑:

在我原来的回答中,我建议您需要从面板中删除表格。实际上我的意思是“滚动窗格”,因为您从未将表格添加到面板中。请注意,我发布的代码显示将“滚动窗格”添加到面板。你本来打算做相反的事情。

在您的原始代码中,您在同一面板中添加和删除了标签。我的建议是在同一面板中添加/删除滚动窗格。

同样的概念,您可以从滚动窗格中删除表格。但是再次将表格添加到滚动窗格的“视口”中。因此,如果您想删除它,请执行相反的操作。您可以使用setViewportView(null) 将其从滚动窗格的视口中移除。这不会从面板中删除滚动窗格(这仍然是最简单的解决方案),但表格不会显示在滚动窗格中。

但是,上述建议都不适用于您的演示代码,因为您不断在 MouseListener 中创建一个新的 JScrollPane,因此您没有对添加到框架的滚动窗格的引用。所以滚动窗格变量需要是一个实例变量,并且您在构造函数中创建滚动窗格。

另外,不要使用空布局。 Swing 旨在与布局管理器一起使用。所以做动态布局变化的基本代码是:

panel.remove(...);
panel.add(...);
panel.revalidate(); // to invoke layout manager
panel.repaint(); // repaint changes.

所以我试图给出的基本答案是,如果您想“删除”某些东西,您需要执行与将组件添加到框架中所做的相反的操作。

【讨论】:

  • 谢谢!我试图添加: panelRicerca.remove(table_1);正如你所建议的,但结果是一样的。表格(和 scrollPane)仍然存在:/
  • @Monia,更好的示例代码。那是更合适的minimal reproducible example。看看我的编辑。
  • 谢谢,它有效!也感谢您的其他建议!
猜你喜欢
  • 2014-09-04
  • 2020-07-09
  • 2014-12-15
  • 2019-04-15
  • 1970-01-01
  • 2015-10-28
  • 2021-05-25
  • 1970-01-01
  • 2019-08-01
相关资源
最近更新 更多