refill JTable from - java

I open JDialog from main window to show set of data, retrieved according to parameters and mode.
(in this simplified version parameters doesn't matter, just "Mode", in real I fill it from recordset).I want
1.to fill table in Dialog Window initially
optionally use button to show another set of data, retrieved with different mode
First mission is OK. Creating table and filling is organised as procedure
that works properly from dialog constructor.
But when I run this procedure from ActionListener of button -- I get another copy of table in the same window - it makes sense because I create it once again as "new". I cant find the way I can refill data on the same table! All examples on the net are about creating a new one
Here is calling part
btnFreqHistory.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Running history");
DlgFreqHistory FreqHist= new DlgFreqHistory(1000,2,1 );
FreqHist.setDefaultCloseOperation(FreqHist.DISPOSE_ON_CLOSE);
FreqHist.setVisible(true);
}
});
Here is JDialog part:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.*;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;
import javax.swing.JTable;
import java.sql.ResultSet;
public class DlgFreqHistory extends JDialog {
private final JPanel contentPanel = new JPanel();
static int Freq;
static int Side;
static int Mode; //1- last 10 results, 2 - best results
/**
* Launch the application.
*/
public static void main(String[] args) {
}
/**
* Create the dialog.
*/
public DlgFreqHistory(int iFreq, int iSide, int iMode) {
Freq = iFreq;
Side = iSide;
Mode = iMode;
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setLayout(new FlowLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
this.setTitle("Last results for " + iFreq );
**// !! This call works fine**
GetHistoryByMode(iFreq, iSide, 2);
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
JButton btn_getData = new JButton("Get data");
btn_getData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
System.out.println("in action performed");
***// !! This call creates another table***
GetHistoryByMode(Freq, Side, 1);
}
} );
buttonPane.add(btn_getData);
getRootPane().setDefaultButton(btn_getData);
}
private void GetHistoryByMode(int Freq, int iSide, int Mode)
{
System.out.println("in GetHistoryByMode " + Freq + " " + iSide + " " + Mode);
String HistColumns[] = new String[2];
String HistData[][] = new String[10][2];
if (Mode==1) {
HistColumns[0] = "X1";
HistColumns[1] = "Result";
HistData[0][0] = "xx1";
HistData[0][1] = "15";
HistData[1][0] = "xx2";
HistData[1][1] = "20";
}
if (Mode==2) {
HistColumns[0] = "Y1";
HistColumns[1] = "Result";
HistData[0][0] = "yy1";
HistData[0][1] = "15";
HistData[1][0] = "yy2";
HistData[1][1] = "23";
}
JTable FreqHistory = new JTable(HistData, HistColumns);
contentPanel.add(FreqHistory);
JScrollPane scrollPane;
scrollPane = new JScrollPane( FreqHistory );
contentPanel.add( scrollPane, BorderLayout.CENTER );
}
}

Don't create the JTable in the GetHistoryByMode method, instead, create it within the constructor and add it to the UI there. Then in the GetHistoryByMode method, create a new TableModel and apply it (setModel) to the existing JTable
Take a look at How to Use Tables for more details
You might also like to have a read through Code Conventions for the Java TM Programming Language, it will make it easier for people to read your code and for you to read others

Related

MouseListener inside loop isnt using updated variable values

