Java Combo Box Not Filling from SQL - java

In my Program I have a ComboBox in which the user can select the User he wishes to edit and currently the Class I use to fill the ComboBox is not doing it. I've look at some similar problems to this on the website but failed to see what I'm doing wrong. If someone can provide a fix to the problem it would be appreciated. I'm still quite new to most of this.
import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class AdminPanelDelUser {
private String Host = "Hidden";
private String Name = "Hidden";
private String Pass = "Hidden";
private JComboBox<String> userPicker;
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AdminPanelDelUser window = new AdminPanelDelUser();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public AdminPanelDelUser() {
initialize();
getUserPicker();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 300, 352);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JComboBox<String> userPicker = new JComboBox<String>();
userPicker.setBounds(59, 6, 235, 27);
frame.getContentPane().add(userPicker);
}
public JComboBox<String> getUserPicker() {
try {
Connection conn = DriverManager.getConnection( Host, Name, Pass );
PreparedStatement pst = conn.prepareStatement("SELECT * From `table_1`");
ResultSet rs = pst.executeQuery();
while(rs.next()) {
String name =rs.getString("user_name");
userPicker.addItem(name);
}
}
catch (Exception e) {
//Place Pop Warning Later
}
return userPicker;
}
}
Also any suggestions on how I can further improve the code would be happily taken. Thanks for anyone who helps me solve this problem.

Your problem is that you are creating the userPicker JComboBox and assigning it to a variable with method level scope instead of using the variable with class level scope. The JComboBox you add to the content pane is different to the one you attempt to add items to (which incidentally is null when getUserPicker() is called).
JComboBox<String> userPicker = new JComboBox<String>();
should be
userPicker = new JComboBox<String>();
You might want to read http://www.java-made-easy.com/variable-scope.html to get a better understanding of what is going on.

Change done in initialize function. The values are not setting because you are creating a new object userPicker. The following code is working
package com.mylender.test;
import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class AdminPanelDelUser {
private JComboBox<String> userPicker;
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AdminPanelDelUser window = new AdminPanelDelUser();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public AdminPanelDelUser() {
initialize();
getUserPicker();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 300, 352);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
//JComboBox<String> userPicker = new JComboBox<String>();
userPicker = new JComboBox<String>();
userPicker.setBounds(59, 6, 235, 27);
frame.getContentPane().add(userPicker);
}
public void getUserPicker() {
try {
String a[]= {"HELLO","WORLD"};
for(String s:a)
userPicker.addItem(s);
}
catch (Exception e) {
//Place Pop Warning Later
}
}
}

Related

Refresh JTextArea in method

