Michael Quinn Michael Quinn - 6 months ago 21
SQL Question

TextArea with News Posts - SQL Inserting (Starting New Lines)

I've currently got a program going that grabs a news post from the SQL database then loads them into a textArea where the user can view them. But at the moment my program has major limitations in that it can only display one post due to me not being able to grab multiple posts.

JScrollPane scrollPane_2 = new JScrollPane();
scrollPane_2.setViewportBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
scrollPane_2.setBounds(769, 125, 294, 430);
frame.getContentPane().add(scrollPane_2);

JTextArea textArea = new JTextArea();
scrollPane_2.setViewportView(textArea);
textArea.setFont(new Font("Lantinghei TC", Font.PLAIN, 13));
textArea.setEditable(false);
textArea.setBackground(Color.LIGHT_GRAY);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);

frame.getContentPane().add(lblChangelogAndNews);
try {
Connection conn = DriverManager.getConnection( Host, Name, Pass );
PreparedStatement pst = conn.prepareStatement("SELECT * From `news_1`");
ResultSet rs = pst.executeQuery();
while(rs.next()) {
String content =rs.getString("content");
textArea.setText(content);
}
}
catch (Exception e) {
}


What I'm having trouble with is how I would get around grabbing multiple news items then displaying them in a layout like this


Title

Content


(With a space in-between each post)


Title

Content


The methods I've tried at the moment all cause problems so I have just listed a simple working one from earlier which displays the basics of what I want.

If you want further infomation into what I'm trying to get it to do please comment so that I can answer with additional infomation.

Thanks Quinn (Beware I'm currently new to coding hence the bad layout)

Answer

This is not exactly a mysql problem but rather a java swing problem. If you look at your while loop you can see that it's over writing the same text area over and over again.

        while(rs.next()) {
            String content =rs.getString("content");
            textArea.setText(content);
        }

What you need is a JTable with a database linked model. Here is an excellent previous Q/A here which explains how this is done:

Most simple code to populate JTable from ResultSet

(normally I would vote to close as duplicate but I felt an explanation was required here)