Second JFrame doesn't show from first JFrame - java

This is a simple JFrameapplication. It basically creates a new Frame on basis of the user choice. The first frame starts but the new one doesn't show up! It show the errors-
ie1 cannot be resolved & ie2 cannot be resolved. I want to see the new Frame.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Test2 {
public static void main(String[] args) {
JFrame jf = new JFrame("Java test");
Container c = jf.getContentPane();
jf.setBounds(450, 180, 450, 450);
jf.setVisible(true);
jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);
JPanel jp = new JPanel();
c.add(jp);
JLabel jl = new JLabel("This is a text in a label",SwingConstants.CENTER);
jp.add(jl);
JComboBox jcb1 = new JComboBox();
jp.add(jcb1);
jcb1.addItemListener(new ItemListener() {
public void itemStateChanged(final ItemEvent ie1) {
ie1.getItem();
}
});
jcb1.addItem(" Select the Size ");
jcb1.addItem("100 x 100");
jcb1.addItem("200 x 200");
jcb1.addItem("300 x 300");
jcb1.addItem("400 x 400");
jcb1.addItem("500 x 500");
jcb1.addItem("600 x 600");
JComboBox jcb2 = new JComboBox();
jp.add(jcb2);
jcb2.addItemListener(new ItemListener() {
public void itemStateChanged(final ItemEvent ie2) {
ie2.getItem();
}
});
jcb2.addItem(" Select the Colour ");
jcb2.addItem("Blue");
jcb2.addItem("Red");
jcb2.addItem("Black");
jcb2.addItem("White");
jcb2.addItem("Yellow");
jcb2.addItem("Green");
JButton jb = new JButton("Create a new Frame");
jp.add(jb);
jb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
final JFrame jf1 = new JFrame("New Frame");
Container c = jf1.getContentPane();
jf1.setVisible(true);
jf1.setDefaultCloseOperation(jf1.EXIT_ON_CLOSE);
// The Size of the frame
if (ie1.getItem().equals(" Select the Size ")) {
JOptionPane.showMessageDialog(null, "Please select the size of the Frame");
}
if (ie1.getItem().equals("100 x 100"))
;
{
jf1.setBounds(450, 180, 100, 100);
}
if (ie1.getItem().equals("200 x 200"))
;
{
jf1.setBounds(450, 180, 200, 200);
}
if (ie1.getItem().equals("300 x 300"))
;
{
jf1.setBounds(450, 180, 300, 300);
}
if (ie1.getItem().equals("400 x 400"))
;
{
jf1.setBounds(450, 180, 400, 400);
}
if (ie1.getItem().equals("500 x 500"))
;
{
jf1.setBounds(450, 180, 500, 500);
}
if (ie1.getItem().equals("600 x 600"))
;
{
jf1.setBounds(450, 180, 600, 600);
}
// The size of the Frame ends
// The colour of the frame
if (ie2.getItem().equals(" Select the Colour ")) {
JOptionPane.showMessageDialog(null, "Please select the colour of the Frame");
}
final JPanel jp1 = new JPanel();
c.add(jp1);
if (ie2.getItem().equals("Blue")) {
jp1.setBackground(Color.blue);
}
if (ie2.getItem().equals("Red")) {
jp1.setBackground(Color.red);
}
if (ie2.getItem().equals("Black")) {
jp1.setBackground(Color.black);
}
if (ie2.getItem().equals("White")) {
jp1.setBackground(Color.white);
}
if (ie2.getItem().equals("Yellow")) {
jp1.setBackground(Color.yellow);
}
if (ie2.getItem().equals("Green")) {
jp1.setBackground(Color.green);
}
// the colour of the frame ends
}
});
}
}

You are not instantiating, nor initializing the ie1 and ie2 variables anywhere. I can see these represent ItemEvent references, but their scope is limited to the ItemListener 'changed' method.
If you are using Eclipse, it should provide you with a quick fix. But if I were you, I would start reading on Java for Beginners first, and after that move onto the AWT/Swing and SWT/JFace stuff.
Try starting with more basic stuff. It occurs to me that the code above is a bit overwhelming for you. Good luck lil programmer.

