Open second JFrame and components don't show - java

Before you say something, i know the implications of having more than one JFrame. I'm kinda delayed and i need to add the components manually.
So, i open a JFrame that i have designed with a button click:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
JFrame DataCalc = new JFrame();
DataCalc.setVisible(true);
DataCalc.setSize(500, 500);
DataCalc.setLocationRelativeTo(null);
}
Then the JFrame shows up but doesn't show my components. I read that if i setVisible before adding components they won't show, but they're already there cause i designed them.
If i change my code and add the setSize and setLocation like the following code, nothing happens besides the JFrame opening.
public DataCalc() {
this.setSize(500, 500);
this.setLocationRelativeTo(null);
initComponents();
}
Sry for the post, i'll edit my post if you need more info.

JFrame DataCalc = new JFrame();
Should be:
JFrame dataCalc = new DataCalc(); // use the CUSTOM frame!

Related

Getting stared with GUI programming in JAVA

When I compile the code below in Eclipse, I expect a window to appear with a button on the upper left corner of the window. Instead, the button has the same size as the window and fills the window completely, although I suppose to have restricted the size of the button in line 11 with "button.setBounds(20, 20, 200, 50);". Can anybody tell me what I did wrong or what I forgot?
import javax.swing.*;
import java.awt.*;
public class BeobachterGUI {
public BeobachterGUI() {
JFrame frame = new JFrame("A frame");
frame.setSize(new Dimension(600, 600));
JButton button = new JButton("Click me");
button.setBounds(20, 20, 200, 50);
frame.getContentPane().add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new BeobachterGUI();
}
});
}
}
JFrames automatically give themselves a default BorderLayout, which is what is making your button fill the entire screen. If you want to have direct control over the size and position of your button, you have to get rid of that layout manager. Use this line of code:
frame.getContentPane().setLayout(null);
A word of advice, though: working without a layout manager is OK for fun and experimentation, but you shouldn't make a habit of it. You'll get a better GUI (and the users of your GUI get a better experience) if you learn to design with layout managers.
To see an example of what I mean, just watch what happens when you resize your window: if you make the window too small, the button can get cut off or hidden completely. A layout manager would try to reposition and/or resize the button so it stays visible.

Why is JPanel not adding any component at Runtime?

public class Create_JFrame extends JFrame{
public Create_JFrame(){
//Create a Frame
JFrame Frame = new JFrame("Bla-Bla");
JPanel Panel_1 = new JPanel();
JPanel Panel_2 = new JPanel();
JButton Option_1 = new JButton("Option-1");
//Layout management for Panels
Frame.getContentPane().add(BorderLayout.WEST, Panel_1);
//Add button to Panel
Panel_1.add(Option_1);
//Registering Listeners for all my buttons
Option_1.addActionListener(new ListenerForRadioButton(Panel_2));
//Make the frame visible
Frame.setSize(500, 300);
Frame.setVisible(true);
}//end of Main
}//end of Class
public class ListenerForRadioButton implements ActionListener{
JPanel Panel_2;
JButton browse = new JButton("Browse");
//Constructor, will be used to get parameters from Parent methods
public ListenerForRadioButton(JPanel Panel){
Panel_2 = Panel;
}
//Overridden function, will be used for calling my 'core code' when user clicks on button.
public void actionPerformed(ActionEvent event){
Panel_2.add(browse);
System.out.println("My listener is called");
}//end of method
}//end of class
Problem Statement:
I have 2 JPanel components in a a given JFrame. Panel_1 is having a Option_1 JButton. When user clicks on that I am expecting my code to add a JButton 'browse' in Panel_2 at runtime.
Runtime Output:
System is not adding any JButton in Panel_2. However, I see my debug message in output, indicating that system was successful in identifying user's click action on 'option-1'.
Question:
Why is JPanel not adding any component at Runtime?
Panel_2.add(browse);
Panel_2.revalidate();
adding a 'revalidate' will solve the problem.
There are some reasons. but:
usually it's because of using unsuitable LayoutManager.
sometimes it's because of adding the JPanel to it's root component in worng way. which any operation (add, remove,...) works but is not visible.
you must refresh the view when you make some changes on it, like adding or removing components to/from it.
try to use Panel_2.revalidate() to refresh.
if it doesn't work properly use it with Panel_2.repaint() method.
see Java Swing revalidate() vs repaint()
see Difference between validate(), revalidate() and invalidate() in Swing GUI
using setSize twice for your jframe is another way.
Frame.setSize(498, 300); then Frame.setSize(500, 300);

GUI won't open when button pressed (Java)