I want to first apologize for my poor English.
I made some JPanels which I'm putting inside one JPanel and this last JPanel I'm putting it in one JScrollPane, each Jpanel has some JLabels that have text inside them. I've done that and everything is working until now, then I added a mouseListener to System.out.print the text inside the JLabels.
The texts are different, but on the console I'm getting the same text,
here's my code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package testa;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import java.awt.event.*;
public class Test extends JFrame{ //see https://www.javatpoint.com/java-naming-conventions
private JLabel[] titles;
private JLabel[] descriptions;
private JPanel [] panels;
private JScrollPane jScrollPane1;
private JPanel bigPanel;
private final static int NUM_OF_RESULTS =10;
String identifier ;
String title;
String authors;
String resume;
String references;
public Test() throws IOException {
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(1000,500);
//jScrollPane1.setSize(1000, 500); and layouts. see following comments
bigPanel = new JPanel();
bigPanel.setBounds(30, 90, 950, 400);
//set layout to
GridLayout layout = new GridLayout(NUM_OF_RESULTS, 0);
bigPanel.setLayout(layout);
jScrollPane1 = new JScrollPane(bigPanel);
jScrollPane1.setBounds(30, 90, 950, 400);
getContentPane().add(jScrollPane1);
requetezQuery();
//pack(); //see https://stackoverflow.com/questions/22982295/what-does-pack-do
setVisible(true); //set visible typically comes last
}
public void requetezQuery() {
int actual=0;
titles = new JLabel[NUM_OF_RESULTS];
descriptions = new JLabel[NUM_OF_RESULTS];
panels = new JPanel[NUM_OF_RESULTS];
for(int i = 0; i<NUM_OF_RESULTS; i++){
title = "Title "+i;
resume = "Description "+i ;
titles[i]= new JLabel();
descriptions[i]= new JLabel();
panels[i]= new JPanel();
panels[i].setPreferredSize(new Dimension(250, 50));
panels[i].setLayout(new FlowLayout()); //FlowLayout is default for JPanel
titles[i].setText(title);
descriptions[i].setText(resume.substring(0, Math.min(resume.length(), 100))+"...");
titles[i].setForeground(Color.blue);
descriptions[i].setForeground(Color.black);
titles[i].addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
System.out.println(title);
}
});
panels[i].add(titles[i]);
panels[i].add(descriptions[i]);
bigPanel.add(panels[i],i, 0);
}
}
public static void main(String args[]) throws IOException{
new Test();
}
}
I believe your reference to title refers to the last created title at runtime. What you can do to fix this is instead of printing the title, print the labels text. Try putting this inside of your mouseClicked method.
JLabel obj = (JLabel) me.getSource();
System.out.println(obj.getText());
Your mouse click event reference variable from outer class:
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
System.out.println(title); // This `title` is a reference of Test.title variable
}
});
So all of your MouseAdapter references the same title (whose value is replaced by each loop) -> System.out.println all prints the same last title.

Editable JComboBox gives error: <identifier> expected and illegal start of type