Several things:
You don't need ItemListeners to get the selected value of the combo boxes, instead just do
Object ie1 = jcb1.getSelectedItem();
Object ie2 = jcb2.getSelectedItem();
right above
if(ie1.equals(" Select the Size "))
{
JOptionPane.showMessageDialog(null,"Please select the size of the Frame");
}
And since you're using an anonymous inner class, you'll need to make sure jcb1 and jcb2 are declared final, like so:
final JComboBox jcb1 = new JComboBox();
Also, change ie1.getItem().equals(...) to just ie1.equals(...), and do the same for ie2.
On another note, don't put semicolons after if statements.
Right:
if(ie1.equals("100 x 100"))
{
...
}
Wrong:
if(ie1.equals("100 x 100"));
{ //^
...
}
So remove the semicolons that you have after those if statements.
With all that said, I would definitely recommend going with GGrec's advice, and start reading some Java tutorials.

Related

I'm adding a JLabel (pop_up) to a JFrame, but it doesn't show until the frame is resized. How do I fix this?

I'm adding a JLabel (pop_up) to a JFrame, but it doesn't show until the frame is resized.The program is to get users inputs for different search functions. The bit I'm struggling on is the below, as the pop_up JLabel isn't showing.
enter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(table_search.getText().equals("Table") || column.getText().equals("Column") || search.getText().equals("Search")) {
JLabel pop_up = new JLabel("You haven't changed one or more of the text fields.");
pop_up.setBounds(240, 184, 350, 40);
frame.add(pop_up);
}
else {
String txtTable = table_search.getText();
String txtColumn = column.getText();
String txtSearch = search.getText();
table_search.setText("");
column.setText("");
search.setText("");
}
}
});

Trying to display images in multiple JPanels

I'm creating a program that features a grid of 12 JPanels. When the "add image" button is pressed, an image appears in the first JPanel in the grid and a counter is incremented by one. From then onwards, every time the "add image" is clicked again, an image would be added to the next JPanel. For some reason, the button only adds an image to the first JPanel and then stops working. Here's the code I've got so far.
public class ImageGrid extends JFrame {
static JPanel[] imageSpaces = new JPanel[12];
int imageCounter = 0;
ImageGrid() {
this.setTitle("Image Grid");
setSize(750, 750);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel p3 = new JPanel();
p3.setLayout(new GridLayout(3, 4, 10, 5));
p3.setBackground(Color.WHITE);
p3.setOpaque(true);
p3.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
for (int j = 0; j < imageSpaces.length; j++) {
imageSpaces[j] = setImageSpace();
p3.add(imageSpaces[j]);
}
MyButtonPanel p1 = new MyButtonPanel();
add(p1, BorderLayout.SOUTH);
add(p3, BorderLayout.CENTER);
}
public JPanel setImageSpace() {
JPanel test;
test = new JPanel();
test.setOpaque(true);
test.setPreferredSize(new Dimension(100, 100));
return test;
}
class MyButtonPanel extends JPanel implements ActionListener {
final JButton addImage = new JButton("Add Image");
ImageIcon lorryPicture = new ImageIcon(ImageGrid.class.getResource("/resources/lorry.png"));
JLabel lorryImage = new JLabel(lorryPicture);
MyButtonPanel() {
add(addImage);
addImage.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == addImage) {
imageSpaces[imageCounter].add(lorryImage);
revalidate();
repaint();
imageCounter++;
}
}
}
public static void main(String[] args) {
ImageGrid test = new ImageGrid();
test.setVisible(true);
}
}
You should be revalidating and repainting the panel, (which is the containter being affected by the addition), not the frame
imageSpaces[imageCounter].add(lorryImage);
imageSpaces[imageCounter].revalidate();
imageSpaces[imageCounter].repaint();
Diclaimer: This may work as a simple fix, but also note that a component (in this case your JLabel lorryImage) can only have one parent container. The reason the above fix still works is because you don't revalidate and repaint the previous panel, the label was added to. So you may want to think about doing it correctly, and adding a new JLabel to each panel.
if (e.getSource() == addImage) {
JLabel lorryImage = new JLabel(lorryPicture);
imageSpaces[imageCounter].add(lorryImage);
imageSpaces[imageCounter].revalidate();
imageSpaces[imageCounter].repaint();
imageCounter++;
}
Disclaimer 2: You should add a check, to only add a label if the count is less than the array length, as to avoid the ArrayIndexOutOfBoundsException
Side Notes
Swing apps should be run from the Event Dispatch Thread (EDT). You can do this by wrapping the code in the main in a SwingUtilities.invokeLater(...). See more at Initial Threads
You could also just use a JLabel and call setIcon, instead of using a JPanel

pass value from one jframe to other jframe?