I have the following problem:
in my JTextArea I inserted a default string, which must be updated with the new wording once the file is uploaded.
I have the problem that a live refresh of JTextArea is not done, but if I log out and log in I will see the changed string.
public void createWindow()
{
// some code...
JTextArea textArea = new JTextArea(1,1);
String all = "Nothing Infractions";
try {
all = new Scanner (file).useDelimiter("\\A").next();
textArea =new JTextArea(100,1);
} catch (FileNotFoundException e1) {
textArea =new JTextArea(1,1);
}
JScrollPane scroll = new
JScrollPane(textArea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
textArea.setText(all);
frmUser.getContentPane().add(textArea);
Update:
the text area was thought to have been written without infraction, then passed the program going on randomly and assigning it to each user, the problem and that when assigning them all the logged in user does not automatically update that part of text where no infraction was written.
I Use Java 8
Use revalidate() and repaint().
Here is an MCVE (Minimal, Complete and Verifiable example, see https://stackoverflow.com/help/mcve) from which you cut and paste as needed for your question. The example below is not fundamentally different from your question, but it allows other users on StackOverflow to replicate the problem and pass along suggestions or solutions.
In addition to modifying the question, please indicate which version of Java you are running.
Based on what you have said, you will probably need to implement some type of listener to determine when the contents of the file change -- or does it get created and never changed?
190418 1646Z: Added a refresh button per your last comment. Let me know if you would prefer the window to update without having to click a button.
package javaapplication7;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class FileWatcher extends JFrame {
static final File WATCH_FILE = new File("c:\\temp\\java7.txt");
static final String DELIMITER = "\n";
private JPanel panel = new JPanel();
private JTextArea textArea = new JTextArea(20, 20);
public FileWatcher() {
JFrame frame = new JFrame();
frame.setSize(600, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setTitle("File Watcher");
frame.add(createPanel());
frame.pack();
}
private JPanel createPanel() {
// some code...
JPanel tempPanel = getPanel();
GridBagConstraints gbc = new GridBagConstraints();
tempPanel.setLayout(new GridBagLayout());
JButton button = new JButton("Refresh");
button.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
getUpdatedText();
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
});
gbc.anchor = GridBagConstraints.NORTH;
getPanel().add(button, gbc);
getTextArea().setFont(new Font("Verdana", Font.BOLD, 16));
getTextArea().setBorder(BorderFactory.createEtchedBorder());
getTextArea().setLineWrap(true);
getTextArea().setWrapStyleWord(true);
getTextArea().setOpaque(true);
getTextArea().setVisible(true);
getUpdatedText();
JScrollPane scroll = new JScrollPane(getTextArea(), JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scroll.setBorder(BorderFactory.createLineBorder(Color.blue));
scroll.setVisible(true);
// frmUser.getContentPane().add(textArea);
gbc.gridy = 1;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
tempPanel.add(scroll, gbc);
return tempPanel;
}
public void getUpdatedText() {
String all = new String();
try (Scanner scanner = new Scanner(WATCH_FILE).useDelimiter(DELIMITER)) {
while (scanner.hasNext()) {
all = all.concat(scanner.next()).concat(DELIMITER);
}
} catch (FileNotFoundException ex) {
// swallow, next line covers it
}
if (all.isEmpty()) {
all = "No Infractions";
}
getTextArea().setText(all);
}
public JPanel getPanel() {
return panel;
}
public void setPanel(JPanel panel) {
this.panel = panel;
}
public JTextArea getTextArea() {
return textArea;
}
public void setTextArea(JTextArea textArea) {
this.textArea = textArea;
}
public static void main(String[] args) {
FileWatcher javaApplication7 = new FileWatcher();
}
}

Getting a table from my database to display in a JPanel

I am pretty new to Java, and I am dabbling in a small Point of Sale program just to teach myself how it works. My goal is to get a table from my database which stores the inventory data and display it within my JPanel I made. I thought what I did would work, but when I click my Load Database button, nothing displays. This is the first time I am working with java.sql so my knowledge of it is very basic. It may even be an obvious issue that I don't even see. Here's what I'm working with.
package gui;
import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import net.proteanit.sql.DbUtils;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class tableTest {
private JFrame frame;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
tableTest window = new tableTest();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public tableTest() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 804, 484);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 11, 768, 382);
frame.getContentPane().add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
JButton tableBtn = new JButton("Load Data");
tableBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String tableQuery = "SELECT * FROM inventory";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bazaar", "root", "password");
PreparedStatement ps = con.prepareStatement(tableQuery);
ResultSet rs = ps.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception e) {
e.printStackTrace();
}
}
});
tableBtn.setBounds(350, 411, 89, 23);
frame.getContentPane().add(tableBtn);
}
}
Just edited the code to make it a bit more simple to look at. I have data in the database, so I know that isn't the issue, but I cannot figure out how to get that data to display in the table.

SQLite database not displaying on button click

