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);
}
}
}
Related
I am creating a NotePad app in Java Swing but when I am trying to open a popup to set a title, it is not showing up.
The class that calls the popup:
import java.io.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
public class NewFile implements ActionListener{
public static String title;
public void actionPerformed(ActionEvent e){
PopupFileName popup = new PopupFileName();
/*try{
Thread.sleep(30000);
}catch (InterruptedException o){
o.printStackTrace();
}*/
JTextArea titl = popup.title;
title = titl.getText();
try{
File writer = new File(title+".txt");
if(writer.createNewFile()){
System.out.println("file created");
}else{
System.out.println("file exists");
}
}catch (IOException i) {
System.out.println("An error occurred.");
i.printStackTrace();
}
}
}
The popup class that is supposed to open:
import javax.swing.*;
public class PopupFileName{
static JFrame popup = new JFrame("File Title");
static JLabel titlel = new JLabel("Title:");
static public JTextArea title = new JTextArea();
public static void main(String[] args){
popup.setSize(200,300);
popup.setVisible(true);
popup.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
popup.add(titlel);
popup.add(title);
}
}
Is there any way I can make it visible and make it able to get the text before it is created?
Start by taking a look at:
Creating a GUI With Swing
How to Write an Action Listener
How to Use Scroll Panes
How to Use Buttons, Check Boxes, and Radio Buttons
How to Make Dialogs
You're running in an event driven environment, this means, something happens and then you respond to it.
The problem with your ActionListener is, it's trying to present a window and then, immediately, trying to get some result from it. The problem is, the window probably isn't even present on the screen yet.
What you need is some way to "stop" the code execution until after the user responds. This is where a modal dialog comes in.
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
JButton btn = new JButton("Test");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String title = PopupFileName.getTitle(TestPane.this);
System.out.println(title);
}
});
add(btn);
}
}
public static class PopupFileName extends JPanel {
private JLabel titlel = new JLabel("Title:");
private JTextArea title = new JTextArea(20, 40);
public PopupFileName() {
setLayout(new BorderLayout());
add(titlel, BorderLayout.NORTH);
add(new JScrollPane(title));
}
public String getTitle() {
return title.getText();
}
public static String getTitle(Component parent) {
PopupFileName popupFileName = new PopupFileName();
int response = JOptionPane.showConfirmDialog(parent, popupFileName, "Title", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
switch (response) {
case JOptionPane.OK_OPTION:
return popupFileName.getTitle();
default: return null;
}
}
}
}
In my project code, we are using custom dialogs. I am facing some weird issues with them.
I have a child dialogue and a parent dialogue.
Ideally a child dialogue goes to invisible state when we invoke parent.setVisible(false).
But I am seeing some strange behaviour.
When I make parent.setVisible(false) then still my child dialog remains visible but when I try to get child.isVisible() : it gives me false.
Also when I try to invoke child.setVisible(false), again it has no effect in visiblity of parent dialog .
NOTE: I cannot show any code sample due to too much complexity, lenght and other external API issues. Also I tried replicating this using external programs but it works as expected and no issues seen.
I just want to know does anybody knows any scenario in which a child dialog control get loosen up when we make parent.setVisible(false)?
I just want to know does anybody knows any scenario in which a child
dialog control get loosen up when we make parent.setVisible(false)?
for parent is called setVisible(false) too,
be sure that you to reuse reduced number of childs, to set DefaultCloseOparation to HIDE or DISPOSE_ON_CLOSE (by defasult the last container turn off light, but hasn't effect if is there modality between containers)
for example
import java.awt.BorderLayout;
import java.awt.Dialog.ModalityType;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
/**
*
* #author user
*/
public class ModalityAndJDialog {
private JFrame frame = new JFrame();
private JDialog dialog1;
private JDialog dialog2;
private JButton button = new JButton("Start Swing Timer");
private JButton button1 = new JButton();
private JButton button01 = new JButton();
private JButton button02 = new JButton();
private Timer timer;
public ModalityAndJDialog() {
button.setAction(updateCol());
frame.setTitle("JFrame");
frame.add(button, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setSize(400, 300);
frame.setLocation(150, 150);
frame.setVisible(true);
timer = new javax.swing.Timer(500, updateCol());
timer.setRepeats(false);
timer.start();
}
private Action updateCol() {
return new AbstractAction("Show JDialog") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
if (dialog1 == null) {
dialog1 = new JDialog(dialog1, ModalityType.APPLICATION_MODAL);
dialog1.setTitle("1st. JDialog");
dialog1.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
button1.setAction(updateCol1());
button01.setAction(updateCol01());
dialog1.add(button1, BorderLayout.SOUTH);
dialog1.add(button01, BorderLayout.NORTH);
dialog1.pack();
dialog1.setSize(400, 300);
dialog1.setLocation(250, 250);
dialog1.setVisible(true);
} else {
EventQueue.invokeLater(() -> {
dialog1.setVisible(true);
});
}
}
};
}
private Action updateCol01() {
return new AbstractAction("Hide JDialog") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
if (dialog1 != null) {
dialog1.setVisible(false);
}
}
};
}
private Action updateCol1() {
return new AbstractAction("Show Child JDialog") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
if (dialog2 == null) {
dialog1.setTitle("2nd. JDialog");
dialog2 = new JDialog(frame, ModalityType.APPLICATION_MODAL);
dialog2.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
button02.setAction(updateCol02());
dialog2.add(button02, BorderLayout.SOUTH);
dialog2.pack();
dialog2.setSize(400, 300);
dialog2.setLocation(350, 350);
dialog2.setVisible(true);
} else {
EventQueue.invokeLater(() -> {
dialog2.setVisible(true);
if (!frame.isVisible()) {
frame.setVisible(true);
}
});
}
}
};
}
private Action updateCol02() {
return new AbstractAction("Hide JDialog") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
if (frame != null) {
frame.setVisible(false);
}
/*if (dialog1 != null) {
dialog1.setVisible(false);
}*/
}
};
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
/*UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());*/
} catch (UnsupportedLookAndFeelException | ClassNotFoundException | IllegalAccessException | InstantiationException ex) {
System.out.println("[L&F][Exception] " + ex.getMessage());
}
EventQueue.invokeLater(() -> {
new ModalityAndJDialog();
});
}
}
I wanted to know if there's any easy way to delete the content (text) from a JLabel after 5 seconds. Is that possible? Because I have a JLabel in a JFrame and it shows some internal errors from the program I'm coding and I want the JLabel to show the message for a couple of seconds and then go to blank. Any ideas?
Simplest solution is to use a Swing Timer. It will prevent freezing the GUI and ensure proper Thread access (ie, UI modification is performed on the EDT).
Small demo example:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestLabelDelete {
private JFrame frame;
private JLabel label;
protected void initUI() {
frame = new JFrame(TestLabelDelete.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label = new JLabel("Some text to delete in 5 seconds");
frame.add(label);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Timer t = new Timer(5000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
label.setText(null);
}
});
t.setRepeats(false);
t.start();
}
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException,
UnsupportedLookAndFeelException {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
TestLabelDelete testLogin = new TestLabelDelete();
testLogin.initUI();
}
});
}
}
Use Timer. Please see my example.
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;
public class SourceCodeProgram {
private static void createAndShowGUI() {
// Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
// Create and set up the window.
JFrame frame = new JFrame("HelloWorldSwing");
frame.setMinimumSize(new Dimension(200, 300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Add the ubiquitous "Hello World" label.
final JLabel label = new JLabel("Hello World");
frame.getContentPane().add(label);
// Display the window.
frame.pack();
frame.setVisible(true);
Timer timer = new Timer(5000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Clear text or whatever you want
label.setText("New text");
}
});
// start Tick-Tack
timer.start();
}
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Or you can write a separate class, which can clean label.
class JLabelCleaner {
private JLabel label;
private int waitSeconds;
public JLabelCleaner(int waitSeconds, JLabel label) {
this.label = label;
this.waitSeconds = waitSeconds;
}
public void startCountdownFromNow() {
Timer timer = new Timer(waitSeconds * 1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
label.setText("");
}
});
timer.start();
}
}
Now, you can use it whenever you need it in this way:
new JLabelCleaner(5, label).startCountdownFromNow();
Also see:
How to Use Swing Timers
There is an easy solution to this.
JLabel label = new JLabel("error text");
Thread.sleep(5000);
label.setText("");
Hope this helps!
EDIT: If you don't want the program to freeze for 5 secs you'll have to put this inside a Runnable.
It's very easy to do... just create a new thread and write code to clear text on label, and make that thread to sleep for 5sec and then start it.
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class LabelThread {
private JLabel textLabel;
public LabelThread() {
try {
JFrame frame = new JFrame("Label");
frame.setSize(500, 500);
textLabel = new JLabel("Hiiii.... Kill me");
frame.setContentPane(textLabel);
frame.setVisible(true);
MyThread thread = new MyThread();
MyThread.sleep(5000);
thread.start();
} catch (InterruptedException ex) {
}
}
class MyThread extends Thread{
#Override
public void run() {
System.out.print("Running thread");
textLabel.setText("");
}
}
public static void main(String args[]){
LabelThread labelThread = new LabelThread();
}
}
I've made my own SwingWorker example to get familiar with how it works.
What I'm wanting to do is the following:
When the button is clicked I want a progress bar appear until the task is done I want to simply remove the progress bar and add a string to the dialog.
When the button is clicked, the progress bar comes up but never goes away. (never removes the progress bar after 10 seconds and never places the label up)
Here is an SSCCE:
package swingtesting;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;
public class SwingTesting {
/**
* Creates a frame that will hold a simple button to make use of SwingWorker
*/
public static void main(String[] args) {
// TODO code application logic here
JFrame frame = new JFrame();
JButton button = new JButton();
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new GuiWorker().execute();
}
});
button.setText("Test Me");
frame.getContentPane().add(button);
frame.pack();
frame.setVisible(true);
}
}
class GuiWorker extends SwingWorker<Integer, Integer> {
/*
* This should just create a frame that will hold a progress bar until the
* work is done. Once done, it should remove the progress bar from the dialog
* and add a label saying the task complete.
*/
private JFrame frame = new JFrame();
private JDialog dialog = new JDialog(frame, "Swingworker test", true);
private JProgressBar progressBar = new JProgressBar();
public GuiWorker() {
progressBar.setString("Waiting on time");
progressBar.setStringPainted(true);
progressBar.setIndeterminate(true);
dialog.getContentPane().add(progressBar);
dialog.pack();
dialog.setVisible(true);
}
#Override
protected Integer doInBackground() throws Exception {
Thread.sleep(10000);
return 0;
}
#Override
protected void done() {
JLabel label = new JLabel("Task Complete");
dialog.getContentPane().remove(progressBar);
dialog.getContentPane().add(label);
}
}
Here an updated version of your code which works
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;
public class SwingTesting {
public static void main(String[] args) {
EventQueue.invokeLater( new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
JButton button = new JButton();
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new GuiWorker().execute();
}
});
button.setText("Test Me");
frame.getContentPane().add(button);
frame.pack();
frame.setVisible(true);
}
} );
}
}
class GuiWorker extends SwingWorker<Integer, Integer> {
/*
* This should just create a frame that will hold a progress bar until the
* work is done. Once done, it should remove the progress bar from the dialog
* and add a label saying the task complete.
*/
private JFrame frame = new JFrame();
private JDialog dialog = new JDialog(frame, "Swingworker test", true);
private JProgressBar progressBar = new JProgressBar();
public GuiWorker() {
progressBar.setString("Waiting on time");
progressBar.setStringPainted(true);
progressBar.setIndeterminate(true);
dialog.getContentPane().add(progressBar);
dialog.pack();
dialog.setModal( false );
dialog.setVisible(true);
}
#Override
protected Integer doInBackground() throws Exception {
System.out.println( "GuiWorker.doInBackground" );
Thread.sleep(1000);
return 0;
}
#Override
protected void done() {
System.out.println("done");
JLabel label = new JLabel("Task Complete");
dialog.getContentPane().remove(progressBar);
dialog.getContentPane().add(label);
dialog.getContentPane().validate();
}
}
Key point is that setting a model dialog visible blocks until the dialog is disposed. So making it non-modal fixed it + the validate call on the content pane when you switch components. I also adjusted your main method to run on the EDT, and added some System.out calls. If you remove the setModal( false ) call you will see those statements are not printed until you close the dialog
There's no need to make the dialog non-modal. Simply display the dialog after starting the SwingWorker. This can be done either from the calling class, the one executing the SwingWorker, by first calling execute, and then showing the dialog, or it can be done from the SwingWorker, but if from the latter, you'll have to make your own pseudo-execute method that calls super's execute, and then shows the dialog. Note that you can't override execute() itself since it's final.
For example...
import java.awt.CardLayout;
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.concurrent.ExecutionException;
import javax.swing.*;
#SuppressWarnings("serial")
public class SwingTesting2 {
private static void createAndShowGui() {
final JFrame frame = new JFrame("SwingTesting2");
final JDialog dialog = new JDialog(frame, "Dialog",
ModalityType.APPLICATION_MODAL);
final DialogPanel dialogPanel = new DialogPanel();
dialog.getContentPane().add(dialogPanel.getMainPanel());
dialog.pack();
dialog.setLocationRelativeTo(frame);
JButton button = new JButton(new AbstractAction("Test Me") {
#Override
public void actionPerformed(ActionEvent actEvt) {
final GuiWorker2 guiWorker = new GuiWorker2();
guiWorker.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent pcEvt) {
if (pcEvt.getPropertyName().equals("state")) {
if (pcEvt.getNewValue() == SwingWorker.StateValue.DONE) {
try {
dialogPanel.done(guiWorker.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
} else if (pcEvt.getPropertyName().equals("progress")) {
dialogPanel.setProgress((Integer)pcEvt.getNewValue());
}
}
});
guiWorker.execute();
dialogPanel.start();
dialog.setVisible(true);
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(button);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class GuiWorker2 extends SwingWorker<Integer, Integer> {
private static final int MAX_COUNT = 20;
private static final long SLEEP_TIME = 100;
private int count = 0;
#Override
protected Integer doInBackground() throws Exception {
while (count < MAX_COUNT) {
Thread.sleep(SLEEP_TIME);
count++;
setProgress((100 * count) / MAX_COUNT);
}
return count;
}
}
#SuppressWarnings("serial")
class DialogPanel {
public static final String PROGRESS_BAR = "Progress Bar";
public static final String DONE = "Done";
private static final int TIMER_DELAY = 2000;
private CardLayout cardLayout = new CardLayout();
private JPanel mainPanel = new JPanel(cardLayout);
private JLabel doneLabel = new JLabel("Done", JLabel.CENTER);
private JProgressBar progressBar = new JProgressBar();
public DialogPanel() {
progressBar.setString("Waiting on time");
progressBar.setStringPainted(true);
progressBar.setIndeterminate(false);
mainPanel.add(progressBar, PROGRESS_BAR);
mainPanel.add(doneLabel, DONE);
}
public void setProgress(Integer newValue) {
progressBar.setValue(newValue);
}
public void start() {
cardLayout.show(mainPanel, PROGRESS_BAR);
progressBar.setValue(0);
}
public void done(int countValue) {
doneLabel.setText(DONE + ". Count: " + countValue);
cardLayout.show(mainPanel, DONE);
new Timer(TIMER_DELAY, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Window win = SwingUtilities.getWindowAncestor(mainPanel);
win.dispose();
}
}){{setRepeats(false);}}.start();
}
public JPanel getMainPanel() {
return mainPanel;
}
}
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 );
}
}