I am trying to create and Editable JComboBox to allow the user to type the name of the song to purchase. However when I set tunes.setEditable(true); I get an error... any help will be appreciated!
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JTextArea;
public class JTunes2 extends JFrame implements ItemListener
{
int songNum,songPrice;
int[] songAmount = {2,5,8,1,4,7,12,10,11,3,6,9};
String result;
JComboBox tunes = new JComboBox();
// set as editable
tunes.setEditable(true);
JLabel labelTunes = new JLabel("Song List");
JLabel outputs = new JLabel();
FlowLayout layout = new FlowLayout();
public JTunes2()
{
super("Song Selector");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(layout);
// add song names to combo box and register an item listener.
tunes.addItem("Song1");
tunes.addItem("Song2");
tunes.addItem("Song3");
tunes.addItem("Song4");
tunes.addItem("Song5");
tunes.addItem("Song6");
tunes.addItem("Song7");
tunes.addItem("Song8");
tunes.addItem("Song9");
tunes.addItem("Song10");
tunes.addItem("Song11");
tunes.addItem("Song12");
tunes.addItemListener(this);
panel.add(labelTunes);
panel.add(tunes);
panel.add(outputs);
//add panel to the frame
setContentPane(panel);
}
public void itemStateChanged(ItemEvent e)
{
//create source object
Object source = e.getSource();
//check the type size
if(source == tunes)
{
songNum = tunes.getSelectedIndex();
songPrice = songAmount[songNum];
result = "Total Price $" + songPrice;
//Display result
outputs.setText(result);
}
}
public static void main(String[] args)
{
// create class object
JTunes frame = new JTunes();
frame.setSize(250, 180);
frame.setVisible(true);
}
}
Thank you!
Actually, Java requires that you setup JComponents in the constructor. In order for your code to work, you need to call on setEditable(true) in the constructor, which means that you just need to move tunes.setEditable(true); to the constructor.
Tip: always allocate memory for JComponents in the constructor (you want to draw the components as soon as you create the Jframe). You can have a reference to the JComboBox at the class level.
Here is another version of your code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JTextArea;
public class JTunes2 extends JFrame implements ItemListener
{
int songNum,songPrice;
int[] songAmount = {2,5,8,1,4,7,12,10,11,3,6,9};
String result;
JComboBox tunes;
JLabel labelTunes = new JLabel("Song List");
JLabel outputs = new JLabel();
FlowLayout layout = new FlowLayout();
public JTunes2()
{
super("Song Selector");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(layout);
tunes = new JComboBox();
// set as editable
tunes.setEditable(true);
// add song names to combo box and register an item listener.
tunes.addItem("Song1");
tunes.addItem("Song2");
tunes.addItem("Song3");
tunes.addItem("Song4");
tunes.addItem("Song5");
tunes.addItem("Song6");
tunes.addItem("Song7");
tunes.addItem("Song8");
tunes.addItem("Song9");
tunes.addItem("Song10");
tunes.addItem("Song11");
tunes.addItem("Song12");
tunes.addItemListener(this);
panel.add(labelTunes);
panel.add(tunes);
panel.add(outputs);
//add panel to the frame
setContentPane(panel);
}
public void itemStateChanged(ItemEvent e)
{
//create source object
Object source = e.getSource();
//check the type size
if(source == tunes)
{
songNum = tunes.getSelectedIndex();
songPrice = songAmount[songNum];
result = "Total Price $" + songPrice;
//Display result
outputs.setText(result);
}
}
public static void main(String[] args)
{
// create class object
JTunes2 frame = new JTunes2();
frame.setSize(250, 180);
frame.setVisible(true);
}
}
You added the tunes.setEditable(true) at the class level, instead of at the method level. No statements allowed at the class level!
Here's a fixed version: I renamed JTunes2 to JTunes to fix the compilation errors, and moved the setEditable to the constructor. Also I fixed the indentation - this makes it harder to make this mistake:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JTextArea;
public class JTunes extends JFrame implements ItemListener
{
int songNum,songPrice;
int[] songAmount = {2,5,8,1,4,7,12,10,11,3,6,9};
String result;
JComboBox tunes = new JComboBox();
JLabel labelTunes = new JLabel("Song List");
JLabel outputs = new JLabel();
FlowLayout layout = new FlowLayout();
public JTunes()
{
super("Song Selector");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(layout);
tunes.setEditable(true);
// add song names to combo box and register an item listener.
tunes.addItem("Song1");
tunes.addItem("Song2");
tunes.addItem("Song3");
tunes.addItem("Song4");
tunes.addItem("Song5");
tunes.addItem("Song6");
tunes.addItem("Song7");
tunes.addItem("Song8");
tunes.addItem("Song9");
tunes.addItem("Song10");
tunes.addItem("Song11");
tunes.addItem("Song12");
tunes.addItemListener(this);
panel.add(labelTunes);
panel.add(tunes);
panel.add(outputs);
//add panel to the frame
setContentPane(panel);
}
public void itemStateChanged(ItemEvent e)
{
//create source object
Object source = e.getSource();
//check the type size
if(source == tunes)
{
songNum = tunes.getSelectedIndex();
songPrice = songAmount[songNum];
result = "Total Price $" + songPrice;
//Display result
outputs.setText(result);
}
}
public static void main(String[] args)
{
// create class object
JTunes frame = new JTunes();
frame.setSize(250, 180);
frame.setVisible(true);
}
}

How to reference JFrame

