This question already has answers here:
Closed 10 years ago.
i have learnt core java and just started working with netbeans,but i am stuck at a point when i was trying to add the components like buttons,labels etc. at the run time in my project.I searched for it on google but the examples which i studied include some extra overhead of using panels in them,,,,but why can't i create the components at run time as i was creating them in the simple editor like notepad as follows
JButton b4=new JButton("ok");
add b4;
its not working.
To add Swing framework elements at runtime, you need to have a JFrame to add the elements to. A JFrame is just a window, like any other window you use (and just like NetBeans has), and it has a method called add(Component comp). The parameter is whichever Swing or AWT component you want to add to the JFrame. Here is some sample code to get you started:
// This line creates a new window to display the UI elements:
JFrame window = new JFrame("Window title goes here");
// Set a size for the window:
window.setSize(600, 400);
// Make the entire program close when the window closes:
// (Prevents unintentional background running)
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// This makes it so we can position elements freely:
window.setLayout(null);
// Create a new button:
JButton b4 = new JButton("ok");
// Set the location and size of the button:
b4.setLocation(10, 10);
b4.setSize(100, 26);
// Add the button to the window:
window.add(b4);
// Make the window visible (this is the only way to show the window):
window.setVisible(true);
Hopefully, this helps you out! I remember when I started Java, and I would highly recommend getting as good as possible at non-GUI related stuff first, but if you are ready for Swing, then the code above should work. Best of luck!
Related
I've been searching around this site and the internet for hours trying to figure out how to fix this problem. I'm creating a game and it's my first time using graphics. I figured out how to create a JFrame, JPanel and JLabel, and the only problem I can't seem to get around is updating the JLabel. Let's say I start it out like this:
JLabel testing = new JLabel ("blah", JLabel.CENTER);
testing.setAlignmentX(0);
testing.setAlignmentY(0);
frame.add(testing);
I am able to change the text after a Thread.sleep(2500) by using testing.setText("hi");, but the previous state of the JLabel (which says blah) is still there. The "hi" just appears on top. I've tried testing.setVisible(false);, and so many other things but nothing is letting me display the JLabel, hide it, and then change it.
Any ideas what could be wrong?
Thanks
Don't sleep or otherwise block on the AWT Event Dispatch Thread (EDT).
Use javax.swing.Timer instead. Note: not any other class of the same name in a different package.
javax.swing.Timer timer =
new javax.swing.Timer(2500, event -> {
testing.setText("hi");
});
timer.setRepeats(false);
timer.start();
So I am trying to make a messenger sort of app with Java Drag and Drop in Netbeans.
I am fairly new at it. I initially want to take a string from the text area and display it in a JLabel in another panel. I tried to do it in the following process but it did not work.Can someone please help?
private void sendButtonActionPerformed(java.awt.event.ActionEvent evt) {
int i=0;
message = messageType.getText();
JLabel messageLabel = new JLabel();
messageLabel.setText(message);
messageLabel.setSize(100, 100);
messageLabel.setAlignmentX(0);
messageLabel.setAlignmentY(0);
JOptionPane.showMessageDialog(null, message);
clientPanel.add(messageLabel);
messageLabel.setVisible(true);
}
We have no idea what layout manager clientPanel is using and so do not know how well it will accept a JLabel being dropped into it, so as asked your direct question is unanswerable, other than to say you should always call revalidate() on a container (clientPanel) and then repaint() after adding or removing components so that the container re-lays out its components and then redraws them.
I advise against creating new JLabels for this. Much easier to set up the GUI including all necessary JLabels from the very beginning, give them text, empty spaces if need be, and then during the program set the text of an existing JLabel.
If on the other hand you wish to show multiple messages on the cientPanel, then consider using a JList<String> or a non-focusable JTextArea.
I am teaching myself Java and I am reading "Java All in One Desk Reference For Dummies." I am currently using the code provided in the book to practice Swing. Here is the code I am using that comes from the book: `import javax.swing.*;
public class JavaBook6 extends JFrame
{
public static void main(String[] args)
{
new JavaBook6();
}
public JavaBook6()
{
this.setSize(400, 400);
this.setLocation(500, 0);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setTitle("Sample");
this.setVisible(true);
JPanel pnlMain = new JPanel();
JCheckBox chkMy = new JCheckBox("Save");
JButton btnMy = new JButton("Search");
JTextField txtMy = new JTextField(20);
pnlMain.add(chkMy);
pnlMain.add(txtMy);
pnlMain.add(btnMy);
this.add(pnlMain);
}
}
I seem to get inconsistent results when I press run. A window always shows up. However, sometimes the only thing displayed in the window is the Frame title and other times the components such as JCheckBox, JTextArea and JButton show up, as I would expect.
My question is why do the components show up sometimes and not others? I have tried using other components and get the same inconsistent results.
As I stated I am a beginner and I therefore have a very basic understanding of how java works, so please forgive me if the answer to my question is obvious.
I'm not too impressed with the text book:
The GUI should be created on the EDT. Read the section from the Swing tutorial on Concurrency for more information. I would also recommend you use the examples from the tutorials since they incorporate the suggestions from the tutorial.
Component must be added to the GUI before the setVisible( true ) method is invoked. (There are ways around this, but for now keep it simple and follow this rule).
You generally need to do...
this.pack();
before it will display everything.
I suspect if you resize the window, everything shows up?
Adding the pack() tells the layout manager to position and size all the components.
Also if you resize the window or force it to refresh in some way it will also display the components.
I am learning java and building one project to test basics.
I have one menu item FILE and then sub menu item like
1)Front
2)Admin
3)Booking
I have separate gui made in separate files but i want that they should be visible in one area , with click on submenus
I am using swing , JmenuBar . Also the other guis are using Jframe
I have separate gui made in separate files but i want that they should be visible in one area
Most applications should only ever have a single JFrame, which indeed is your requirement since you want the separate GUI to be visible in the same area.
Therefore your other GUI, should not extend JFrame but instead should extend JPanel. Then you can just use a CardLayout on your real GUI to swap the panels in/out depending on which panel is selected from your menu. All these basic are covered in the Swing tutorial. I guess you would start with the section on:
How to Use Card Layout
How to Use Menus
Other people have already talked about ActionListeners and stuff, so that's half of the problem. The other half is how to actually deal with the multiple windows. I would probably not use one JFrame per different GUI, given that the spirit of the JFrame suggests you should only have one instance of it per application. Instead, I would look at using either JDialog or JInternalFrame. I'm not sure what you mean by
...should be visible in one area...
but JInternalFrame will allow you to implement something like a multiple document interface, where all the sub-GUIs would be contained within the frame of the main UI. JDialog would be give you independent windows like JFrame does.
If with "they should be visible in one area" you mean modal, then you should change all your JFrames to JDialogs and leave only the JFrame that contains your main-menu.
To do this, you need an ActionListener for each of the menu items. Then have each listener pass the instance of the JFrame you want to a method that controls where you want to position the window and show it.
//Make menu items
JMenuItem font = new JMenuItem();
font.addActionListener(new ActionListener() {
showWindow(new FontFrame());
});
JMenuItem admin = new JMenuItem();
admin.addActionListener(new ActionListener() {
showWindow(new AdminFrame());
});
...
//define frame handling method
void showWindow(JFrame f) {
...
f.setVistible(true);
}
I want to know how I can make a Java program where an unknown amount of objects can be added to a GUI depending on user input. I can program in objects one at a time within the program, but I haven't seen a more dynamic program.
Can I do that with Java? If not, what can I do it with?
For more information, here's a picture.
There can be more than one question per question block, and each question can have it's own question block.
Yes you can dynamically add and remove components. The basic code would be:
panel.add( ... );
panel.revalidate();
panel.repaint();
Ofcourse you can do it with Java Swings. All you gotta do is based on user input you gotta take a decision to add new JPanels. From the picture you've given in the example, you would need to add a Q&A block dynamically. Simply attach that to any event handler within your application so that it gets added dynamically
public getQandAPanel(){
JPanel questPanel = new JPanel();
JPanel answerPanel = new JPanel();
JPanel wrappingPanel = new JPanel();
wrappingPanel.setLayout(new GridLayout(0,1));
//CODE TO DECORATE question and answer panels should go here
wrappingPanel.add(questPanel);
wrappingPanel.add(answerPanel);
}
Now everytime when you call this getQandAPanel, this would return you a fresh JPanel everytime which you can add it to your parent JFrame. You should have a good idea of Java Swings to know what I'm talking about.