怎样才能在使用Swing时,将一个无返回值的方法打印到按钮上呢?

huangapple go评论58阅读模式
英文:

How can I print a void method inside a button using Swing?

问题

我是新手如果我使用术语不正确我感到抱歉我正在尝试学习Swing并将其导入到我的当前项目中在我的主文件中一个方法从MySQL数据库中打印一个列表我想要的是当按下按钮时将此输出打印到文本字段或对话框窗口在GUI上显示而不仅仅是命令行输出希望我能正确解释我的请求我使用Netbeans作为IDE

Baglanti.java中的方法

```java
public void dogList() {
    String sorg = "Select * From dogs";
    NewJFrame frame1 = new NewJFrame();

    try {
        statement = con.createStatement();
        ResultSet rs = statement.executeQuery(sorg);
        while (rs.next()) {
            int id = rs.getInt("id");
            String name = rs.getString("name");
            String species = rs.getString("species");
            int age = rs.getInt("age");
            String owner = rs.getString("owner");
            String date = rs.getString("date");

            System.out.println(" id : " + id + " name: " + name+ " species: " + species+ " age: " + age+ " owner: " + owner+ " date: " + date);
        }

    } catch (SQLException ex) {
        Logger.getLogger(Baglanti.class.getName()).log(Level.SEVERE, null, ex);
    }
}

NewJFrame.java中的列表按钮:

private void listbuttonActionPerformed(java.awt.event.ActionEvent evt) {
    Baglanti baglanti = new Baglanti();
    // 我不知道下一步怎么做
}

谢谢。


<details>
<summary>英文:</summary>

i am pretty new i am sorry if i use terms incorrect. I am trying to learn Swing and import it to my current project. In my main file, a method prints a list from mysql database. I want this : when button pressed, print this output to textfield or dialog window, show on the gui, not only cmd output. I hope I could explain my request correctly. I use Netbeans as IDE.

method in Baglanti.java : 

    public void dogList() {
        String sorg = &quot;Select * From dogs&quot;;
         NewJFrame frame1 = new NewJFrame();
         
        
        try {
            statement = con.createStatement();
            ResultSet rs = statement.executeQuery(sorg);
            while (rs.next()) {
                int id = rs.getInt(&quot;id&quot;);
                String name = rs.getString(&quot;name&quot;);
                String species = rs.getString(&quot;species&quot;);
                int age = rs.getInt(&quot;age&quot;);
                String owner = rs.getString(&quot;owner&quot;);
                String date = rs.getString(&quot;date&quot;);

                System.out.println(&quot; id : &quot; + id + &quot; name: &quot; + name+ &quot; species: &quot; + species+ &quot; age: &quot; + age+ &quot; owner: &quot; + owner+ &quot; date: &quot; + date);
            }
            
        } catch (SQLException ex) {
            Logger.getLogger(Baglanti.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    }

    

and my list button in NewJFrame.java

    private void listbuttonActionPerformed(java.awt.event.ActionEvent evt) {                                           
        Baglanti baglanti = new Baglanti();       
        // i don&#39;t know what next

Thanks.      

</details>


# 答案1
**得分**: 0

首先,让我们修复你的`doglist()`方法。我给它传递了一个`PrintStream`参数,这样它就可以与`System.out`一起使用,也可以与其他任何`PrintStream`一起使用。我还将“NewJFrame”创建部分移除。这部分不应该放在这里。

```java
public void dogList(PrintStream stream) {
    String sorg = "Select * From dogs";

    try {
        statement = con.createStatement();
        ResultSet rs = statement.executeQuery(sorg);
        while (rs.next()) {
            int id = rs.getInt("id");
            String name = rs.getString("name");
            String species = rs.getString("species");
            int age = rs.getInt("age");
            String owner = rs.getString("owner");
            String date = rs.getString("date");

            stream.println(" id : " + id + " name: " + name+ " species: " + species+ " age: " + age+ " owner: " + owner+ " date: " + date);
        }
        
    } catch (SQLException ex) {
        Logger.getLogger(Baglanti.class.getName()).log(Level.SEVERE, null, ex);
    }
}

现在,你只需要一个用于JTextFieldDialogPrintStream。获取这个的最简单方法是使用ByteArrayOutputStream,然后将其转换为String,并将其设置在JComponent中。

ByteArrayOutputStream bstream = new ByteArrayOutputStream();
PrintStream myPS = new PrintStream(bstream);
dogList(myPS);
String msg = new String(bstream.getBytes());

现在,你可以使用JTextField.setText(msg),或在你的JFrame/Dialog中执行类似的操作。

英文:

So first, let's fix your doglist() method. I have Given it a PrintStream parameter so that it can be used with System.out but also with any other PrintStream. I have also taken out the "NewJFrame" creation. This shouldn't go there.

public void dogList(PrintStream stream) {
    String sorg = &quot;Select * From dogs&quot;;
     //Take this out
     //NewJFrame frame1 = new NewJFrame();
     
    
    try {
        statement = con.createStatement();
        ResultSet rs = statement.executeQuery(sorg);
        while (rs.next()) {
            int id = rs.getInt(&quot;id&quot;);
            String name = rs.getString(&quot;name&quot;);
            String species = rs.getString(&quot;species&quot;);
            int age = rs.getInt(&quot;age&quot;);
            String owner = rs.getString(&quot;owner&quot;);
            String date = rs.getString(&quot;date&quot;);

            stream.println(&quot; id : &quot; + id + &quot; name: &quot; + name+ &quot; species: &quot; + species+ &quot; age: &quot; + age+ &quot; owner: &quot; + owner+ &quot; date: &quot; + date);
        }
        
    } catch (SQLException ex) {
        Logger.getLogger(Baglanti.class.getName()).log(Level.SEVERE, null, ex);
    }

}

}