I have a problem which is most likely "simple" however I can't figure it out. I am trying to reference my current JFrame so that I can dispose of it, and create a new one, thus "resetting" the program, however I and having trouble figuring out how to reference the JFrame, I have tried, super, this and getParent(), but none of the seem to work. Thanks for any / all help. ^^
Here is my code:
Main Class, just sets up the Jframe and calls the class that creates everything:
public static void main(String args[]) {
JFrame window = new JFrame();
Director director = new Director(window, args);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLocationRelativeTo(null);
window.pack();
window.setVisible(true);
}
}
Class the creates everything:
import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class Director extends JFrame implements CollisionListener {
private BrickWall wall;
private JLabel gameTitle, gameScore, gameLives;
private JPanel controlPanel;
private JButton reset, quit;
private JRadioButton hard, normal, easy;
private int score = 6, lives = 5;
private ButtonGroup difficulty;
public Director(JFrame window, String[] args) {
window.getContentPane().add(makeGamePanel(), BorderLayout.CENTER);
window.getContentPane().add(gameControlPanel(), BorderLayout.NORTH);
}
public void collisionDetected(CollisionEvent e) {
wall.setBrick(e.getRow(), e.getColumn(), null);
}
private JComponent makeGamePanel() {
wall = new BrickWall();
wall.addCollisionListener(this);
wall.buildWall(3, 6, 1, wall.getColumns(), Color.GRAY);
return wall;
}
// Reset method I'm trying to dispose of the JFrame in.
private void reset() {
JFrame frame = new JFrame();
frame.getContentPane().add(makeGamePanel(), BorderLayout.CENTER);
frame.getContentPane().add(gameControlPanel(), BorderLayout.NORTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private JComponent gameControlPanel() {
// CONTROL PANEL PANEL!
controlPanel = new JPanel();
gameTitle = new JLabel("Brickles");
gameScore = new JLabel("Score:" + " " + score);
gameLives = new JLabel("Lives:" + " " + lives);
reset = new JButton("Reset");
quit = new JButton("Quit");
hard = new JRadioButton("Hard", false);
normal = new JRadioButton("Normal", true);
easy = new JRadioButton("Easy", false);
difficulty = new ButtonGroup();
difficulty.add(hard);
difficulty.add(normal);
difficulty.add(easy);
controlPanel.setLayout(new GridLayout(4, 2));
controlPanel.add(gameTitle);
controlPanel.add(gameScore);
controlPanel.add(hard);
controlPanel.add(gameLives);
controlPanel.add(normal);
controlPanel.add(reset);
controlPanel.add(easy);
controlPanel.add(quit);
// Action Listener, where I'm caling the reset method.
reset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
reset();
}
});
return controlPanel;
}
}
You can refer to the "outer this" from a nested class with the following syntax:
reset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Director.this.reset();
}
});
Yes, you can refer to the outer class by specifying it with the class name as noted in DSquare's good answer (1+ to it), but I urge you not to fling JFrame's at the user as you're program is trying to do. I recommend:
Instead of opening and closing multiple JFrames, use only one JFrame as the main application's window.
If you need helper windows, such as modal windows to get critical information that is absolutely needed, before the program can progress, use modal dialogs such as JDialogs or JOptionPanes.
If you need to swap GUI's, instead of swapping JFrames, swap "views" inside the JFrame via a CardLayout.
Gear your code towards creating these JPanel views and not JFrames as it will make your Swing GUI's much more flexible and portable.

how do I create a public String from a JTextArea?