Evening all,
So I've been working on creating a local database using SQLite. (As a plugin that is part of Firefox). It uses three classes:
databaseConnection
Login
Display
and two tables (which come under the database MyFilms) called:
Users
MyFilms
databaseConnection is used to simply just connect to my SQLite database MyFilms, which it does fine.
The second class, Login, access my Users table from my database so it can access the logins and proceed to my GUI called Display.
Display will load the following GUI, which consists of a button, which when clicked is supposed to load the data from my database table MyFilms into a JTable:
However, when I click the button, nothing loads... it even looks like the JTable is not there, but when I check my code it defiantly is!
The code where I think the problem might lie is:
JButton btnLoadData = new JButton("Load Data");
btnLoadData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
String query ="Select * from MyFilms";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception anException){
anException.printStackTrace();
}
}
});
Any idea why the database is not showing here? Please find the code to each class below:
databaseConnection:
import java.sql.*;
import javax.swing.*;
public class databaseConnection {
Connection conn = null;
public static Connection dbConnector(){
try{
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Joe\\workspace\\MyFilms.sqlite");
JOptionPane.showMessageDialog(null, "Connection Successful!");
return conn;
}
catch(Exception anException)
{
JOptionPane.showMessageDialog(null, anException);
return null;
}
}
}
Login:
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.sql.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Login {
private JFrame frmTest;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login window = new Login();
window.frmTest.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connection = null;
private JTextField textFieldUN;
private JPasswordField passwordField;
/**
* Create the application.
*/
public Login() {
initialize();
connection = databaseConnection.dbConnector();
}
/**
* Initialise the contents of the frame.
*/
private void initialize() {
frmTest = new JFrame();
frmTest.setTitle("Database Login");
frmTest.setBounds(100, 100, 345, 184);
frmTest.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmTest.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("Username:");
lblNewLabel.setBounds(34, 37, 64, 14);
frmTest.getContentPane().add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("Password:");
lblNewLabel_1.setBounds(34, 66, 64, 14);
frmTest.getContentPane().add(lblNewLabel_1);
textFieldUN = new JTextField();
textFieldUN.setBounds(126, 34, 151, 20);
frmTest.getContentPane().add(textFieldUN);
textFieldUN.setColumns(10);
JButton btnLogin = new JButton("Login");
frmTest.getRootPane().setDefaultButton(btnLogin);
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
String query = "Select * from Users where username=? and password=?";
PreparedStatement pst = connection.prepareStatement(query);
pst.setString(1, textFieldUN.getText());
pst.setString(2, passwordField.getText());
ResultSet rs = pst.executeQuery();
int count = 0;
while(rs.next()){
count = count +1;
}
if (count == 1){
frmTest.dispose();
Display GUI = new Display();
GUI.setVisible(true);
}
else if (count > 1){
JOptionPane.showMessageDialog(null, "Duplicate Username and Password");
}
else{
JOptionPane.showMessageDialog(null, "Username or Password is not correct - Please try again..");
}
rs.close();
pst.close();
}
catch (Exception anException){
JOptionPane.showMessageDialog(null, anException);
}
}
});
btnLogin.setBounds(126, 111, 89, 23);
frmTest.getContentPane().add(btnLogin);
passwordField = new JPasswordField();
passwordField.setBounds(126, 64, 151, 17);
frmTest.getContentPane().add(passwordField);
}
}
Display:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import net.proteanit.sql.DbUtils;
import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.*;
public class Display extends JFrame {
private JPanel contentPane;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Display frame = new Display();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connection = null;
/**
* Create the frame.
*/
public Display() {
connection = databaseConnection.dbConnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 711, 443);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnLoadData = new JButton("Load Data");
btnLoadData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
String query ="Select * from MyFilms";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception anException){
anException.printStackTrace();
}
}
});
btnLoadData.setBounds(596, 11, 89, 23);
contentPane.add(btnLoadData);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(684, 45, -675, 349);
contentPane.add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
}
}
Any help would be greatly appreciated! Cheers..
However, when I run it in Eclipse I receive no errors at all. It runs fine, just does not display the database in the JTable.
Could you please replace your Display.java with the following:
Display.java
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.EmptyBorder;
import net.proteanit.sql.DbUtils;
public class Display extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Display frame = new Display();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connection = null;
/**
* Create the frame.
*/
public Display() {
connection = databaseConnection.dbConnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 711, 443);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout());
JButton btnLoadData = new JButton("Load Data");
btnLoadData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query = "Select * from MyFilms";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception anException) {
anException.printStackTrace();
}
}
});
// btnLoadData.setBounds(596, 11, 89, 23);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BorderLayout());
buttonPanel.add(btnLoadData, BorderLayout.EAST);
contentPane.add(buttonPanel, BorderLayout.NORTH);
JScrollPane scrollPane = new JScrollPane();
// scrollPane.setBounds(684, 45, -675, 349);
table = new JTable();
scrollPane.setViewportView(table);
contentPane.add(scrollPane, BorderLayout.CENTER);
}
}
and see the results?
Few changes have been made to your code. They are:
1) You first added scrollPane to the contentPane then you added table to scrollPane. I changed the order.
2) You used absolute layout. I changed that with BorderLayout.
The result displayed on my system is:
Hope this helps!

label unclear text when change its text

unfortunately I can't handle the change of txt when the button is clicked, I try to write a txt and overtime that I click the button, this txt value should change and allotting seems right, the only problem is that the printed number is not obvious and it seems some part of previous txt remains with it.
package berGenerator;
import java.awt.EventQueue;
public class sscce {
private JFrame frame;
private final Action action = new SwingAction();
private static int i = 555;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
sscce window = new sscce();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public sscce() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 550, 401);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton Next = new JButton("Next");
Next.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
Next.setAction(action);
Next.setBounds(167, 290, 198, 64);
frame.getContentPane().add(Next);
}
private class SwingAction extends AbstractAction {
public SwingAction() {
putValue(NAME, "Next Timeslot/scheduler");
putValue(SHORT_DESCRIPTION, "Some short description");
}
public void actionPerformed(ActionEvent e) {
i = i+1;
frame.getContentPane().validate();
frame.getContentPane().repaint();
String from = String.valueOf(i);
System.out.println("sw is: "+from);
JTextArea TextArea11 = new JTextArea("");
TextArea11.setText(from);
TextArea11.setForeground(Color.GREEN);
TextArea11.setBounds(6, 66, 87, 16);
frame.getContentPane().add(TextArea11);
}
}
}
Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify.
Layout managers are fundamental to the Swing API, you should make the time to learn how to use them, they will solve more problems than you think they create.
See Laying Out Components Within a Container for more details.
You're creating multiple instances of JTextArea and adding to the frame, but you're not removing any, you're running into a potential z-ordering problem at best and a major resource management issue at worst.
Instead, simply create a single instance of JTextArea, add it to the frame (just like you did your button) and simply update it when the Action is triggered, for example...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import static javax.swing.Action.NAME;
import static javax.swing.Action.SHORT_DESCRIPTION;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Test {
private JFrame frame;
private final Action action = new SwingAction();
private static int i = 555;
private JTextArea textArea;
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();
}
}
});
}
public Test() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textArea = new JTextArea(10, 20);
textArea.setText(String.valueOf(i));
frame.add(new JScrollPane(textArea));
JButton next = new JButton("Next");
next.setAction(action);
frame.getContentPane().add(next, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
}
private class SwingAction extends AbstractAction {
public SwingAction() {
putValue(NAME, "Next Timeslot/scheduler");
putValue(SHORT_DESCRIPTION, "Some short description");
}
public void actionPerformed(ActionEvent e) {
i = i + 1;
String from = String.valueOf(i);
System.out.println("sw is: " + from);
textArea.setText(from);
textArea.setForeground(Color.GREEN);
}
}
}