Now, all you need is a PrintStream for a JTextField or a Dialog. And the easiest way to get this is to use a ByteArrayOutputStream and then convert that to a String and set it in the JComponent

ByteArrayOutputStream bstream = new ByteArrayOutputStream();
PrintStream myPS = new PrintStream(bstream);
dogList(myPS);
String msg = new String(bstream.getBytes());

Now you can use JTextField.setText(msg), or do something similar within your JFrame/Dialog.

答案2

得分: 0

似乎在 Baglanti 类的 dogList 方法中,您不需要再创建 NewJFrame 的另一个实例。

此外,每次按下按钮时在 NewJFrame 中创建 Baglanti 类的实例可能是多余的。只需创建一个该类的单一实例来负责从数据库中检索数据即可。

接下来,您需要重构 dogList 方法的代码,使其开始返回与调用者相关的数据类(例如 Dog)。然后您将能够在窗体中使用此列表,并根据需要显示其数据:可以是在文本区域、表格、列表等中。

话虽如此,以下是一些代码片段:

// 数据传输类 Dog
public class Dog {
    private int id;
    private String name;
    private String species;
    private int age;
    private String owner;
    private String date;

    // 带所有参数的构造函数,以及 getter 和 setter 方法
}
import java.util.*;

public class Baglanti {
// ...
    public List<Dog> dogList() {
        String sorg = "Select * From dogs";

        List<Dog> result = new ArrayList<>();

        try (statement = con.createStatement()) { // 使用 try-with-resources 确保语句关闭
            ResultSet rs = statement.executeQuery(sorg);
            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String species = rs.getString("species");
                int age = rs.getInt("age");
                String owner = rs.getString("owner");
                String date = rs.getString("date");

                System.out.println(" id : " + id + " name: " + name+ " species: " + species+ " age: " + age+ " owner: " + owner+ " date: " + date);

                // 假设 Dog 中已实现带所有参数的构造函数
                Dog dog = new Dog(id, name, species, age, owner, date);

                result.add(dog);
            }
        } catch (SQLException ex) {
            Logger.getLogger(Baglanti.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }
// ... 其他方法
}

NewJFrame 中的剩余部分:

public class NewJFrame extends JFrame {

    Baglanti baglanti = new Baglanti();

//... 其他 UI 组件

    private void listbuttonActionPerformed(java.awt.event.ActionEvent evt) {
        List<Dog> dogs = baglanti.dogList();

        for (Dog dog : dogs) {
            // 在其他 UI 组件中设置有关狗的信息
            textArea.append(String.format("Dog id=%d named: %s, age %d years, owner: %s",
                dog.getId(), dog.getName(), dog.getAge(), dog.getOwner()));
        }
    }
}
英文:

It seems you do not need to create another instance of NewJFrame in dogList method of Baglanti class.

Also, it may be redundant to create an instance of Baglanti class in NewJFrame each time when you press on the button. It would suffice to have a single instance of this class responsible for retrieval of the data from the DB.

Next, you need to refactor the code of dogList method so that it begins to return a list of relevant data classes (e.g. Dog) to the caller. Then you'll be able to use this list in the frame and show its data as needed: in a text area, table, list, etc.

That being said, some code snippets:

// data transfer class Dog
public class Dog {
    private int id;
    private String name;
    private String species;
    private int age;
    private String owner;
    private String date;

    // constructor with all args, getters/setters
}
import java.util.*;

public class Baglanti {
// ...
    public List&lt;Dog&gt; dogList() {
        String sorg = &quot;Select * From dogs&quot;;

        List&lt;Dog&gt; result = new ArrayList&lt;&gt;();

        try (statement = con.createStatement()) { // use try-with-resources to make sure the statement is closed
            ResultSet rs = statement.executeQuery(sorg);
            while (rs.next()) {
                int id = rs.getInt(&quot;id&quot;);
                String name = rs.getString(&quot;name&quot;);
                String species = rs.getString(&quot;species&quot;);
                int age = rs.getInt(&quot;age&quot;);
                String owner = rs.getString(&quot;owner&quot;);
                String date = rs.getString(&quot;date&quot;);

                System.out.println(&quot; id : &quot; + id + &quot; name: &quot; + name+ &quot; species: &quot; + species+ &quot; age: &quot; + age+ &quot; owner: &quot; + owner+ &quot; date: &quot; + date);

                // assuming all-args constructor is implemented in Dog
                Dog dog = new Dog(id, name, species, age, owner, date);

                result.add(dog);
            }
        } catch (SQLException ex) {
            Logger.getLogger(Baglanti.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }
// ... other methods
}

Remaining part in NewJFrame:

public class NewJFrame extends JFrame {

    Baglanti baglanti = new Baglanti();

//... other UI components

    private void listbuttonActionPerformed(java.awt.event.ActionEvent evt) {
        List&lt;Dog&gt; dogs = baglanti.dogList();

        for (Dog dog : dogs) {
            // set information about the dog in other UI components
            textArea.append(String.format(&quot;Dog id=%d named: %s, age %d years, owner: %s&quot;,
                dog.getId(), dog.getName(), dog.getAge(), dog.getOwner()));
        }
    }
}

huangapple
  • 本文由 发表于 2020年10月8日 23:12:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/64265545.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定