i created two classes one class is just like form the other class is main class and having jmenu and jinternal frames i want to print the input from the form class on the jinternal frame but i cannot understand how i recall the jinternalframe in the form classes, please guide me in this regard or any hint or some piece of code or tutorial that can help me here is code of both the classes. Moreover both classes are working fine .
JTextArea text;
static int openFrameCount = 0;
public form(){
super("Insert Form");
Container panel=getContentPane();
JPanel cc = new JPanel();
cc.setLayout(new FlowLayout());
JButton b=new JButton("print");
b.setPreferredSize(new Dimension(140,50));
b.setBounds(1000,500,350,50);
cc.add(b);
.......................................................
JLabel label1=new JLabel(" Question"+(++openFrameCount));
cc.add(label1);
text=new JTextArea();
text.setLineWrap(true);
text.setWrapStyleWord(true);
text.setPreferredSize(new Dimension(750,50));
text.setBounds(80, 60,750,50);
cc.add(text);
JLabel symbol=new JLabel("Selection for Option?");
symbol.setBounds(200, 120,1000,100);
cc.add(symbol);
..................................................
JLabel op4=new JLabel("4th Option?");
JTextArea otext4=new JTextArea();
otext4.setLineWrap(true);
otext4.setWrapStyleWord(true);
otext4.setPreferredSize(new Dimension(750,50));
otext4.setBounds(10, 40,700,30);
cc.add( op4 ) ;
cc.add( otext4 ) ;
cc.revalidate();
validate();
............................................................
}
#Override
public void actionPerformed(ActionEvent ae) {
if ( e.getSource() == b1 ){
}
}
}
and the second class of jinternalframe is
public class Desktop1 extends JFrame
implements ActionListener {
Desktop p=new Desktop();
JDesktopPane desktop;
static int openFrameCount = 0;
public Desktop1() {
super("InternalFrameDemo");
//Make the big window be indented 50 pixels from each edge
//of the screen.
int inset = 50;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(inset, inset,
screenSize.width - inset*2,
screenSize.height - inset*2);
//Set up the GUI.
desktop = new JDesktopPane(); //a specialized layered pane
createFrame(); //create first "window"
setContentPane(desktop);
setJMenuBar(createMenuBar());
//Make dragging a little faster but perhaps uglier.
desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
}
protected JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
//Set up the lone menu.
.................................................
return menuBar;
}
//React to menu selections.
public void actionPerformed(ActionEvent e) {
if ("new".equals(e.getActionCommand())) { //new
createFrame();
}
............................................
}
}
class MyInternalFrame extends JInternalFrame {
static final int xPosition = 30, yPosition = 30;
public MyInternalFrame() {
super("IFrame #" + (++openFrameCount), true, // resizable
true, // closable
true, // maximizable
true);// iconifiable
setSize(700, 700);
// Set the window's location.
setLocation(xPosition * openFrameCount, yPosition
* openFrameCount);
}
}
//Create a new internal frame.
protected void createFrame() {
Desktop1.MyInternalFrame frame = new Desktop1.MyInternalFrame();
JPanel panel=new JPanel();//to add scrollbar in jinternalpane insert jpanel
panel.setBackground(Color.white);//set background color of jinternal frame
JScrollPane scrollBar=new JScrollPane(panel,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
frame.add(scrollBar);
frame.setVisible(true);
desktop.add(frame);
try {
frame.setSelected(true);
frame.setMaximum(true);
} catch (java.beans.PropertyVetoException e) {}
}
public static void main(String[] args) {
Desktop1 d=new Desktop1();
d.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
d.setVisible(true);
}
}
i want to know hint about the work that come in this part of code to pass the value of form to internal frame when i click on print button
public void actionPerformed(ActionEvent ae) {
if ( e.getSource() == b1 ){
}
}
}
just call the constructor and pass the value
ClassName(parameter)
I guess you want to pass some text to your InternalFrame class on the button click from the main form.
Modify your createFrame() method to accept a String value
e.g-
protected void createFrame(String value){
//..your code
}
and when you call your InternalFrame class, pass this value to its constructor. e.g-
Desktop1.MyInternalFrame frame = new Desktop1.MyInternalFrame(value);
Parameterised constructor will solve your problem. Modify your InternalFrame constructor
e.g-
public MyInternalFrame(String value){
//..use this value
}

Creating a Panel of Button GUI

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.

How to make PopUp window in java