JOptionPane and scroll function

I want to JList a lot of results in a JOptionPane, however, I'm not sure how to add in a scroll function should there be too many results. How would I add a scroll bar to a JOptionPane? Any help would be great.
Thanks.
Here is an example using a JTextArea embedded in a JScrollPane:
JTextArea textArea = new JTextArea("Insert your Text here");
JScrollPane scrollPane = new JScrollPane(textArea);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
scrollPane.setPreferredSize( new Dimension( 500, 500 ) );
JOptionPane.showMessageDialog(null, scrollPane, "dialog test with textarea",
JOptionPane.YES_NO_OPTION);
Put the objects in a JList or other such component, drop it into a JScrollPane, and put the JScrollPane into the JOptionPane.
you can add any JComponent(s) to JOptionPane, including JScrollPane contains JList
I had a similar need, a JOptionPane with a Scrolling TextArea that any of my classes across my application could write to. This was to provide the user with status and progress information.
My approach was to make this a static class that I instantiated once and any class could call its update method to write to it. Below is the code and a small driver in the hopes it saves someone esle the time. This could be made not static, that just fit my needs.
package com.acme.view;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import com.acme.controller.MyController;
import com.acme.utils.NonModalMessage;
public class MyView {
private JFrame frame;
private int dialogNum = 0;
private MyController myCntrlr;
/**
* Launch the application.
*/
public static void main(String[] args) {
NonModalMessage.createMesgDialog();
NonModalMessage.updateMessage("Acme Anvil Targeting Progress");
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MyView window = new MyView();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MyView() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 250, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myCntrlr = new MyController();
JButton btnMybutton = new JButton("myButton");
btnMybutton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
NonModalMessage.setMessageVisible();
if(dialogNum > 0 && dialogNum % 10 == 0){
NonModalMessage.clearMessage();
NonModalMessage.updateMessage("Acme Anvil Targeting Progress");
myCntrlr.someMethod("Controller reports Roadrunner sighted. Message Number: ", dialogNum);
}
NonModalMessage.getMessage();
NonModalMessage.updateMessage("Message number: " + Integer.toString(dialogNum));
System.out.println("dialogNum: " + dialogNum);
dialogNum++;
}
});
frame.getContentPane().add(btnMybutton, BorderLayout.NORTH);
}
}
package com.acme.controller;
import com.acme.utils.NonModalMessage;
public class MyController {
public MyController(){
}
public void someMethod(String mystring, int myInt){
NonModalMessage.updateMessage(mystring + " "+ myInt);
}
}
package com.acme.utils;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
public class NonModalMessage {
private static JTextArea textArea = null;
private static JOptionPane oPane = null;
private static JDialog dialog = null;
private static JScrollPane myjsPane = null;
public NonModalMessage(){}
public static void createMesgDialog(){
textArea = new JTextArea();
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
myjsPane = new JScrollPane(textArea);
myjsPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
oPane = new JOptionPane();
oPane.add(myjsPane);
//final JDialog dialog = pane.createDialog(myPane, "Progress Dialog");
dialog = oPane.createDialog(null, "");
dialog.setTitle("Progress Messages");
dialog.setModal(false);
dialog.setSize(400, 250);
dialog.setResizable(true);
dialog.setAlwaysOnTop(true);
}
public static void setMessageVisible(){
dialog.setVisible(true);
}
public static void updateMessage(String newMessage){
String mytext = textArea.getText();
if(mytext.isEmpty()){
textArea.setText(newMessage);
}
else{
textArea.setText(mytext + "\n" + newMessage);
}
oPane.setMessage( myjsPane );
}
public static String getMessage(){
return textArea.getText();
}
public static void clearMessage(){
textArea.setText("");
oPane.setMessage( myjsPane );
}
}

Categories