I have a program that does several thing and displays different JFrames after several actions. When I launch the first JFrame from the main, it all goes ok, but When I launch it from another class different from the main class, it doesn't shows up.
What is the point? What am I doing wrong?
Here's some code:
This is called from the main:
SwingUtilities.invokeLater(new Runnable() {
PdfFileUtils pfu = new PdfFileUtils(path);
public void run() {
try {
PdfToImg.setup(pfu, null);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
And it works.
And this is called from another class that is used after some operations:
pfu.setPath(SIGNED);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
PdfToImg.setup(pfu, data);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
Sometimes (every 4 or 5 executions), it launches interrupted exception.
I also tried launching the second frame in this way:
pfu.setPath(SIGNED);
try {
PdfToImg.setup(pfu, data);
} catch (IOException ex) {
ex.printStackTrace();
}
But it shows up for a second and than disappears.
EDIT :
This is the setup() method:
public static void setup(PdfFileUtils pfu, BiometricData data) throws IOException {
// load a pdf from a byte buffer
File file = new File(pfu.getPath());
RandomAccessFile raf = new RandomAccessFile(file, "r");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0,
channel.size());
PDFFile pdffile = new PDFFile(buf);
int numPgs = pdffile.getNumPages();
ImageIcon[] images = new ImageIcon[numPgs];
for (int i = 0; i < numPgs; i++) {
// draw the first page to an image
PDFPage page = pdffile.getPage(i + 1);
// get the width and height for the doc at the default zoom
Rectangle rect = new Rectangle(0, 0, (int) page.getBBox()
.getWidth(), (int) page.getBBox().getHeight());
// generate the image
Image img = page.getImage(rect.width, rect.height, rect, null,
true, true);
pfu.setWidth(rect.width);
pfu.setHeight(rect.height);
// save it on an array
images[i] = new ImageIcon(img);
}
if(data != null){
SignedFileDisplay fileDisplay = new SignedFileDisplay(pfu, data);
fileDisplay.DisplayAndSelect(images);
} else{
SignPosition signPos = new SignPosition(pfu);
signPos.DisplayAndSelect(images);
}
raf.close();
}
The JFrames are launched by SignedFileDisplay(pfu, data) and by SignPosition(pfu). They work both if launched by the main, and no one the second time.
The constructors are:
public SignPosition(PdfFileUtils pfutils) {
pfu = pfutils;
// scale dimensions
width = (int) (scale * pfu.getWidth());
height = (int) (scale * pfu.getHeight());
// sets the frame appearance
sp.setSize(width + 8, height + 68);
sp.setVisible(true);
sp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sp.setLocationRelativeTo(null);
// Add the image gallery panel
add(imageGallery, BorderLayout.PAGE_START);
// creates the JButtons objects for each button
JButton FIRST = new JButton("|<<<");
JButton PREVIOUS = new JButton("< Prev");
JButton OK = new JButton("Ok");
JButton NEXT = new JButton("Next >");
JButton LAST = new JButton(">>>|");
// adds the buttons to the button panel
JPanel buttons = new JPanel();
buttons.setLayout(new GridLayout(1, 4));
buttons.add(FIRST);
buttons.add(PREVIOUS);
buttons.add(OK);
buttons.add(NEXT);
buttons.add(LAST);
// add buttons on the bottom of the frame
add(buttons, BorderLayout.SOUTH);
// register listener
FirstButtonListener FirstButton = new FirstButtonListener();
PreviousButtonListener PreviousButton = new PreviousButtonListener();
OkButtonListener OkButton = new OkButtonListener();
NextButtonListener NextButton = new NextButtonListener();
LastButtonListener LastButton = new LastButtonListener();
// add listeners to corresponding componenets
FIRST.addActionListener(FirstButton);
PREVIOUS.addActionListener(PreviousButton);
OK.addActionListener(OkButton);
NEXT.addActionListener(NextButton);
LAST.addActionListener(LastButton);
}
and
public SignedFileDisplay(PdfFileUtils pfutils, BiometricData bd) {
data = bd;
pfu = pfutils;
// scale dimensions
width = (int) (scale * pfu.getWidth());
height = (int) (scale * pfu.getHeight());
// sets the frame appearance
sfd.setSize(width + 8, height + 68);
sfd.setVisible(true);
sfd.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sfd.setLocationRelativeTo(null);
// Add the image gallery panel
add(imageGallery, BorderLayout.PAGE_START);
// creates the JButtons objects for each button
JButton FIRST = new JButton("|<<<");
JButton PREVIOUS = new JButton("< Prev");
JButton GRAPH = new JButton("Gaph display");
JButton NEXT = new JButton("Next >");
JButton LAST = new JButton(">>>|");
// adds the buttons to the button panel
JPanel buttons = new JPanel();
buttons.setLayout(new GridLayout(1, 4));
buttons.add(FIRST);
buttons.add(PREVIOUS);
buttons.add(GRAPH);
buttons.add(NEXT);
buttons.add(LAST);
// add buttons on the bottom of the frame
add(buttons, BorderLayout.SOUTH);
// register listener
FirstButtonListener FirstButton = new FirstButtonListener();
PreviousButtonListener PreviousButton = new PreviousButtonListener();
GraphButtonListener GraphButton = new GraphButtonListener();
NextButtonListener NextButton = new NextButtonListener();
LastButtonListener LastButton = new LastButtonListener();
// add listeners to corresponding componenets
FIRST.addActionListener(FirstButton);
PREVIOUS.addActionListener(PreviousButton);
GRAPH.addActionListener(GraphButton);
NEXT.addActionListener(NextButton);
LAST.addActionListener(LastButton);
}
Obviously the both extends JFRAME
Are you typing something into that frame? Do you have any shortcuts defined per application?
I had the same problem with my application frame dissapearing from time to time.
In my case, i had some key shortcuts defined per application and one of them was Shift + C (closing the application - bad choice, i know).. so whenever i wanted to type upper case for "c" into a field, i was actually calling the shortcut to close window.
Have many frames is not a good practice.
You should try to use the JDialog instead of JFrame.
This way you can pass the Main Frame to the others dialogs and let them be modal
Like this:
Opening from main
public class Test extends JDialog {
public Test(Frame frame, String dialogName) {
super(frame, dialogName, true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setBounds(x, y, w, h);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new Test(null, "Test Dialog");
}
}
Opening from another frame
public void yourMethod() {
new Test(yourMainFrame, dialogName);
}
Related
I am writing the code of showing images in Jframe in certain directory. The Jframe will show image one at a time.
My code showing that jframe's size changing but the image doesn't change.
I put revalidate and paint but the images are not refreshed.
Here is updateFrame function which has logic of updating.
private void updateFrame(JFrame f, String billBoardImageFileLocation, int imageNumber) throws ClassNotFoundException, IOException {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); //this is your screen size
File folder = new File(billBoardImageFileLocation);
String[] extensions = new String[]{"jpeg", "jpg"};
List<File> imageFiles = (List<File>) FileUtils.listFiles(folder, extensions, false);
ImageIcon image = new ImageIcon(ImageIO.read(imageFiles.get(imageNumber % imageFiles.size()))); //imports the image
if (isDebug.equals("Y")) {
System.out.println("Files:" + imageFiles.get(imageNumber % imageFiles.size()).getAbsolutePath());
}
JLabel lbl = new JLabel(image); //puts the image into a jlabel\
f.getContentPane().add(lbl); //puts label inside the jframe
f.setSize(image.getIconWidth(), image.getIconHeight()); //gets h and w of image and sets jframe to the size
f.getContentPane().revalidate();
int x = (screenSize.width - f.getSize().width) / 2; //These two lines are the dimensions
int y = (screenSize.height - f.getSize().height) / 2; //of the center of the screen
f.setLocation(x, y); //sets the location of the jframe
f.setVisible(true); //makes the jframe visible
f.revalidate(); // **** added ****
f.repaint();
f.getContentPane().revalidate();
f.getContentPane().repaint();
}
This is how I invoke the updateFrame function.
try
{
pProcess = pb.start();
if (showBillBoard.toUpperCase().equals("Y")) {
ProcMon proMon = new ProcMon(pProcess);
Thread t = new Thread(proMon);
t.start();
JFrame f = new JFrame(); //creates jframe f
if (isDebug.equals("Y")) {
System.out.println("Starting Thread");
}
int imageNumber = 0;
while (!proMon.isComplete()) {
updateFrame(f, billBoardImageFileLocation, imageNumber);
Thread.sleep(Integer.parseInt(billBoardImageUpdateInterval)*1000);
if (isDebug.equals("Y")) {
System.out.println("Updating Framework");
}
imageNumber++;
}
f.dispose();
}
}
JLabel lbl = new JLabel(image);
Don't create a new label, just update the icon of the existing label:
label.setIcon( image );
So change the method parameters to pass in the label as well as the frame.
That's all you need to do.
You're doing long-running code on the Swing event thread, freezing it. Solution: don't. Swap your images using a Swing Timer, as this will allow repeated actions that don't step on the Swing event thread. Also never call Thread.sleep on this thread. For more on the EDT, the Swing event dispatch thread, please read Concurrency in Swing.
I created a button that is in the main page which when a user clicks on it، it changes the panal ( the main idea is that it changes the background and all whats on the panel and adds new stuff to it ) however i failed!, i also failed in adjusting the location of the button although i tried button.setBounse(..)
anyhow can someone help me in those two things?
public class mainClass {
private static JButton start;
static BackgroundPanel bp = null;
static JFrame mainf = null;
public static void main(String[] args) throws IOException {
mainf = new JFrame ("سين جيم");
// background
BufferedImage mFrame = ImageIO.read(new File("B1.png"));
bp = new BackgroundPanel(mFrame);
mainf.add(bp);
bp.setLayout(new GridBagLayout());
// Hi string
JLabel hi = new JLabel ("أهلا وسهلا");
Font fs = hi.getFont();
hi.setFont(fs.deriveFont(50f));
bp.add(hi);
// button
JPanel another = new JPanel();
start = new JButton ( " لنبدأ");
bp.add(start);
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
bp.removeAll();
BufferedImage mFrame2= null;
try {
mFrame2 = ImageIO.read(new File("B2.png"));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
bp = new BackgroundPanel(mFrame2);
bp.setLayout(new GridBagLayout());
JLabel hi1= new JLabel ("worked");
bp.add(hi1);
}
} );
// end of frame
mainf.pack();
mainf.setVisible(true);
}
}
Well, to change your main panel you don't have to create a new Frame object and set it's main panel. E.g., you could write a setter for bp and invoke this method in your action listener method. If your panel has a different size, you can easily change the frame's size...
I have MDI project. I add the customer JPanel in the JInternalFrame. My customer JPanel has a public method to change some component background color. When the button on the JFrame is clicked, I want it to change the label or text on my customer JPanel for all InternalFrame. How can I call the method? Thanks in advance
The following code is the action for the button on JFrame
private void categoryAction(ActionEvent e){
try{
JButton b=(JButton)e.getSource();
Color c=b.getBackground();
JInternalFrame[] allframes = desktop.getAllFrames();
int count = allframes.length;
for (int i=0; i<allframes.length-1; i++){
//call the method on the PDFJPanel
}
}
catch(Exception err){
Utility.DisplayErrorMsg(err.toString());
}
The following code is add the internal frame into the desktop
private void AddNote(File file){
JInternalFrame internalFrame = new JInternalFrame("PDFAnnotation"
+ file.getName(), true, true, true, true);
internalFrame.setBounds(0, 0, 600, 100);
desktop.add(internalFrame);
PDFJPanel p=new PDFJPanel(file);
internalFrame.add(p, BorderLayout.CENTER);
internalFrame.setVisible(true);
try {
internalFrame.setSelected(true);
}
catch (java.beans.PropertyVetoException e) {}
this.add(desktop, BorderLayout.CENTER);
//resize the internal frame as full screen
Dimension size = desktop.getSize();
int w = size.width ;
int h = size.height ;
int x=0;
int y=0;
desktop.getDesktopManager().resizeFrame(internalFrame, x, y, w, h);
}
There is the method on my customer JPanel
Public void setDefaultColor(Color c){
//change the label and textbox color
}
You can utilize JDesktopPane.getSelectedFrame that returns currently active frame. You can retrieve PDFJPanel from the layout manager, ie using BorderLayout.getLayoutComponent(). Or easier and cleaner, you can extend JInternalFrame, ie:
class PDFFrame extends JInternalFrame {
private PDFJPanel panel;
public PDFFrame(File file) {
panel = new PDFJPanel(file);
add(panel, BorderLayout.CENTER);
}
public void setDefaultColor(Color c){
panel.setDefaultColor();
}
}
Then, access it:
JDesktopPane desktop = ...;
PDFFrame frame = (PDFFrame) desktop.getSelectedFrame();
frame.setDefaultColor(Color.BLUE);
So I am working on a GUI project for my class and I am a bit stuck. My problem has to do with my GUI aspect so I guess you could ignore the other methods having to do with the sorting. As of now, my main concern is just getting the GUI working. However, I keep running into an error, a null pointer exception to be exact:
Java.lang.NullPointerException
at SortDriver$SortCanvas.paint(SortDriver.java:253)
at SortDriver.init(SortDriver.java:197)
at sun.applet.AppletPanel.run(AppletPanel.java:436)
at java.lang.Thread.run(Thread.java:679)
After reading though my code, I think I narrowed it down to the my SortCanvas class. I never used it before but it was part of the stub my professor gave to us. That is to say that it works correctly and displays the image correctly but it looks like my implementation is incorrect however. Could someone help me figure out how to implement my SortCanvas "picture" correctly please? I read over the Java Docs for Canvas and I still don't understand what I am doing wrong. Here is my code:
import java.awt.*;
import java.applet.Applet;
import javax.swing.*;
import java.awt.event.*;
public class SortDriver extends Applet {
private int array[]; // array to be sorted
private int limit = 1000; // size of array to be sorted - you may have to make
// this bigger for faster sorts
private int largestNum; // need to know for color scaling purposes in paint()
// flag to tell paint() whether to paint a single location or the whole array
private enum PaintType {ALL, SINGLE};
private PaintType doPaint = PaintType.ALL;
private int index = -1; // index of single array location to be painted
//this listener object responds to button events
private ButtonActionListener buttonListener;
//button to start the sort
private JButton sortButton;
//basic window frame
private JFrame mainFrame;
//layouts
private BorderLayout initialLayout;
private FlowLayout northLayout;
private BorderLayout centerLayout;
private BorderLayout southLayout;
//basic panel for window frame
private JPanel initialPanel;
//panels for window layout
private JPanel northPanel;
private JPanel centerPanel;
private JPanel southPanel;
//panels for radio buttons
private JPanel radioOrderPanel;
private JPanel radioSortPanel;
private JPanel radioColorPanel;
//north panel header labels
private JLabel topTitleLabel;
private JLabel bottomTitleLabel;
private JLabel arraySizeLabel;
//radio buttons for list order (radioOrderButton)
//random set, ordered set, reverse set
private JRadioButton rOB1, rOB2, rOB3;
//radio buttons for sort type (radioSortButton)
//bubblesort, insertionsort, mergesort, quicksort
private JRadioButton rSB1, rSB2, rSB3, rSB4;
//radio buttons for color choice (radioColorButton)
//green, red, white, blue
private JRadioButton rCB1, rCB2, rCB3, rCB4;
//radio button groups for each radio panel
private ButtonGroup orderGroup, sortGroup, colorGroup;
//text field for size of the array
private JTextField arraySizeTextField;
// the picture of the sort will appear on this canvas
private SortCanvas picture;
private final int pictureWidth = 500; // size of the sort bar 1001
private final int pictureHeight = 50;
public void init() {
buttonListener = new ButtonActionListener();
array = new int[limit];
// load the array
largestNum = array[0] = (int) (Math.random()*1000000.0);
for (int i=1; i<limit; i++) {
array[i] = (int) (Math.random()*1000000.0);
// also keep track of the largest so that we can scale by it in paint()
if (array[i] > largestNum) largestNum = array[i];
}
//set up the main frame
mainFrame = new JFrame();
initialPanel = (JPanel) mainFrame.getContentPane();
initialLayout = new BorderLayout();
mainFrame.setResizable(false);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setSize(650, 750);
initialPanel.setLayout(initialLayout);
//set up north panel
northPanel = new JPanel();
northLayout = new FlowLayout();
topTitleLabel = new JLabel("SortIt!");
bottomTitleLabel = new JLabel("A program by Mike Sevilla");
northPanel.setLayout(northLayout);
northPanel.add(topTitleLabel, BorderLayout.NORTH);
northPanel.add(bottomTitleLabel, BorderLayout.NORTH);
initialPanel.add(northPanel, BorderLayout.NORTH);
//set up center panel
centerPanel = new JPanel();
centerLayout = new BorderLayout();
centerPanel.setLayout(centerLayout);
//place array size label
arraySizeLabel = new JLabel("Size:");
//place array size text field w/ space for 5 chars
arraySizeTextField = new JTextField("", 5);
//place sort button
sortButton = new JButton("Sort it!");
// the listener is triggered when the button is clicked
sortButton.addActionListener(buttonListener);
centerPanel.setLayout(centerLayout);
//place sort bar on top of center layout
picture = new SortCanvas();
centerPanel.add(picture, BorderLayout.CENTER);
centerPanel.add(arraySizeLabel, BorderLayout.CENTER);
centerPanel.add(arraySizeTextField, BorderLayout.CENTER);
centerPanel.add(sortButton, BorderLayout.CENTER);
initialPanel.add(centerPanel, BorderLayout.CENTER);
//set up south panel
southPanel = new JPanel();
southLayout = new BorderLayout();
southPanel.setLayout(southLayout);
//set radio buttons and format layouts
radioOrderPanel = new JPanel();
radioOrderPanel.setLayout(new BoxLayout(radioOrderPanel, BoxLayout.Y_AXIS));
radioSortPanel = new JPanel();
radioSortPanel.setLayout(new BoxLayout(radioSortPanel, BoxLayout.Y_AXIS));
radioColorPanel = new JPanel();
radioColorPanel.setLayout(new BoxLayout(radioColorPanel, BoxLayout.Y_AXIS));
//define radio buttons
rOB1 = new JRadioButton("Random Order", true);
rOB1.addActionListener(buttonListener);
radioOrderPanel.add(rOB1);
rOB2 = new JRadioButton("In Order", false);
rOB2.addActionListener(buttonListener);
radioOrderPanel.add(rOB2);
rOB3 = new JRadioButton("In Reverse", false);
rOB3.addActionListener(buttonListener);
radioOrderPanel.add(rOB3);
rSB1 = new JRadioButton("Bubble Sort", true);
rSB1.addActionListener(buttonListener);
radioSortPanel.add(rSB1);
rSB2 = new JRadioButton("Insertion Sort", false);
rSB2.addActionListener(buttonListener);
radioSortPanel.add(rSB2);
rSB3 = new JRadioButton("Merge Sort", false);
rSB3.addActionListener(buttonListener);
radioSortPanel.add(rSB3);
rSB4 = new JRadioButton("Quick Sort", false);
rSB4.addActionListener(buttonListener);
radioSortPanel.add(rSB4);
rCB1 = new JRadioButton("Green", true);
rCB1.addActionListener(buttonListener);
radioColorPanel.add(rCB1);
rCB2 = new JRadioButton("Red", false);
rCB2.addActionListener(buttonListener);
radioColorPanel.add(rCB2);
rCB3 = new JRadioButton("White", false);
rCB3.addActionListener(buttonListener);
radioColorPanel.add(rCB3);
rCB4 = new JRadioButton("Blue", false);
rCB4.addActionListener(buttonListener);
radioColorPanel.add(rCB4);
//add radio buttons to a button group
orderGroup = new ButtonGroup();
orderGroup.add(rOB1);
orderGroup.add(rOB2);
orderGroup.add(rOB3);
sortGroup = new ButtonGroup();
sortGroup.add(rSB1);
sortGroup.add(rSB2);
sortGroup.add(rSB3);
sortGroup.add(rSB4);
colorGroup = new ButtonGroup();
colorGroup.add(rCB1);
colorGroup.add(rCB2);
colorGroup.add(rCB3);
colorGroup.add(rCB4);
initialPanel.add(southPanel, BorderLayout.NORTH);
picture.paint(picture.getGraphics());
mainFrame.setVisible(true);
}
// this object is triggered whenever a button is clicked
private class ButtonActionListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
// find out which button was clicked
Object source = event.getSource();
// start sort button was clicked
if (source == sortButton) {
// call the sort
doBubblesort();
}
// called when user hits return in text field
if (source == arraySizeTextField) {
int size = Integer.parseInt(arraySizeTextField.getText());
}
}
}
private void doBubblesort() {
int temp;
// this is just bubblesort
for (int i=0; i<limit-1; i++) {
for (int j=0; j<limit-1-i; j++) {
if (array[j]>array[j+1]) {
temp = array[j]; array[j] = array[j+1]; array[j+1] = temp;
// redraw only locations j and j+1
doPaint = PaintType.SINGLE; // try changing this to ALL and see what happens
index = j;
picture.paint(picture.getGraphics());
index = j+1;
picture.paint(picture.getGraphics());
}
}
}
}
class SortCanvas extends Canvas {
// this class paints the sort bar
SortCanvas() {
setSize(pictureWidth, pictureHeight);
setBackground(Color.white);
}
public void paint(Graphics g) {
if (doPaint == PaintType.ALL) {
// paint whole array - this takes time so it shouldn't be done too frequently
setBackground(Color.white);
g.setColor(Color.white);
g.fillRect(0, 0, pictureWidth, pictureHeight);
for (int i=0; i<limit; i++) {
// the larger the number, the brighter green it is
// green is between 0.0 and 1.0
// divide by the largest number to get a value between 0 and 1
float green = (float)(array[i]/(float)largestNum);
// clamp if necessary - it shouldn't be
if (green<0f) green = 0f;
if (green>1f) green = 1f;
g.setColor(new Color(0.0f, green, 0.0f));
// array location 0 is painted at left;
// array location limit-1 is painted to right
//this is a single vertical line in the bar
g.drawLine((int)(i*pictureWidth/limit), 0,
(int)(i*pictureWidth/limit), pictureHeight);
}
}
else {
// just paint one location on the bar
float green = (float)(array[index]/(float)largestNum);
if (green<0f) green = 0f;
if (green>1f) green = 1f;
g.setColor(new Color(0.0f, green, 0.0f));
g.drawLine((int)(index*pictureWidth/limit), 0,
(int)(index*pictureWidth/limit), pictureHeight);
}
}
}
}
This is not required;
picture.paint(picture.getGraphics());
getGraphics will return null if the component has not yet being painted itself. You should avoid using this method, it is simply a snap shot of the current components graphical state (which in your case is nothing)
You don't control the paint process, that's down to the repaint manager. You can request updates via the repaint methods. Have a read through Painting in AWT and Swing
You should avoid mixing heavy weight (Canvas) & light weight components (JFrame) together, where possible, you should stick with Swing components
Calling paint() directly can lead to unexpected behavior as you are see from this, use repaint() instead:
picture.repaint();
I'm trying to create a board for a game, i first made a frame then if the user //enters the rows and columns as numbers and pushes the start button, it should remove all //whats on frame and add a panel with a grid layout having buttons everywhere
Here is the code ( Problem is the frame gets cleared and nothing appears)
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Frame extends JFrame implements ActionListener{
private static final long serialVersionUID = 1L;
JButton newButton;
JButton Start;
JTextArea row;
JTextArea col;
JLabel background;
JLabel rows;
JLabel columns;
JLabel Error;
JPanel myPanel;
JCheckBox box;
public Frame()
{
//adding frame
setTitle("DVONN Game");
setSize(1000, 700);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(null);
//making start button
Start = new JButton(new ImageIcon("Start"));
Start.setBounds(500, 30, 300, 300);
Start.setOpaque(true);
Start.addActionListener(this);
//make background
background = new JLabel();
background.setBounds(0, -300, 2000, 1500);
background.setIcon(Color.BLUE));
rows = new JLabel("Enter the rows");
columns = new JLabel("Enter the columns");
rows.setForeground(Color.WHITE);
columns.setForeground(Color.WHITE);
rows.setBounds(10,10,100,30);
columns.setBounds(10,45,105,30);
row = new JTextArea();
col = new JTextArea();
row.setBounds(120,10,100,30);
col.setBounds(120,45,100,30);
Error = new JLabel("Enter numbers plz!");
Error.setBounds(10, 100, 400, 30);
Error.setForeground(Color.RED);
Error.setVisible(true);
box = new JCheckBox("Enable Random Filling");
box.setBounds(10, 200, 150, 20);
box.setVisible(true);
myPanel = new JPanel();
myPanel.setBounds(30, 30, 700, 500);
myPanel.setVisible(true);
newButton = new JButton();
newButton.setOpaque(true);
getContentPane().add(box);
getContentPane().add(rows);
getContentPane().add(columns);
getContentPane().add(row);
getContentPane().add(col);
getContentPane().add(Start);
getContentPane().add(background);
this.validate();
this.repaint();
}
public static void main(String[]args)
{
new Frame();
}
//adding actions for start button
public void actionPerformed(ActionEvent e) {
boolean flag = true;
String r1 = row.getText();
String c1 = col.getText();
int x = 0,y = 0;
try{
x = Integer.parseInt(r1);
y = Integer.parseInt(c1);
} catch(NumberFormatException l) {
flag = false;
}
int size = x * y;
if (flag == true) {
this.getContentPane().removeAll();
this.validate();
this.repaint();
myPanel.setLayout(new GridLayout(x, y));
while(size != 0)
{
myPanel.add(newButton);
size --;
}
this.getContentPane().add(myPanel);
} else {
this.getContentPane().add(Error);
}
}
}
There are several issues with this code
Is it really needed to post that much code. A simple UI with one button to press, and then another component which should appear would be sufficient for an SSCCE
The use of null layout's. Please learn to use LayoutManagers
Each Swing component can only be contained once in the hierarchy. So this loop is useless since you add the same component over and over again (not to mention that a negative size would result in an endless loop)
while(size != 0){
myPanel.add(newButton);
size --;
}
Have you tried debugging to see whether size is actually >0. Since you silently ignore ParseExceptions you might end up with a size of 0 which will clean the content pane and add nothing
Then do as goldilocks suggests and call validate after adding the components. See the javadoc of the Container#add method
This method changes layout-related information, and therefore, invalidates the component hierarchy. If the container has already been displayed, the hierarchy must be validated thereafter in order to display the added component.
Call validate() and repaint() after the new elements have been added instead of after the old ones have been removed.
You don't need to be calling setVisible() on individual components, call it after pack() on the Frame itself, and you shouldn't use validate() and repaint() in the constructor. Ie, replace those with:
pack();
setVisible(true);
or you can do that on the object after the constructor is called.
Try to replace
public static void main(String[]args)
{
new Frame();
}
by
public static void main(String[]args)
{
new Frame().setVisible(true);
}
Remove the call to this.setVisible in the constructor and make this your main method.
public static void main(String[] args) {
final Frame fr = new Frame();
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
fr.setVisible(true);
}
});
}
This will make sure that the frame elements will be in place before it becomes visible.