I am currently developing a java application.
I want to show a new Window which contains a text area and a button.
Do you have any ideas?
The same answer : JOptionpane with an example :)
package experiments;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class CreateDialogFromOptionPane {
public static void main(final String[] args) {
final JFrame parent = new JFrame();
JButton button = new JButton();
button.setText("Click me to show dialog!");
parent.add(button);
parent.pack();
parent.setVisible(true);
button.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
String name = JOptionPane.showInputDialog(parent,
"What is your name?", null);
}
});
}
}
Hmm it has been a little while but from what I remember...
If you want a custom window you can just make a new frame and make it show up just like you would with the main window.
Java also has a great dialog library that you can check out here:
How to Make Dialogs
That may be able to give you the functionality you are looking for with a whole lot less effort.
Object[] possibilities = {"ham", "spam", "yam"};
String s = (String)JOptionPane.showInputDialog(
frame,
"Complete the sentence:\n"
+ "\"Green eggs and...\"",
"Customized Dialog",
JOptionPane.PLAIN_MESSAGE,
icon,
possibilities,
"ham");
//If a string was returned, say so.
if ((s != null) && (s.length() > 0)) {
setLabel("Green eggs and... " + s + "!");
return;
}
//If you're here, the return value was null/empty.
setLabel("Come on, finish the sentence!");
If you do not care to limit the user's choices, you can either use a form of the showInputDialog method that takes fewer arguments or specify null for the array of objects. In the Java look and feel, substituting null for possibilities results in a dialog that has a text field and looks like this:
JOptionPane is your friend : http://www.javalobby.org/java/forums/t19012.html
Check out Swing Dialogs (mainly focused on JOptionPane, as mentioned by #mcfinnigan).
public class JSONPage {
Logger log = Logger.getLogger("com.prodapt.autotest.gui.design.EditTestData");
public static final JFrame JSONFrame = new JFrame();
public final JPanel jPanel = new JPanel();
JLabel IdLabel = new JLabel("JSON ID*");
JLabel DataLabel = new JLabel("JSON Data*");
JFormattedTextField JId = new JFormattedTextField("Auto Generated");
JTextArea JData = new JTextArea();
JButton Cancel = new JButton("Cancel");
JButton Add = new JButton("Add");
public void JsonPage() {
JSONFrame.getContentPane().add(jPanel);
JSONFrame.add(jPanel);
JSONFrame.setSize(400, 250);
JSONFrame.setResizable(false);
JSONFrame.setVisible(false);
JSONFrame.setTitle("Add JSON Data");
JSONFrame.setLocationRelativeTo(null);
jPanel.setLayout(null);
JData.setWrapStyleWord(true);
JId.setEditable(false);
IdLabel.setBounds(20, 30, 120, 25);
JId.setBounds(100, 30, 120, 25);
DataLabel.setBounds(20, 60, 120, 25);
JData.setBounds(100, 60, 250, 75);
Cancel.setBounds(80, 170, 80, 30);
Add.setBounds(280, 170, 50, 30);
jPanel.add(IdLabel);
jPanel.add(JId);
jPanel.add(DataLabel);
jPanel.add(JData);
jPanel.add(Cancel);
jPanel.add(Add);
SwingUtilities.updateComponentTreeUI(JSONFrame);
Cancel.addActionListener(new ActionListener() {
#SuppressWarnings("deprecation")
#Override
public void actionPerformed(ActionEvent e) {
JData.setText("");
JSONFrame.hide();
TestCasePage.testCaseFrame.show();
}
});
Add.addActionListener(new ActionListener() {
#SuppressWarnings("deprecation")
#Override
public void actionPerformed(ActionEvent e) {
try {
PreparedStatement pStatement = DAOHelper.getInstance()
.createJSON(
ConnectionClass.getInstance()
.getConnection());
pStatement.setString(1, null);
if (JData.getText().toString().isEmpty()) {
JOptionPane.showMessageDialog(JSONFrame,
"Must Enter JSON Path");
} else {
// System.out.println(eleSelectBy);
pStatement.setString(2, JData.getText());
pStatement.executeUpdate();
JOptionPane.showMessageDialog(JSONFrame, "!! Added !!");
log.info("JSON Path Added"+JData);
JData.setText("");
JSONFrame.hide();
}
} catch (SQLException e1) {
JData.setText("");
log.info("Error in Adding JSON Path");
e1.printStackTrace();
}
}
});
}
}
Try Using JOptionPane or Swt Shell .

Categories