I did a very simple GUI in Java but when I run the program, the GUI acts wierd!
As soon as I run the application: the GUI shows like this:
Once I simply minimize it and get it back up, it shows fine, like this:
This is the very simple code:
public class Prova2 {
public static void main(String[] args) {
JFrame frame = new JFrame("A Simple GUI");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(650, 120);
frame.setLocation(430, 100);
JPanel panel = new JPanel();
frame.add(panel);
JLabel lbl = new JLabel("Select one of the possible choices and click OK");;
lbl.setVisible(true);
panel.add(lbl);
String[] choices = { "CHOICE 1","CHOICE 2", "CHOICE 3","CHOICE 4","CHOICE 5","CHOICE 6"};
JComboBox<String> cb = new JComboBox<String>(choices);
cb.setVisible(true);
panel.add(cb);
JButton btn = new JButton("OK");
panel.add(btn);
}
}
What am I missing in order to show the GUI fine (with all its element displayed) as soon as I run the application?
It's annoying having to necessarily minimize or resize the window in order to show the GUI properly!
I tested your code and the problem is you are setting the visibility on true before you create the items inside your JFrame. So just cut the frame.setVisible(true); and paste it as the last line of the constructor.
also I see you aren't using a layout manager which is heavy recommended. Check this for information.
Use layout manager
Follow a main Swing Toolkit principle: all UI should be manipulated and started on EDT thread ( UI thread ). Here is a very good explanation http://www.pushing-pixels.org/2007/12/06/unwritten-rule-of-working-with-swings-edt.html
Related
I have some experience in Java creating Apps and would like to learn more, and so have decided to create an application that will have different pages. For example the initial frame will show a menu of buttons that will lead to different frames, showing different components and layouts.
I'm not too sure the best practice of implementing pages. I think I could store the JFrame windows in a list, then use a button handler class to maybe change the visibility of the different frames, only allowing the relevant frame to be visible when the user clicks on a button. I think this method could work, but is there a more efficient/practical way of doing this?
I am aware of CardLayout, however for this program I am trying to learn MigLayout; so that won't be possible (as far as I'm aware). I hope this question is not too vague, I'd just like to know the best practice when it comes to creating applications in Java with different pages.
Can use Tabbed Panes, it is the best for storing pages.
https://docs.oracle.com/javase/tutorial/uiswing/components/tabbedpane.html
Also I noticed that you need to consider top level containers properly, because you don't need to create every time a JFrame for each Page, at least if it was necessary(For example: an editor, create a new window so you need to create a new JFrame, in your case I don't think so) so please consider the link below.
https://docs.oracle.com/javase/tutorial/uiswing/components/toplevel.html
JInternalFrame is a part of Java Swing . JInternalFrame is a container that provides many features of a frame which includes displaying title, opening, closing, resizing, support for menu bar, etc. Internal frames with components example
Code to create multiple internal frames:
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
class solution extends JFrame {
// frame
static JFrame f;
// label to diaplay text
static JLabel l, l1;
// main class
public static void main(String[] args) {
// create a new frame
f = new JFrame("frame");
// set layout of frame
f.setLayout(new FlowLayout());
// create a internal frame
JInternalFrame in = new JInternalFrame("frame 1", true, true, true, true);
// create a internal frame
JInternalFrame in1 = new JInternalFrame("frame 2", true, true, true, true);
// create a Button
JButton b = new JButton("button");
JButton b1 = new JButton("button1");
// create a label to display text
l = new JLabel("This is a JInternal Frame no 1 ");
l1 = new JLabel("This is a JInternal Frame no 2 ");
// create a panel
JPanel p = new JPanel();
JPanel p1 = new JPanel();
// add label and button to panel
p.add(l);
p.add(b);
p1.add(l1);
p1.add(b1);
// set visibility internal frame
in.setVisible(true);
in1.setVisible(true);
// add panel to internal frame
in.add(p);
in1.add(p1);
// add internal frame to frame
f.add(in);
f.add(in1);
// set the size of frame
f.setSize(300, 300);
f.show();
}
}
I have a simple swing App, that can manage a specific type of project with multiple JButton and that print the project tree on the bottom, see the screenshoot bellow when a project is opened in the App :
App screenshoot with project opened
The thing is when no project is opened I get something like this :
App screenshoot without project opened
The HMI is simple and looks like this :
public class Desktop extends JFrame implements ActionListener {
public Desktop() {
JButton newProject, generate, quit, bAddToClassPath, openProject, saveProject;
JPanel mainPanel;
JScrollPane jscrollpane;
super("MainWindow");
setLookAndFeel();
setSize(330, 440);
ParamMainPanel();
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Desktop();
}
});
}
public static void ParamMainPanel() {
mainPanel = new JPanel(new FlowLayout());
// BUTTONS PARAM
newProject = new JButton("Nouveau projet");
generate = new JButton("Générer...");
quit = new JButton("Quitter");
openProject = new JButton ("Ouvrir projet");
saveProject = new JButton ("Sauvegarder");
bAddToClassPath = UIUtil.iconButton();
bAddToClassPath.setActionCommand("setCP");
bAddToClassPath.addActionListener(this);
mainPanel.add(bAddToClassPath);
newProject.addActionListener(this);
newProject.setActionCommand("newP");
generate.addActionListener(this);
generate.setActionCommand("gen");
quit.addActionListener(this);
quit.setActionCommand("qui");
openProject.addActionListener(this);
openProject.setActionCommand("openP");
saveProject.addActionListener(this);
saveProject.setActionCommand("save");
mainPanel.add(newProject);
mainPanel.add(generate);
mainPanel.add(openProject);
mainPanel.add(saveProject);
mainPanel.add(quit);
// PROJECT TREE
jscrollpane = new JScrollPane(new JTree());
jscrollpane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
jscrollpane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
jscrollpane.setMinimumSize(new Dimension(50, 50));
jscrollpane.setLocation(4,61);
jscrollpane.setSize(306,322);
mainPanel.add(jscrollpane);
}
}
So what I want is at the App launch, instead of having the bad looking display JTree (into the jscrollpane) without project opened, having the same display with a project opened (white bloc) but without the project tree inside.
I can't figure how to do it, any ideas ?
Here the answer I found to resolve this display problem :
The FlowLayout used on my main panel somehow was preventing me from resizing my jscrollpane directly using setSize()
So I decided to have a secondary panel on my MainFrame secondMainPanel without specific layout using new JPanel(null);
I did add jscrollpaneon it, then I could resize it without problems to have a correct display.
I think there might be better way to fix it, but this one works.
I am new to Java and especially new to GUI and it's super confusing to me right now.
I'm making a program for class that is supposed to have a menu (JComboBox I'm assuming) that opens a new window when an option is selected. I am just working on the first option where you click "The Matrix" and a new window pops up with two buttons called "Red Pill" & "Blue Pill" and thats where I've hit a wall.
I got to the point where I am able to create a new window (not sure if this is even the right route to take for opening the new window) but, When I try to add Buttons to the new pop up window nothing shows up....
Thanks for any help or pointers in the right direction!
public class MultiForm extends JFrame{
private JComboBox menu;
private JButton bluePill;
private JButton redPill;
private static String[] fileName = {"", "The Matrix", "Another Option"};
public MultiForm() {
super("Multi Form Program");
setLayout(new FlowLayout());
menu = new JComboBox(fileName);
add(menu);
TheHandler handler = new TheHandler();
menu.addActionListener(handler);
}
private class TheHandler implements ActionListener{
public void actionPerformed(ActionEvent event) {
********************************************************************
//Create a new window when "The Matrix" is clicked in the JCB
JFrame newFrame = new JFrame();
JPanel panel = new JPanel();
newFrame.setLayout(new FlowLayout());
newFrame.setSize(500, 300);
newFrame.setDefaultCloseOperation(newFrame.EXIT_ON_CLOSE);
Icon bp = new ImageIcon(getClass().getResource("Blue Pill.png"));
bluePill = new JButton("Blue Pill", bp);
newFrame.add(bluePill);
Icon rp = new ImageIcon(getClass().getResource("Red Pill.png"));
redPill = new JButton("Red Pill", rp);
newFrame.add(redPill);
add(panel);
newFrame.setVisible(true);
}
}
public static void main(String[] args) {
MultiForm go = new MultiForm();
go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
go.setSize(400, 200);
go.setVisible(true);
}
}
I tried doing newFrame.add(BluePill) and it created a button that was the size of the entire window and it would not allow me to add both buttons that way
That's because the frame uses a BorderLayout by default. Unless you specify otherwise, the component's will be added to the CENTER position, BUT, BorderLayout will only allow a single component to be managed at each of the it's five available positions, so you are only seeing the last component you added.
See How to Use BorderLayout for more details
so I figured that wasn't the correct way
It's the right approach, you just need to use a layout manager which can accommodate more components or change the position which you are adding the buttons
In this little example, I've just use a FlowLayout, but you can use what ever is going to give you the effect you desire
JFrame newFrame = new JFrame();
newFrame.setLayout(new FlowLayout());
newFrame.setDefaultCloseOperation(newFrame.EXIT_ON_CLOSE);
bluePill = new JButton("Blue Pill");
newFrame.add(bluePill);
redPill = new JButton("Red Pill");
newFrame.add(redPill);
newFrame.pack();
newFrame.setVisible(true);
As a general rule of thumb, I don't like adding components like this directly to a top level container, I prefer to use a intermediate container, like a JPanel, this gives me more possibilities for re-use, but that's me.
You should also only make the frame visible when it's actually ready, otherwise you may find that some times, the components won't show up
See Laying Out Components Within a Container for more details
You are not using the getContentPane() method from the new JFrame.
You have to actually use getContentPane() first because you're not adding any component to the JFrame itself but to an intermediate "panel".
JFrame newFrame = new JFrame();
JPanel panel = new JPanel();
newFrame.setSize(300, 200);
newFrame.setDefaultCloseOperation(newFrame.EXIT_ON_CLOSE);
bluePill = new JButton("Blue Pill");
panel.add(bluePill);
redPill = new JButton("Red Pill");
panel.add(redPill);
newFrame.getContentPane().add(panel);
newFrame.setVisible(true);
You'll have to add a Layout to the JPanel or/and the JFrame and play with the sizes of the component but with this you're on the right path.
I always put the setVisible method a the end, after adding all the components to the frame.
You made some mistakes.
add(bluePill);
will not do what you want, even if it would, it would still be wrong.
(sounds weird, but I'll explain it)
First the "right" way to do it:
//Create a new window when "The Matrix" is clicked in the JCB
JFrame newFrame = new JFrame();
newFrame.setSize(300, 200);
newFrame.setDefaultCloseOperation(newFrame.EXIT_ON_CLOSE);
bluePill = new JButton("Blue Pill");
newFrame.getContentPane().add(bluePill);
redPill = new JButton("Red Pill");
newFrame.getContentPane().add(redPill);
newFrame.setVisible(true);
Notice I added "newFrame", because you were calling the method of MultiForm.
That's because "add()" is the same as "this.add()" and "this" points to MultiForm. Check it with this line if you want:
System.out.println(this.toString());
The "getContentPane()" is best explained with this image:
You were adding it directly to the JFrame (I don't even know what exactly happens then).
It is also good practice to set the frame visible when it is ready to be visible. Your frame did not contain anything when you made it visible.
Now to the JPanel. A JPanel can hold some elements like JButton,etc. and it can also have a layout. Since you didn't use the JPanel at all, i removed the line from your code. You can still add the JPanel to your ContentPane and add a Layout to the JPanel. (You can also add JPanels to JPanels to create complex layouts)
I hope this was clear for you.
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);
}
}
I am relatively new to Java(especially swing) and I am using BlueJ IDE for some basic Swing programs.
The problem is that when I run it, the output of the code shows no consistency!
Sometimes it gets displayed properly with all the components , but at other times it only displays upto the green panel but not any components inside it that I have added. The components suddenly appear if I maximize or drag the window and increase it's size in those cases.
I would say only about one in 3 or 4 times it runs correctly. What is happening and how can I prevent it?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Swing16
{
public static void main()
{
JFrame frame1 = new JFrame("TESTING");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setVisible(true);
frame1.setSize(1000,700);
frame1.setLocation(200,100);
//frame1.setResizable(false);
frame1.setLayout(null);
JPanel pan1 = new JPanel();
pan1.setBackground(Color.green);
pan1.setBounds(0,0,900,600);
frame1.add(pan1);
pan1.setLayout(null);
JButton east = new JButton("East");
JButton west = new JButton("West");
JButton north = new JButton("North");
JButton south = new JButton("South");
Color cr1 = new Color(0,127,0);
Font ft1 =new Font("impact",Font.BOLD,25);
north.setForeground(Color.white);
north.setBackground(cr1);
south.setForeground(Color.white);
south.setBackground(cr1);
east.setForeground(Color.white);
east.setBackground(Color.blue);
east.setFont(ft1);
east.setToolTipText(" This is the EAST zone");
west.setForeground(Color.white);
west.setBackground(Color.blue);
west.setFont(ft1);
west.setToolTipText(" This is the WEST zone");
JLabel lb1 = new JLabel(" Label 1 ");
JLabel lb2 = new JLabel(" Label 2 ");
lb2.setOpaque(true);
lb2.setForeground(Color.white);
lb2.setBackground(Color.black);
lb2.setFont(ft1);
JTextField tf1 =new JTextField(" TextField1");
tf1.setForeground(Color.white);
tf1.setBackground(Color.black);
tf1.setFont(ft1);
//tf1.selectAll();
JTextField tf2 =new JTextField("TextField 2");
//tf2.getFocus();
JTextArea ta1= new JTextArea("Enter TA",5,30);
ta1.setForeground(Color.white);
ta1.setBackground(Color.black);
//ta1.setFont(ft1);
east.setBounds(400,200,80,100);
pan1.add(east);
west.setBounds(20,200,80,100);
pan1.add(west);
north.setBounds(200,10,100,80);
pan1.add(north);
south.setBounds(200,510,100,80);
pan1.add(south);
lb1.setBounds(0,0,100,50);
pan1.add(lb1);
lb2.setBounds(0,80,100,50);
pan1.add(lb2);
tf1.setBounds(10,350,80,30);
pan1.add(tf1);
tf2.setBounds(10,500,80,30);
pan1.add(tf2);
ta1.setBounds(400,10,100,180);
pan1.add(ta1);
}
}
Three things jump out...
You are not constructing your UI within the context of the Event Dispatching Thread
You are using null layouts
You are calling setVisible(true) on the frame before you've completed building your UI.
Start by making sure that you start you program within the context of the Event Dispatching Thread...
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Construct your UI here...
}
});
}
See Initial Threads for more details...
Not every system is the same. They may have different font metrics, DPI, screen resolutions, graphics pipelines, etc... all which will affect how your UI is rendered. To this end, you should be making use of appropriate layout managers.
Take a look at Laying Out Components Within a Container
And lastly, you should avoid calling setVisible on the frame until you've completed constructing you UI, on some systems, this can present a blank frame