This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Java adding ImageIcon to JLabel
(3 answers)
Closed last year.
I am building a Chat Bot application that queries text files according to topic and returns a text (answer) and would also want to display images related to that topic e.x Cricket. I am able to query and get text properly but trying to show images that that stored in the same place where my text file is. I am using ImageIcon for this. Is there any way that I can produce text with one or more images?
package com.javavalley;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JScrollPane;
import java.awt.event.*;
import javax.swing.border.Border;
import javax.swing.BorderFactory;
import java.lang.Override;
import java.lang.Thread;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.lang.Math;
public class ChatBot extends JFrame{
private JFrame frame;
private JTextArea chatArea;
private JTextField chatBox;
private JScrollPane scroll;
private Border border;
private ImageIcon image1;
private JLabel label1;
private ImageIcon image2;
private JLabel label2;
public static void main(String[] args){
new ChatBot();
}
public ChatBot(){
JPanel gui = new JPanel(new BorderLayout(5,5));
JPanel panel = new JPanel();
JLabel label = new JLabel(new ImageIcon(getClass().getResource("SamsungJ2.png")));
add(label);
panel.setLayout(new FlowLayout());
frame = new JFrame("Product Bot");
frame.setContentPane(gui);
chatArea = new JTextArea(10, 50);
chatBox = new JTextField();
scroll = new JScrollPane(chatArea,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
border = BorderFactory.createLineBorder(Color.BLUE, 1);
chatBox.setBorder(border);
JLabel bot = new JLabel(
"Hello! I am a \"Product Bot\"! that answers product related queries! " +
"Ask me by typing above. Type \"QUIT\" to end the program.");
chatArea.append("Chats: \n");
chatBox.setText("");
gui.add(chatBox, BorderLayout.PAGE_START);
gui.add(scroll);
gui.add(bot, BorderLayout.PAGE_END);
gui.setBorder(new EmptyBorder(5,5,5,5));
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
chatBox.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
String gtext = chatBox.getText();
chatArea.append("You: " +gtext + "\n");
chatBox.setText("");
if(gtext.equals("QUIT")|gtext.equals("quit")|gtext.equals("exit")) {
sleep(500);
System.exit(0);
}
String category = "";
try {
category = ProBot.findCategory(gtext);
System.out.println(category);
}
catch (Exception e) {
System.out.println("Exception thrown.");
}
String response = respond(category);
bot(response);
}
});
}
private void bot(String string)
{
chatArea.append("Bot: " + string + "\n");
}
private void sleep(int x) {
try {
Thread.sleep(x);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private String respond(String category)
{
String[] greetings = {"Hello, how can I help you?"};
String[] conversationContinue = {"How can I help you with?", "What else can I help you with?"};
String[] colorsinquiry = {"Black, Blue, Green, Red, Sierra Blue"};
String[] priceinquiry = {"Price is EUR 279"};
String[] productinquiry = {"Product is an Android 11 smart phone with latest features like Super AMOLED Display, 6.5 inches, Li-Ion 5000 mAh, non-removable battery, Octa-core (4x1.6 GHz Cortex-A55 & 4x1.2 GHz Cortex-A55))"};
String[] conversationComplete = {"Goodbye", "Bye", "Nice chatting with you. Bye!"};
if (category.equals("greeting")) return greetings[(int) (Math.random()*greetings.length)];
else if (category.equals("colors-inquiry")) return colorsinquiry[(int) (Math.random()*colorsinquiry.length)];
else if (category.equals("price-inquiry")) return priceinquiry[(int) (Math.random()*priceinquiry.length)];
else if (category.equals("product-inquiry")) return productinquiry[(int) (Math.random()*productinquiry.length)];
else if (category.equals("conversation-continue")) return conversationContinue[(int) (Math.random()*conversationContinue.length)];
else if (category.equals("conversation-complete")) return conversationComplete[(int) (Math.random()*conversationComplete.length)];
else return "Err.. :( Sorry, I did'nt get that!";
}
}
However, it gives me NullPointerException
Exception in thread "main" java.lang.NullPointerException
at java.desktop/javax.swing.ImageIcon.<init>(ImageIcon.java:217)
at com.javavalley.ChatBot.<init>(ChatBot.java:40)
at com.javavalley.ChatBot.main(ChatBot.java:32)
My UI
Remove add(label), and replace frame.setContentPane(gui); with the below, for example:
frame.getContentPane().add(gui, BorderLayout.NORTH);
frame.getContentPane().add(label, BorderLayout.SOUTH);
You could also add the label in the gui (e.g., gui.add(panel)), and add only the panel to the frame.
Related
So I have two classes, one is a GUI class with my JButtons, JFrames etc.... My other class has my main method along with a static method to play a sound. I am trying to create a constructor that will allow me to easily create a bunch of quiz questions, it will play a sound, ask the user to identify what makes that noise, and then display if the answer was correct or incorrect. I'm trying to put the JButton in the constructor as the "correct response" for the question that will be created, but I am getting a cannot find symbol error
This is my first Class
import javax.sound.sampled.Clip;
import java.io.File;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class NateApp {
private static JLabel label = new JLabel("Select the correct answer");
public static void main(String[] args)
{
File shred = new File("shredNoise.WAV");
// PlaySound(noise);
generateQuestion(" Shred", " Airplane ", "Car", "Pool Party", buttonA, shred);
}
public static void PlaySound(File Sound)
{
try{
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(Sound));
clip.start();
Thread.sleep(clip.getMicrosecondLength()/1000);
}
catch(Exception e){
}
}
public static void generateQuestion(String option1, String option2, String option3, String option4, JButton correctAnswer, File audioQue)
{
new GUI(option1, option2, option3, option4, correctAnswer, audioQue);
//System.out.println("Can you identify this sound?");
File noise = new File(String.valueOf(audioQue));
PlaySound(noise);
//System.out.println(option1 + option2 + option3 + option4);
if(correctAnswer.getModel().isPressed())
{
label.setText("Correct!");
}
}
}
and here is my second one with the GUI
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
public class GUI implements ActionListener {
private int clicks = 0;
private JLabel label = new JLabel("Can you identify this sound?");
private JFrame frame = new JFrame();
private Object ActionEvent;
public GUI(String optionA, String optionB, String optionC, String optionD, JButton correct, File noise) {
// the clickable button
JButton buttonA = new JButton("A " + optionA);
JButton buttonB = new JButton("B " + optionB);
JButton buttonC = new JButton("C " + optionC);
JButton buttonD = new JButton("D " + optionD);
buttonA.addActionListener(this);
buttonB.addActionListener(this);
buttonC.addActionListener(this);
buttonD.addActionListener(this);
// the panel with the button and text
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(30, 30, 10, 30));
panel.setLayout(new GridLayout(0, 1));
panel.add(buttonA);
panel.add(buttonB);
panel.add(buttonC);
panel.add(buttonD);
panel.add(label);
// set up the frame and display it
frame.add(panel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("GUI");
frame.pack();
frame.setVisible(true);
}
// process the button clicks
public void actionPerformed(ActionEvent e) {
}
// create one Frame
public static void main(String[] args) {
}
}
I am currently working on my school project to practice vocabulary, I have a method in my GUI that creates new vocabulary and the name of the list, I wanted to create a button that adds more Panels with input fields just this prototype image.
My idea is that when the user clicks
AddMoreButton it will add one JPanel just like P Panel, then the user can write vocabulary to send it to my database, is it possible to create something that?, I tried looping the P panel but it did not not change, any help would be appreciated.
private JPanel SetUpCreate() {
JPanel createPanel = new JPanel();
nameListInput = new JTextField(INPUT_FIELD_WIDTH);
termInput = new JTextField(INPUT_FIELD_WIDTH);
defintionInput = new JTextField(INPUT_FIELD_WIDTH);
p = new JPanel();
doneCreate = new JButton("Done");
doneCreate.addActionListener(new DoneCreateButtonAction());
addMoreButton = new JButton("Add");
addMoreButton.addActionListener(new AddMorePanelsListener());
p.setBorder(new BevelBorder(BevelBorder.RAISED));
p.add(termInput);
p.add(defintionInput);
JScrollPane pane = new JScrollPane(p);
createPanel.add(nameListInput);
createPanel.add(p);
createPanel.add(pane);
createPanel.add(doneCreate);
return createPanel;
}
private class DoneCreateButtonAction implements ActionListener {
public DoneCreateButtonAction() {
super();
}
public void actionPerformed(ActionEvent e) {
String namelist = nameListInput.getText();
String termglosa = termInput.getText();
String defintionglosa = defintionInput.getText();
try {
if (model.createWordList(namelist) && (model.createGlosa(termglosa, defintionglosa))) {
cl.show(cardPanel, "home");
}
} catch (IOException e1) {
JOptionPane.showMessageDialog(frame, "skapelsen av listan fungerar ej.");
}
}
}
private class AddMoreButtonAction implements ActionListener {
public AddMoreButtonAction() {
super();
}
public void actionPerformed(ActionEvent e) {
}
}
What I understand from your question is that you want to add another panel every time the user clicks the Add button and the panel to add contains fields for entering a word and its definition.
I see JScrollPane appears in the code you posted in your question. I think this is the correct implementation. In the below code, every time the user clicks the Add button I create a panel that contains the fields for a single word definition. This newly created panel is added to an existing panel that uses GridLayout with one column. Hence every time a new word definition panel is added, it is placed directly below the last word panel that was added and this GridLayout panel is placed inside a JScrollPane. Hence every time a word definition panel is added, the GridLayout panel height increases and the JScrollPane adjusts accordingly.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
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.JTextField;
import javax.swing.WindowConstants;
public class MorPanel implements ActionListener, Runnable {
private static final String ADD = "Add";
private JFrame frame;
private JPanel vocabularyPanel;
#Override
public void run() {
showGui();
}
#Override
public void actionPerformed(ActionEvent actionEvent) {
String actionCommand = actionEvent.getActionCommand();
switch (actionCommand) {
case ADD:
vocabularyPanel.add(createWordPanel());
vocabularyPanel.revalidate();
vocabularyPanel.repaint();
break;
default:
JOptionPane.showMessageDialog(frame,
actionCommand,
"Unhandled",
JOptionPane.ERROR_MESSAGE);
}
}
public JButton createButton(String text) {
JButton button = new JButton(text);
button.addActionListener(this);
return button;
}
public JPanel createButtonsPanel() {
JPanel buttonsPanel = new JPanel();
buttonsPanel.add(createButton(ADD));
return buttonsPanel;
}
private JScrollPane createMainPanel() {
vocabularyPanel = new JPanel(new GridLayout(0, 1));
vocabularyPanel.add(createWordPanel());
JScrollPane scrollPane = new JScrollPane(vocabularyPanel);
return scrollPane;
}
private JPanel createWordPanel() {
JPanel wordPanel = new JPanel();
JLabel wordLabel = new JLabel("Enter Term");
JTextField wordTextField = new JTextField(10);
JLabel definitionLabel = new JLabel("Enter Term Definition");
JTextField definitionTextField = new JTextField(10);
wordPanel.add(wordLabel);
wordPanel.add(wordTextField);
wordPanel.add(definitionLabel);
wordPanel.add(definitionTextField);
return wordPanel;
}
private void showGui() {
frame = new JFrame("Vocabulary");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(createMainPanel(), BorderLayout.CENTER);
frame.add(createButtonsPanel(), BorderLayout.PAGE_END);
frame.setSize(480, 200);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new MorPanel());
}
}
As your code is not an Minimal Reproducible Example, I cannot provide further assistance than this:
Red part: Your main JPanel with BoxLayout
Green part: another JPanel with your JTextField in it.
Purple part: JScrollPane
Blue parts: custom JPanels with 2 panes in them, one on top for the number, one on the bottom for both JTextFields and icon, so I would say GridBagLayout or BoxLayout + FlowLayout
Orange part: JPanel with GridBagLayout or FlowLayout
Each time you clic on the + icon, you just create a new instance of the custom blue JPanel and that's it.
I've been having some (very annoying) trouble with these scripts that I've created.
Sburb.java
import java.awt.Color;
import javax.swing.*;
public class Sburb
{
public static void main (String[] args)
{
JFrame frame = new JFrame ("Welcome to Sburb");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
spirograph page = new spirograph();
progressbar bar = new progressbar();
frame.getContentPane().add(page);
frame.getContentPane().add(bar);
frame.pack();
frame.setVisible(true);
frame.setResizable(true);
}
}
progressbar.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class progressbar extends JPanel
{
JProgressBar current;
JTextArea out;
JButton find;
Thread runner;
int num = 1;
progressbar()
{
super();
//setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel();
pane.setLayout(new FlowLayout());
current = new JProgressBar(0, 2000);
current.setStringPainted(false);
pane.add(current);
//setContentPane(pane);
}
public void iterate() {
while (num < 2000) {
current.setValue(num);
try {
Thread.sleep(300);
} catch (InterruptedException e) { }
num += 5;
}
}
// public static void main(String[] arguments) {
// progressbar frame = new progressbar();
// frame.pack();
// frame.setVisible(true);
// frame.iterate();
// }
}
spirograph.java
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class spirograph extends JPanel
{
private ImageIcon image;
private JLabel label;
private JLabel frame = new JLabel();
private JPanel panel = new JPanel();
spirograph()
{
this.setOpaque(true);
this.setBackground(Color.BLACK);
setLayout(new FlowLayout());
image = new ImageIcon(getClass().getResource("Gate.gif"));
label = new JLabel(image);
add(label);
progressbar bar = new progressbar();
}
}
I'm trying to call the file "progressbar" to the Sburb file but when I do, it gives me just the simple JFrame of this (not fixed):
http://imgur.com/1aAmPwJ
And when I get rid of the "frame.getContentPane().add(bar);" in Sburb.java, it gives me this (fixed, kind-of):
http://imgur.com/15aGtT2
How do I fix this? I've looked everywhere and yet I still can't figure it out! I also can't seem to figure out how to align the bar directly below the gif.
frame.getContentPane().add(page);
frame.getContentPane().add(bar);
The content pane of a JFrame is a set to a BorderLayout which can only accept one component in any one of the border layout constraints. Given no constraints were supplied here, the JRE will try to put them both in the CENTER.
For this, and a variety of other reasons, I would advise to ignore the existing content pane, arrange the entire GUI (as many panels as it consists of) into another panel (let's call it ui) then call
frame.setContentPane(ui);
In our aplication we use Metal L&F. We are using a floatable JToolBar; it happens that when doing the drag behavior it appears with the Windows L&F.
May anyone say me how to keep Metal L&F when dragging the JToolBar?
Thanks
P.D. Our JToolBar is within a JPanel container that user BorderLayout Layout Manager.
Maybe I explained badly my question. So I post an example taken from The Java Tutorials to give anyone an idea of what happens to my application.
If you execute the following code the main JFrame appears decorated with Ocean Theme; but when I drag the JToolBar its decorated is not Ocean. What can I do??.
Many thanks in advance
package components;
/*
* ToolBarDemo.java requires the following addditional files:
* images/Back24.gif
* images/Forward24.gif
* images/Up24.gif
*/
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.plaf.metal.MetalLookAndFeel;
import javax.swing.plaf.metal.OceanTheme;
public class ToolBarDemo extends JPanel
implements ActionListener {
protected JTextArea textArea;
protected String newline = "\n";
static final private String PREVIOUS = "previous";
static final private String UP = "up";
static final private String NEXT = "next";
public ToolBarDemo() {
super(new BorderLayout());
//Create the toolbar.
JToolBar toolBar = new JToolBar("Still draggable");
addButtons(toolBar);
//Create the text area used for output. Request
//enough space for 5 rows and 30 columns.
textArea = new JTextArea(5, 30);
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
//Lay out the main panel.
setPreferredSize(new Dimension(450, 130));
add(toolBar, BorderLayout.PAGE_START);
add(scrollPane, BorderLayout.CENTER);
}
protected void addButtons(JToolBar toolBar) {
JButton button = null;
//first button
button = makeNavigationButton("Back24", PREVIOUS,
"Back to previous something-or-other",
"Previous");
toolBar.add(button);
//second button
button = makeNavigationButton("Up24", UP,
"Up to something-or-other",
"Up");
toolBar.add(button);
//third button
button = makeNavigationButton("Forward24", NEXT,
"Forward to something-or-other",
"Next");
toolBar.add(button);
}
protected JButton makeNavigationButton(String imageName,
String actionCommand,
String toolTipText,
String altText) {
//Look for the image.
String imgLocation = "images/"
+ imageName
+ ".gif";
URL imageURL = ToolBarDemo.class.getResource(imgLocation);
//Create and initialize the button.
JButton button = new JButton();
button.setActionCommand(actionCommand);
button.setToolTipText(toolTipText);
button.addActionListener(this);
if (imageURL != null) { //image found
button.setIcon(new ImageIcon(imageURL, altText));
} else { //no image found
button.setText(altText);
System.err.println("Resource not found: "
+ imgLocation);
}
return button;
}
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
String description = null;
// Handle each button.
if (PREVIOUS.equals(cmd)) { //first button clicked
description = "taken you to the previous <something>.";
} else if (UP.equals(cmd)) { // second button clicked
description = "taken you up one level to <something>.";
} else if (NEXT.equals(cmd)) { // third button clicked
description = "taken you to the next <something>.";
}
displayResult("If this were a real app, it would have "
+ description);
}
protected void displayResult(String actionDescription) {
textArea.append(actionDescription + newline);
textArea.setCaretPosition(textArea.getDocument().getLength());
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("ToolBarDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add content to the window.
frame.add(new ToolBarDemo());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
setsLF();
createAndShowGUI();
}
});
}
/**
*
*/
private static void setsLF() {
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
MetalLookAndFeel.setCurrentTheme(new OceanTheme());
UIManager.setLookAndFeel(new MetalLookAndFeel());
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ToolBarDemo.class.getName()).log (java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ToolBarDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ToolBarDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ToolBarDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
JFrame.setDefaultLookAndFeelDecorated(Boolean.TRUE);
return;
}
}
Looks like nowadays the toplevel container of the ripped of toolBar is of type JDialog, so you have the set the lafDecoration for that as well:
JFrame.setDefaultLookAndFeelDecorated(Boolean.TRUE);
JDialog.setDefaultLookAndFeelDecorated(true);
Works for jdk7 and vista, didn't test other environments.
I made a small project as you described:
public class LafTest
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(500, 500);
JPanel panel = new JPanel(new BorderLayout());
JToolBar toolbar = new JToolBar();
toolbar.add(new JButton("button1"));
toolbar.add(new JButton("button2"));
panel.add(toolbar, BorderLayout.PAGE_START);
frame.add(panel);
frame.setVisible(true);
}
}
Works fine for me, all the time the JToolBar has Metal-LAF.
(OS: Windows 7 x64, java version "1.7.0_09")
Please compare your code with this snippet. Propably you used the UIManager-class somewhere. If you still cannot fix this issue, you should post some of the used code and maybe some more details about your OS and the used Java version.
I am writing a small program that converts files, and I wanted to have a box pop up that asks the user to please wait while the program loops through and converts all the relevant files, but I am running into a small problem. The box that pops up should have a JLabel and a JButton, while the user is "waiting" I wanted to display a message that says please wait, and a disabled "OK" JButton, and then when its finished I wanted to set the text of the JLabel to let them know that It successfully converted their files, and give them a count of how many files were converted. (I wrote a method called alert that sets the text of the label and enables the button.) The problem is That while the program is running, the box is empty, the Label and the Button are not visible, when it finishes, label appears with the final text that I want and the button appears enabled. I am not sure exactly what is going on, I tried changing the modifiers of the JLabel and JButton several times but I cant seem to get it to work correctly. Here is the code for the box that pops up, any help is greatly appricated.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class PleaseWait extends javax.swing.JFrame{
private static final int height = 125;
private static final int width = 350;
final static JLabel converting = new JLabel("Please Wait while I convert your files");
private static JButton OK = new JButton("OK");
public PleaseWait(){
// creates the main window //
JFrame mainWindow = new JFrame();
mainWindow.setTitle("Chill For A Sec");
mainWindow.setSize(width, height);
mainWindow.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
// creates the layouts//
JPanel mainLayout = new JPanel(new BorderLayout());
JPanel textLayout = new JPanel(new FlowLayout());
JPanel buttonLayout = new JPanel(new FlowLayout());
// Sets Text //
converting.setText("Please wait while I convert your files");
// disables button //
OK.setEnabled(false);
// adds to the layouts //
textLayout.add(converting);
buttonLayout.add(OK);
mainLayout.add(textLayout, BorderLayout.CENTER);
mainLayout.add(buttonLayout, BorderLayout.SOUTH);
// adds to the frame //
mainWindow.add(mainLayout);
// sets everything visible //
mainWindow.setVisible(true);
}
public static void alert(){
OK.setEnabled(true);
String total = String.valueOf(Convert.result());
converting.setText("Sucsess! " + total + " files Converted");
}
}
Okay here's the issue. You are extending the JFrame . That means your class IS a JFrame.
When you create the PleaseWait frame you don't do anything to it. This is the empty box you are seeing. You are instead creating a different JFrame in your constructor. Remove your mainWindow and instead just use this. Now all of your components will be added to your PleaseWait object. That should fix your blank box issue.
You need an application to create your frame first. This is a simple example of such application.
import javax.swing.UIManager;
import java.awt.*;
public class Application {
boolean packFrame = false;
//Construct the application
public Application() {
PleaseWait frame = new PleaseWait();
//Validate frames that have preset sizes
//Pack frames that have useful preferred size info, e.g. from their layout
if (packFrame) {
frame.pack();
}
else {
frame.validate();
}
//Center the window
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = frame.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
frame.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
frame.setVisible(true);
frame.convert();
}
//Main method
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch(Exception e) {
e.printStackTrace();
}
new Application();
}
}
You have to slightly modify your frame to add controls to the content pane. You can do some work after frame is created, then call alert.
import java.awt.*;
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.JPanel;
public class PleaseWait extends JFrame {
private static final int height = 125;
private static final int width = 350;
final static JLabel converting = new JLabel();
private static JButton OK = new JButton("OK");
BorderLayout borderLayout1 = new BorderLayout();
JPanel contentPane;
int count;
public PleaseWait(){
contentPane = (JPanel)this.getContentPane();
contentPane.setLayout(borderLayout1);
this.setSize(new Dimension(width, height));
this.setTitle("Chill For A Sec");
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
// creates the layouts//
JPanel mainLayout = new JPanel(new BorderLayout());
JPanel textLayout = new JPanel(new FlowLayout());
JPanel buttonLayout = new JPanel(new FlowLayout());
// Sets Text //
converting.setText("Please wait while I convert your files");
// disables button //
OK.setEnabled(false);
OK.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
// adds to the layouts //
textLayout.add(converting);
buttonLayout.add(OK);
mainLayout.add(textLayout, BorderLayout.CENTER);
mainLayout.add(buttonLayout, BorderLayout.SOUTH);
// adds to the frame //
contentPane.add(mainLayout);
}
public void convert(){
count = 0;
for (int i = 0; i <10; i++){
System.out.println("Copy "+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
count++;
}
alert();
}
public void alert(){
OK.setEnabled(true);
// String total = String.valueOf(Convert.result());
converting.setText("Sucsess! " + count + " files Converted");
}
}