I am trying to open a GUI from my main GUI by pressing a button. When the button is pressed, this is executed:
WorkloadFactor wf = new WorkloadFactor();
wf.setVisible(true);
This doesn't open the WorkloadFactor GUI. I am confused by this because I have other GUIs that open this way without issue.
WorkloadFactor class works fine when I run it by itself but won't open when it is called by my main GUI. Below is my class without imports and stuff:
public class WorkloadFactor extends JPanel {
public WorkloadFactor() {
setLayout(new BorderLayout());
JTabbedPane tabbedPane = new JTabbedPane();
String[] tabnames = { "Zero", "One", "Two", "Three", "Four" };
for (int i = 0; i < tabnames.length; i++) {
tabbedPane.addTab(tabnames[i], createPane(tabnames[i]));
}
tabbedPane.setSelectedIndex(0);
JButton submit = new JButton("Submit All");
submit.setForeground(Color.RED);
add(tabbedPane, BorderLayout.CENTER);
add(submit, BorderLayout.SOUTH);
}
public JPanel createPane(final String t) {
JPanel contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
//setContentPane(contentPane); I think this might be it?
contentPane.setLayout(null);
setBounds(100, 100, 531, 347);
//***** all the components I am including then add them like so
//******contentPane.add(checkbox1);
//****** contentpane.add(label1);
return contentPane;
}
public static void main(String[] args) {
JFrame frame = new JFrame("Set Workload Factor Information");
frame.getContentPane().add(new WorkloadFactor());
frame.setBounds(100, 100, 531, 347);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
}
I have tried arranging things in so many ways, putting everything in the constructor and other changes but can't seem to find a reason why instantiating this WorkloadFactor class elsewhere and setting it visible won't work.
Does it have something to do with setContentPane(contentPane) vs contentPane.add(xxxx) and returning it?
Thank you for reading!
WorkloadFactor wf = new WorkloadFactor();
wf.setVisible(true);
To be blunt, this won't display anything. Please understand that WorkloadFactor extends JPanel and like all non-top level components must be placed into a container that is ultimately held by a top-level window in order to be displayed. Look at how you display it in your main method -- you first put it into a JFrame, and then display that JFrame. You must do the same thing if you want to display it on button press -- you need to put it into a JPanel or other container that is held by a JFrame or JDialog, or JOptionPane.
Make sure that you have properly registered the button on your main GUI which opens WorkLoadFactor GUI to an action listener.
Since you have not included code from your main GUI I can't confirm this is the issue. However it is a commonly overlooked issue.
Heres some suggestions from the Java documentation tutorials:
"Problem: I'm trying to handle certain events from a component, but the component isn't generating the events it should.
First, make sure you registered the right kind of listener to detect the events. See whether another kind of listener might detect the kind of events you need.
Make sure you registered the listener on the right object.
Did you implement the event handler correctly? For example, if you extended an adapter class, then make sure you used the right method signature. Make sure each event-handling method is public void, that the name spelled right and that the argument is of the right type."
source: Solving Common Event-Handling Problems
Make a JFrame and add a JButton in it than add action listener in button and add this code in it like this:
This code makes a frame with a button and when button is pressed new window is opened.
public class Example extends JFrame {
public Example() {
super("Title");
setLayout(new FlowLayout());
JButton b = new JButton("Open new Frame");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
newWindow nw = new newWindow();
}
});
add(b);
}
}
newWindow Code:
public class newWindow extends JFrame {
newWindow() {
super("title");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,400);
setVisible(true);
}
}

JFrame not displaying button or background color

My JFrame is not displaying the button or background color that is set in the constructor. I am only getting a blank box when I start the program. Not sure what is wrong with the code.
//imports
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;;
public class StartingTheCode{
JButton CalculateButton;
JTextField Ans;
JPanel p;
JFrame f;
public static void main (String[] args){
new StartingTheCode();
}
//constructor
StartingTheCode(){
f = new JFrame("test");
f.setVisible(true);
f.setSize(600,600);
f.setLocationRelativeTo(null);
f.setResizable(false);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p = new JPanel();
p.setBackground(Color.BLUE); // not displaying blue background
CalculateButton = new JButton("+"); // should display button
CalculateButton.setSize(30,30);
CalculateButton.setLocation(5,5);
}
}
You're not adding your button or your JPanel to anything, and so no JFrame is magically going to display them.
You should add your JButton to your JPanel via its add(...) method, and then add the JPanel to the JFrame via its add(...) method, and do so before setting the JFrame visible.
Most importantly, you should read the Swing tutorials, since I speak from experience when saying you'll get no-where just guessing at this stuff. This is all well explained there.
As an aside, avoid setting the sizes of any components and instead read the tutorial section on use of the layout managers as it will allow you to simplify and empower your code greatly.
You need to add your calculateButton to the JPanel with p.add(calculateButton) and add the panel to the frame with f.add(p)

Prevent a JWindow to remain always on top

I created a JFrame and and a JWindow. My problem is that when I click on another application my JFrame passes behind the application but not my JWindow which remains always on top.
I tried to call setAlwaysOnTop(false) on my JWindow but this doesn't change anything.
I would like that the JWindow "follows" the JFrame.
Here's my test code:
public class WindowAlwaysOnTop {
public static void main(String[] args) {
final JFrame frame = new JFrame();
frame.setSize(new Dimension(400, 400));
final JWindow window = new JWindow(frame);
window.setAlwaysOnTop(false);
window.setSize(new Dimension(200, 200));
frame.setVisible(true);
window.setVisible(true);
}
}
This problem occurred with JRE 1.6.0_32 and is solved with JDK7.
Don't use a JWindow.
Instead use a JDialog. Just make sure you specify the frame as the parent when you create the dialog. You can use an undecorated dialog if you don't like the titlebar.

Categories