I'm doing a little program for me, with NetBeans. I need no create many JButtons on a JPanel but i can't do it. The JPanel has been generated by the NetBeans editor on a JFrame (also made it by the NetBeans editor)
This is the code:
public static ArrayList<Account> accounts = Account.accounts;
public verCuenta() {
initComponents();
panel.setVisible(true);
Account ac;
JButton button;
int size= accounts.size();
for(int i=0;i<size;i++){
button = new JButton(accounts.get(i).getName());
button.setVisible(true);
button.addActionListener(null);
button.setPreferredSize(new Dimension(50,30));
panel.add(button);
}
I managed to get a single Button to pop up,
maybe start with this first, then try to get several, then get your loop working
// Create a new button:
JButton b1 = new JButton("ok");
// Set the location and size of the button:
b1.setSize(100, 26);
// Add the button to the window:
jPanel1.add(b1);
//Repaint the Panel to make visible
jPanel1.repaint();
It only works when you set a size, just checked in Netbeans.
You can also specify the location, using
b1.setLocation(100, 100);
btw, whole frame is in gridbag layout
you need to add all elements to the panel and then call the setVisible method.
Additions after calling the setVisible method are not per se taking into account.
Related
I've put quite a few objects into this JFrame. however many of them do not appear until I hover them mainly the button as well as the JTextField. I only included the JSpinner components so that it wasn't so long. Is there anything in my spinners or lacking with my spinners that would make them not appear?
I've stripped it down alot so that it is just one textfield. Still nothing shows up. I've put everything in panels, however still nothing shows up.
public static void screen() {
JFrame myFrame = new JFrame("Yore");
myFrame.setAlwaysOnTop(true);
myFrame.setResizable(false);
myFrame.setForeground(Color.BLACK);
myFrame.setSize(300,365);
myFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
myFrame.setVisible(true);
myFrame.setBackground(Color.WHITE);
JPanel panel = new JPanel();
myFrame.setContentPane(panel);
JTextField Username = new JTextField();
Username.setText("Username");
Username.setColumns(10);
panel.add(Username);
}
Sorry, i forgot pne statement.
public static void screen() {
JFrame myFrame = new JFrame("Yore");
myFrame.setAlwaysOnTop(true);
myFrame.setResizable(false);
myFrame.setForeground(Color.BLACK);
myFrame.setSize(300,365);
myFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
myFrame.setVisible(true);
myFrame.setBackground(Color.WHITE);
JPanel panel = new JPanel();
myFrame.setContentPane(panel);
JTextField Username = new JTextField();
Username.setText("Username");
Username.setColumns(10);
panel.add(Username);
panel.validate();
}
Try using a layout manager for the frame. Also, add a JPanel to the frame and add all of the Spinners to the Panel.
Using the correct layout manager, you can programatically add the Spinners to the Panel, so that you do not need to hard code the bounds. You will also have the ability to have them resize as the window resizes, for example.
Take a look here to get started with layout managers.
https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
myFrame.getContentPane() returns an AWT container, not a Swing component. To change this you have to use
JPanel panel = new JPanel();
panel.add(..);
myFrame.setContentPane(panel);
panel.validate();
Add your spinners to the panel and your problem is solved.
Add spinners to the panel. and then add panel to your JFrame.
panel.add(spinner_5);
i recently code a system homepage that include the background image. After i set the background, the button that i created cannot show properly. It just appear after i use the mouse and point to the buttons' location. Can someone teach me how to fix this problem? Your help are appreciated. The codes are as below:
public class HomePage extends JFrame{
private JPanel button = new JPanel();
private JButton time = new JButton("Bus Schedule");
private JButton reserve = new JButton("Booking");
private JButton info = new JButton("About Us");
Container con = getContentPane();
public HomePage(){
setTitle("Bus Reservation System");
setSize(650,500);
setLocation(360,100);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setBackground();
setButton();
}
public void setBackground(){
JLabel background = new JLabel(new ImageIcon("C:/User/Desktop/Assignment/bg.jpg"));
con.add(background);
background.setLayout(new FlowLayout());
con.add(button);
}
public void setButton(){
Font but = new Font("Serif" , Font.ITALIC , 20);
info.setFont(but);
time.setFont(but);
reserve.setFont(but);
button.add(info);
button.add(time);
button.add(reserve);
con.add(button);
}
After you call setVisible(true), if you perform certain actions, you must manually validate() or revalidate() your window.
It is simpler to just call setVisible() after you have initialized all of the desired settings and membership of the window.
/* setVisible(true); -- wrong place */
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setBackground();
setButton();
setVisible(true); // proper place
Simple mistake (probably a typo?), you are setting the layout of the JLabel, you intended to set the layout of the Container. Do con.setLayout(new FlowLayout()); instead of background.setLayout(...)
Also, I believe your path to the file is incorrect. For testing, just put the file in the project and do a path like "bg.jpg", if that works, we can verify this. For me that works. The reason I believe this is the issue is because you specify C:/Users, but then never give the folder for the specific User. A correct path would be C:/Users/Your_name/Desktop/Assignment/bg.jpg
I don't know for sure on that path part, since I'm not on your system. However, for me, if I run your code in my eclipse, this fixes it.
edit:
One last thing, the image isn't really going to be a "background" image with the current code because it will move the buttons underneath it instead of on top of it with the FlowLayout. You may want to use a different Layout.
First of all as already noted, all components should be added to the frame BEFORE invoking setVisible(true) on the JFrame.
JLabel background = new JLabel(new ImageIcon("C:/User/Desktop/Assignment/bg.jpg"));
con.add(background);
background.setLayout(new FlowLayout());
con.add(button);
Based on the above code you are adding two components to the content pane so the hierarchy of your GUI looks like this:
- frame
- content pane
- background
- button
It seems to me you want your GUI to look like this:
- frame
- content pane
- background
- button
So your code should be:
JLabel background = new JLabel(new ImageIcon("C:/User/Desktop/Assignment/bg.jpg"));
con.add(background);
background.setLayout(new FlowLayout());
//con.add(button);
background.add( button );
I just created a GUI, now I want to create another GUI and link both together.
So on the first GUI when the user selects 'next' button, the second GUI is displayed.
For this, do I have to create a new class and just create a GUI again?
Here is what I have now:
import java.awt.Color;
import javax.swing.*;
public class Wizard {
private JLabel lblPicture;
private JRadioButton btLdap, btKerbegos, btSpnego, btSaml2;
private JButton btNext;
private JPanel panel;
public static void main(String[] args) {
new Wizard();
}
public Wizard() {
JFrame frame = new JFrame("Wizard");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600,360);
frame.setVisible(true);
MyPanel();
RadioButtons();
Button();
Image();
groupButton();
frame.add(panel);
frame.setVisible(true);
}
public void MyPanel() {
panel = new JPanel();
panel.setLayout(null);}
public void RadioButtons() {
btLdap = new JRadioButton ("Ldap");
btLdap.setBounds(60,85,100,20);
panel.add(btLdap);
btKerbegos = new JRadioButton ("Kerbegos");
btKerbegos.setBounds(60,115,100,20);
panel.add(btKerbegos);
btSpnego =new JRadioButton("Spnego");
btSpnego.setBounds(60,145,100,20);
panel.add(btSpnego);
btSaml2 = new JRadioButton("Saml2");
btSaml2.setBounds(60,175,100,20);
panel.add(btSaml2);
}
public void Button() {
btNext = new JButton ("Next");
btNext.setBounds(400,260,100,20);
panel.add(btNext);
}
public void Image() {
ImageIcon image = new ImageIcon("image.jpg");
lblPicture = new JLabel(image);
lblPicture.setBounds(200,20, 330, 270);
panel.add(lblPicture);
}
private void groupButton() {
ButtonGroup bg1 = new ButtonGroup( );
bg1.add(btLdap);
bg1.add(btKerbegos);
bg1.add(btSpnego);
bg1.add(btSaml2);
}
}
To display another window, you would create the window, be it a JFrame, JDialog, or what have you, and call setVisible(true) just like you do for your first window.
You ask if your other "window" should be in another class, and likely that answer is yes. Since it will have a completely different set of behaviors and goals from the first class, better to separate out concerns.
Having said that, what you plan to do, to show multiple windows is not always the best user interface design. Better often is to show multiple views using a container that uses a CardLayout.
If you want to display another window in a modal fashion, that is, have the first window wait for the second window to be processed before allowing user interaction, the second window should be a modal JDialog or JOptionPane (a JDialog in disguise).
I think for what you want to achieve, the use of a CardLayout would be appropriate.
This enables you to have multiple panels within the one frame with only one panel visible at a time and has functionality to 'flip' through the panels like a 'deck of cards'. So on initialising your frame you create the panels you want, and specify which one to start at then your next button will go to the next panel in the list.
See the tutorial here there are also some video tutorials available on youtube.
Write the two GUI's in different classes. When you start your program, start the first GUI.
FirstGUI frame1 = new FirstGUI("Title text");
frame1.setVisible(true);
Then, in the action listener code for the button you call "next"...
frame1.setVisible(false); //if you want to save the frame
frame1.dispose(); //if you want to kill the frame
SecondGUI frame2 = new SecondGUI("Title text");
frame2.setVisible(true);
I'm having some troubles with Java Swing.
I'm trying to make a frame with a control panel at the top with some buttons in it.
and below that i want a JTable to show
I've been trying but the table is not showing.
If I remove the controlPanel at the top, it sometimes shows and sometimes not.
The code that I use inside my constructor of my JTable is provided in the same application,
so it's no network error
public ServerMainFrame(GuiController gc){
this.gc = gc;
initGUI();
}
private void initGUI() {
System.out.println("initiating GUI");
createFrame();
addContentPanel();
addControls();
//openPopUpServerSettings();
addSongTable();
}
private void createFrame()
{
this.setTitle("AudioBuddy 0.1");
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(800, 600);
this.setResizable(false);
this.setLocationRelativeTo(null);
}
private void addContentPanel()
{
JPanel p = new JPanel();
p.setLayout(new FlowLayout());
p.setSize(new Dimension(800, 600));
this.setContentPane(p);
}
private void addControls()
{
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
controlPanel.setBorder(BorderFactory.createLineBorder(Color.black));
controlPanel.setSize(700,100);
// Buttons
JButton play = new JButton("Play");
JButton pause = new JButton("Pause");
JButton stop = new JButton ("Stop");
JButton next = new JButton("Next");
JButton prev = new JButton("Previous");
controlPanel.add(play);
controlPanel.add(pause);
controlPanel.add(stop);
controlPanel.add(next);
controlPanel.add(prev);
// Currently playing
JLabel playing = new JLabel("Currently playing:");
controlPanel.add(playing);
JLabel current = new JLabel("Johnny Cash - Mean as Hell");
controlPanel.add(current);
this.getContentPane().add(controlPanel);
}
private void addSongTable()
{
JTable songTable = new JTable(Server.getSongTableModel());
songTable.setVisible(true);
JPanel tablePanel = new JPanel();
tablePanel.setVisible(true);
tablePanel.add(songTable);
songTable.repaint();
this.getContentPane().add(tablePanel);
JButton btnMulticastList = new JButton("send list to clients");
btnMulticastList.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
Server.MulticastPlaylist();
}
});
getContentPane().add(btnMulticastList);
}
if I remove the controlPanel at the top, it sometimes shows and
sometimes not.
everything is hidden in Server.getSongTableModel(), nobody knows without posting an SSCCE with hardcoded value returns from
GUI has issue with Concurency in Swing
XxxModel loading data continiously with building GUi, then exception caused described problems
The code that I use inside my constructor of my JTable is provided in
the same application, so it's no network error
no idea what you talking about
have to create an empty GUI, see InitialTread
showing GUI, then to start loading data to JTable
then starting Workers Thread (Backgroung Task) from SwingWorker or (descr. Network issue) better Runnable#Thread (confortable for catching an exceptions and processing separate threads)
output from Runnable to the Swing GUI must be wrapped into invokeLater()
If you want controls at the top of your window, and the table filling the majority of the window, then I'd suggest you try using BorderLayout instead of FlowLayout. Create it like this...
private void addContentPanel()
{
JPanel p = new JPanel();
p.setLayout(new BorderLayout());
p.setSize(new Dimension(800, 600));
this.setContentPane(p);
}
And add the components by specifying the location in the BorderLayout. In this case, the controls should be added to the top in their minimal size...
this.getContentPane().add(controlPanel,BorderLayout.NORTH);
And the table should be in the center, filling the remaining window space...
this.getContentPane().add(tablePanel,BorderLayout.CENTER);
In your case, you also have a button at the bottom...
getContentPane().add(btnMulticastList,BorderLayout.SOUTH);
For the layout you're after, BorderLayout is much more appropriate. The benefit of using BorderLayout here is that the components should be automatically resized to the size of the window, and you're explicitly stating where each component resides, so panels shouldn't not appear.
It would also be my recommendation that you find an alternative to calling getContentPane() in all your methods. Maybe consider keeping a global variable for the main panel, like this...
private mainPanel;
private void addContentPanel()
{
mainPanel = new JPanel(new BorderLayout());
mainPanel.setSize(new Dimension(800, 600));
this.setContentPane(mainPanel);
}
Then you can reference the panel directly when you want to add() components to it.
Finally, I'd also suggest using GridLayout for your controls, as it will allow you to place all your buttons in it, and they'll be the same size for consistency. Define it like this to allow 5 buttons in a horizontal alignment...
JPanel controlPanel = new JPanel(new GridLayout(5,1));
then you just add the buttons normally using controlPanel.add(button) and they'll be added to the next slot in the grid.
For more information, read about GridLayout or BorderLayout, or just see the Java Tutorial for a Visual Guide to Layout Managers to see what alternatives you have and the best one for your situation. In general, I try to avoid FlowLayout, as I find that there are other LayoutManagers that are more suitable in the majority of instances.
I have a JPanel with a GridLayout(1,0) set to a JFrame Borderlayout.SOUTH, there are placed a couple of buttons in here (when pressed they change a variables value to the index of the created button).
Everything is added correctly, but when I try to update the JPanel it does work at first (only when window is maximized). But then when I go over a button (or all the buttons) it goes back to what the original content of the panel.
I've tried invalidate, validate, repaint, jframe.setvisible(true) - none of these seem to work properly.
Any ideas?
private void toonHand(){
JPanel pnlSouth = new JPanel(new GridLayout(1,0));
JButton[] btnArr =new JButton[50];
ArrayList<Kaart> Thand=uno.getSpeler(0).getHand();
for(int i=0;i<Thand.size();i++){
final int T=i;
btnArr[i]=new JButton();
btnArr[i].setIcon(Thand.get(i).getImg());
btnArr[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
iKaart=T;
}
});
pnlSouth.add(btnArr[i]);
}
Hoofdvenster.remove(pnlSouth);
Hoofdvenster.add(pnlSouth, BorderLayout.SOUTH);
}
The problem was that i was just removing the panel, changing the content and adding it again.
Apparently this was giving some issues with displaying the content.
I fixed it by putting the panels as global variables, and splitting up the making and updating of the panels. So in every update i remove the panel, make the panel a new Panel and then i make it again.