I'm creating an encryption method that takes input from a JTextArea, and I'm getting an error saying:
'Illegal modifier for parameter input; only final is permitted'
I have gone through many documentation websites and other articles, and I have found nothing. Here is my near-complete code:
Package lake. RAMBIT7;
import java.awt.EventQueue;
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.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import net.miginfocom.swing.MigLayout;
public class RAMBIT7 implements ActionListener {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
RAMBIT7 window = new RAMBIT7();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public RAMBIT7() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setSize(800, 600); //1024x768, 800x600
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("RAMBIT7 Encryption Software 1.0.0");
frame.setResizable(false);
/**
* 'Encrypt' and 'Decrypt' buttons
*/
JButton encrypt = new JButton("Encrypt");
encrypt.addActionListener(this);
JButton decrypt = new JButton("Decrypt");
decrypt.addActionListener(this);
/**
* JMenuBar
*/
JMenuBar bar = new JMenuBar();
JMenu file = new JMenu("File");
JMenu help = new JMenu("Help");
JMenuItem about = new JMenuItem("About");
JMenuItem license = new JMenuItem("License");
JMenuItem close = new JMenuItem("Exit");
file.add(close);
help.add(about);
help.add(license);
bar.add(file);
bar.add(help);
about.addActionListener(this);
license.addActionListener(this);
close.addActionListener(this);
frame.setJMenuBar(bar);
/**
* Text and input related stuff
*/
frame.getContentPane().setLayout(new MigLayout("", "[69px][71px,grow][]", "[23px][35.00][200px][][grow][]"));
frame.getContentPane().add(encrypt, "cell 0 0,alignx left,aligny top");
frame.getContentPane().add(decrypt, "cell 2 0,alignx right,aligny top");
JLabel lblCopyTextIn = new JLabel("Copy Text in here.");//JLabel
frame.getContentPane().add(lblCopyTextIn, "cell 1 1");
JScrollPane scrollPane = new JScrollPane();
frame.getContentPane().add(scrollPane, "cell 0 2 3 1,grow");
JTextArea textArea = new JTextArea();//JTextArea
scrollPane.setViewportView(textArea);
textArea.setLineWrap(true);
JLabel lblOutputTextIn = new JLabel("Output text in RAMBIT7 encryption");//JLabel
frame.getContentPane().add(lblOutputTextIn, "cell 1 3");
JScrollPane scrollPane_1 = new JScrollPane();
frame.getContentPane().add(scrollPane_1, "cell 0 4 3 1,grow");
JTextArea textArea_1 = new JTextArea();//JTextArea_1
scrollPane_1.setViewportView(textArea_1);
textArea_1.setEditable(false);
textArea_1.setLineWrap(true);
JLabel lblRambitEncryptionMethod = new JLabel("RAMBIT7 Encryption Method"); //JLabel
frame.getContentPane().add(lblRambitEncryptionMethod, "cell 1 5");
public String input_0 = textArea.getText();//Error here
}
#Override
public void actionPerformed(ActionEvent e) {
String a = e.getActionCommand();
if(a.equalsIgnoreCase("encrypt")) {
System.out.println("Begin RAMBIT7 encryption.");
encryptRAMBIT7(input);
} else if(a.equalsIgnoreCase("decrypt")) {
System.out.println("Begin RAMBIT7 decryption.");
decryptRAMBIT7(input);
} else if(a.equalsIgnoreCase("about")) {
System.out.println("Opening Program Specs...");
JOptionPane.showMessageDialog(frame, "RAMBIT7 v1.0.0");
System.out.println("Program Specs Closed.");
} else if(a.equalsIgnoreCase("license")) {
System.out.println("Opening License...");
JOptionPane.showMessageDialog(frame, "You may not sell this program or say that any part of the code is yours.");
System.out.println("License closed.");
} else if(a.equalsIgnoreCase("exit")) {
System.out.println("Why, oh WHY CRUEL WORLD does that person have to close me?! I'm\na living thing too! Or maybe I'm an emotionless pig! NOOOOOOOO!");
System.exit(3);
}
}
}
You need to re-think your structure a bit:
Even if you could get the String out of the JTextArea on creation time, it would not help you one bit. When the JTextArea changes its display text, that String will not change since Strings are invariants.
Likewise a String field would not help, not unless it was dynamically bound to the JTextArea via a DocumentListener or something similar.
Instead make the JTextArea a private field and extract its String when needed.
If other classes need the text, then create a public method public String getTextAreaText() and return the text held by the JTextArea in that method.
public class RAMBIT7 implements ActionListener {
private JFrame frame;
private JTextArea textarea = new JTextArea();
// ....
private void initialize() {
// .....
// JTextArea textArea = new JTextArea();//JTextArea
scrollPane.setViewportView(textArea);
textArea.setLineWrap(true);
and elsewhere:
if(a.equalsIgnoreCase("encrypt")) {
System.out.println("Begin RAMBIT7 encryption.");
encryptRAMBIT7(textarea.getText());
You just can't use the public keyword inside a method. Visibility modifiers are used to determine what members of each object can be accessed from outside, by other objects or classes. Things you declare inside of a method are not members of a class, but rather things that only exist in that method, so visibility modifiers make no sense there.
public String input_0 = textArea.getText();
Any variable declared inside a function is local to that function. Outside world don't know about that variable but the function itself. hence, access modifier public, private or protected are not applicable to local instance variable, such as input_0 here which is local to initialize(). Again, this code, is inside initialize() function, which is responsible for initializing your GUI component, creating them and adding them to the container, user input is yet to happen, so reading the text content of textArea is meaning less.

change jlabel with method

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");
}
}

Categories

Resources