Grey screen on repaint() and revalidate() - java

My application gives a grey screen after the timer is run. As advised, I have now a MainPage which extends JFrame and a MenuPage that extends JPanel. I wish to load MenuPage after MainPage is run. repaint() and revalidate() does not work out for me. Please point me in the right direction.
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
public class MainPage extends JFrame {
private static JPanel contentPane;
//timer
private final static int interval = 40;
private int i;
private Timer t;
private JProgressBar pbar;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainPage frame = new MainPage();
frame.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
public MainPage() {
dim = Toolkit.getDefaultToolkit().getScreenSize();
System.out.println(dim);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
contentPane.setBounds(0,0,dim.width,dim.height);
setContentPane(contentPane);
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
pbar = new JProgressBar (0,20);
pbar.setBounds(600, 500, 200, 45);
pbar.setValue(0);
pbar.setStringPainted(true);
pbar.setForeground(Color.RED);
Border border = BorderFactory.createTitledBorder("Loading...");
pbar.setBorder(border);
t = new Timer (interval, new ActionListener(){
public void actionPerformed(ActionEvent e) {
if (i == 20){
t.stop();
//start.setEnabled(true);
//refresh + load next page
contentPane.removeAll();
MenuPage menuPage = new MenuPage();
//setContentPane(menuPage);
contentPane.add(menuPage);
contentPane.revalidate();
contentPane.repaint();
contentPane.setVisible(true);
}
else{
i++;
pbar.setValue(i);
}
}
});
t.start();
contentPane.add(pbar, BorderLayout.NORTH);
contentPane.add(lblTitle);
contentPane.add(imgLogo);
contentPane.add(imgBackground);
}
}
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class MenuPage extends JPanel {
private JPanel contentPane;
public MenuPage() {
//setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setSize(500, 500);
contentPane.setLayout(null);
add (contentPane);
JButton btnSadfsafsa = new JButton("sadfsafsa");
btnSadfsafsa.setBounds(10, 52, 89, 23);
btnSadfsafsa.setEnabled(true);
btnSadfsafsa.setVisible(true);
contentPane.add(btnSadfsafsa);
}
}

Your MenuPage constructor is the problem.
You create a new JPanel - contentPane but never add it and never set the size. So in fact you just create an empty panel.

I hope this helps others in future. Yes null layout is not to be recommended. Applied setContentPane() instead of contentPane.add() in my case.
//refresh + load next page
contentPane.removeAll();
contentPane.revalidate();
contentPane.repaint();
setContentPane(new MenuPage());

Related

How do I update a JLabel during run time

the JLabel's name is set to an int which changes as the user modifies the number, i tried label.revalidate and Label.repaint after the user changes the int value. i have seen in similar questions people suggest creating a new jlabel everytime, but im wondering if there is a simpler way? the code is very long so i will summerize when needed.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class officia {
static JFrame Frame;
static JPanel Panel;
static JTextField healthPlace;
static String health="0";
static JButton begin;
static JLabel heart;
static int loop;
public static void main(String[] args) {
Panel = new JPanel();
Frame = new JFrame();
Frame.setSize(500,1000);
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Frame.add(Panel);
Panel.setLayout(null);
//adds panel and frame
healthPlace = new JTextField();
healthPlace.setBounds(170, 130, 165, 25);
Panel.add(healthPlace);
begin = new JButton("Begin");
begin.setBounds(217, 185, 70, 25);
Panel.add(begin);
while(loop==1)
loop=0;
heart = new JLabel(health);
heart.setBounds(150, -85, 500, 500);
Panel.add(heart);
Frame.setVisible(true);
//inputs gui's
ActionListener beginPressed = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
health = healthPlace.getText();
loop=1;
}
};
begin.addActionListener(beginPressed);
}
}
You're working in a event driven environment, that is, something happens and you respond to it.
This means, you're while-loop is ill-conceived and is probably the source of your issue. How can the ActionListener for the button be added when the loop is running, but you seem to using the ActionListener to exit the loop...
I modified you code slightly, so when you press the button, it will update the label.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class officia {
static JFrame Frame;
static JPanel Panel;
static JTextField healthPlace;
static String health = "0";
static JButton begin;
static JLabel heart;
static int loop;
public static void main(String[] args) {
Panel = new JPanel();
Frame = new JFrame();
Frame.setSize(500, 1000);
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Frame.add(Panel);
Panel.setLayout(null);
//adds panel and frame
healthPlace = new JTextField();
healthPlace.setBounds(170, 130, 165, 25);
Panel.add(healthPlace);
begin = new JButton("Begin");
begin.setBounds(217, 185, 70, 25);
Panel.add(begin);
// This is ... interesting, but a bad idea
// while (loop == 1) {
// loop = 0;
// }
heart = new JLabel(health);
heart.setBounds(150, -85, 500, 500);
Panel.add(heart);
Frame.setVisible(true);
//inputs gui's
ActionListener beginPressed = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
health = healthPlace.getText();
loop ++;
heart.setText(Integer.toString(loop));
}
};
begin.addActionListener(beginPressed);
}
}
JLabel#setText is what's known as a stateful property, that is, it will trigger an update that will cause it to be painted, so, if it's not updating, you're doing something wrong.
Possible runnable example (of what I think you want to do)
You're working a very rich UI framework. One if it's, many, features, is the layout management framework, something you should seriously take the time to learn to understand and use.
See Laying Out Components Within a Container for more details.
Below is a relatively simple example which shows one way you might "swicth" between views based on a response to a user input
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new BasePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class BasePane extends JPanel {
private CardLayout cardLayout;
public BasePane() {
cardLayout = new CardLayout();
setLayout(cardLayout);
StartPane startPane = new StartPane(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cardLayout.show(BasePane.this, "HeartPane");
}
});
HeartPane heartPane = new HeartPane();
add(startPane, "StartPane");
add(heartPane, "HeartPane");
}
}
public class StartPane extends JPanel {
public StartPane(ActionListener actionListener) {
setBorder(new EmptyBorder(10, 10, 10, 10));
setLayout(new GridBagLayout());
JButton start = new JButton("Begin");
add(start);
start.addActionListener(actionListener);
}
}
public class HeartPane extends JPanel {
private JTextField heartTextField;
private JLabel heartLabel;
public HeartPane() {
setBorder(new EmptyBorder(10, 10, 10, 10));
setLayout(new GridBagLayout());
heartLabel = new JLabel("Heart");
heartTextField = new JTextField(10);
add(heartLabel);
add(heartTextField);
}
}
}

How to get JDialog textFiels Value from JFrame

Hi I am new in Java coding and trying to design a user friendly desktop App with the help of JFrame and JDialog -
My JFrame is -
package com.myapp.ui;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JCheckBox;
public class MyFrame extends JFrame {
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MyFrame frame = new MyFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public MyFrame() {
setTitle("MyFrame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnClickMe = new JButton("Click Me");
btnClickMe.setBounds(271, 171, 115, 29);
contentPane.add(btnClickMe);
JCheckBox chckbxOpenDialog = new JCheckBox("Open Dialog");
chckbxOpenDialog.setBounds(25, 171, 139, 29);
contentPane.add(chckbxOpenDialog);
chckbxOpenDialog.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(chckbxOpenDialog.isSelected()== true){
MyDialog MD = new MyDialog();
MD.setModal(true);
MD.setVisible(true);
}
}
});
btnClickMe.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Here I want to get the value of textFieldName and textFieldEmail from JDialog
//after Click on Confirm Button in JDialog and closing/disposing it
}
});
}
}
My JDialog is -
package com.myapp.ui;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class MyDialog extends JDialog {
private final JPanel contentPanel = new JPanel();
private JTextField textFieldName;
private JTextField textFieldEmail;
private JButton btnConfirm;
public static void main(String[] args) {
try {
MyDialog dialog = new MyDialog();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
public MyDialog() {
setTitle("MyDialog");
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
textFieldName = new JTextField();
textFieldName.setBounds(108, 26, 146, 26);
contentPanel.add(textFieldName);
textFieldName.setColumns(10);
textFieldEmail = new JTextField();
textFieldEmail.setBounds(108, 68, 146, 26);
contentPanel.add(textFieldEmail);
textFieldEmail.setColumns(10);
btnConfirm = new JButton("Confirm");
btnConfirm.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//passing the Name and Email field value in JFrame
}
});
btnConfirm.setBounds(132, 141, 115, 29);
contentPanel.add(btnConfirm);
MyFrame MF = new MyFrame();
}
}
Both the JFrame and JDialog are in the same package. I am trying to get the value of
textFieldName and textFieldEmail from JDialog to JFrame
if any one can guide me the best possible way, would be relly great.
You could:
Add setters to MyFrame
Pass MyFrame reference to MyDialog (using this) when it is created in the ActionListener
In the ActionListener in MyDialog set fields in MyFrame
There are probably better ways to do this. The built in JOptionPane produces modal dialog windows that wait for user input. These would be better rather than passing references of JFrames to JDialog.
Also note that JavaFX has largely replaced Java Swing for desktop UIs

Trying to set the location of a Java Button using JFrame isn't working?

Please look below for Edits.
So I've looking over numerous "solutions" to fix my problem, but I just can't seem to get it working.
This is what my application looks like with the code below:
Basically, I want to set the location of a button, but I can't manage to do so. Here is my code:
package me.cervinakuy.application;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ControlPanel3 extends JFrame {
JPanel panel = new JPanel();
JButton startRobo = new JButton();
JButton stopRobo = new JButton();
JButton restartRobo = new JButton();
public ControlPanel3() {
// setLayout(null);
setSize(1000, 700);
setResizable(false);
setLocation(450, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setBackground(new Color(45, 48, 55));
setTitle("Espin Software | Control Panel");
setVisible(true);
startRobo.setIcon(new ImageIcon(getClass().getResource("/resources/startRobo.png")));
stopRobo.setIcon(new ImageIcon(getClass().getResource("/resources/stopRobo.png")));
restartRobo.setIcon(new ImageIcon(getClass().getResource("/resources/restartRobo.png")));
startRobo.setBorder(null);
stopRobo.setBorder(null);
restartRobo.setBorder(null);
startRobo.setLocation(100, 100);
panel.add(startRobo);
panel.add(stopRobo);
panel.add(restartRobo);
panel.setOpaque(false);
add(panel);
validate();
}
}
EDIT:
I have now managed to create a GUI of what I was initially looking for, however, I have a new problem. Buttons are now pressable from different parts of the GUI, rather than only on the image. For those interested, here is what I have been able to accomplish:
New GUI look.
Updated Code:
package me.cervinakuy.application;
import java.awt.Color;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ControlPanel3 extends JFrame {
JPanel panel = new JPanel();
JButton startRobo = new JButton();
JButton stopRobo = new JButton();
JButton restartRobo = new JButton();
public ControlPanel3() {
// setLayout(null);
setSize(1000, 700);
setResizable(false);
setLocation(450, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setBackground(new Color(45, 48, 55));
setTitle("Espin Software | Control Panel");
setVisible(true);
startRobo.setIcon(new ImageIcon(getClass().getResource("/resources/startRobo.png")));
stopRobo.setIcon(new ImageIcon(getClass().getResource("/resources/stopRobo.png")));
restartRobo.setIcon(new ImageIcon(getClass().getResource("/resources/restartRobo.png")));
startRobo.setBorder(null);
stopRobo.setBorder(null);
restartRobo.setBorder(null);
panel.setLayout(null);
startRobo.setLocation(200, 200);
startRobo.setBounds(5, -95, 300, 300);
stopRobo.setBounds(5, 0, 300, 300);
restartRobo.setBounds(5, 95, 300, 300);
panel.add(startRobo);
panel.add(stopRobo);
panel.add(restartRobo);
panel.setOpaque(false);
add(panel);
validate();
}
}
There are typically a number of ways to layout components that end with the same effect. In this example, we use a panel to contain the buttons in a column (buttonContainer using a GridLayout) then a panel to restrict that container to the top (buttonConstrainPanel using a BorderLayout) then a container to put that panel on the left (ui with BorderLayout).
It could also be achieved using a single GridBagLayout or a GroupLayout, though the logic of achieving it might not be as simple.
The focus border seen on the blue button indicates the limits of where a mouse click would activate the button.
import java.awt.*;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class ThreeButtonAlignedLeft {
private JComponent ui = null;
private String prefix = "http://i.stack.imgur.com/";
private String[] suffix = {"gJmeJ.png","T5uTa.png","wCF8S.png"};
ThreeButtonAlignedLeft() {
try {
initUI();
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
}
public void initUI() throws MalformedURLException {
if (ui!=null) return;
ui = new JPanel(new BorderLayout(4,4));
ui.setBorder(new EmptyBorder(4,4,4,4));
JPanel buttonContainer = new JPanel(new GridLayout(0, 1, 5, 5));
for (int ii=0; ii<suffix.length; ii++) {
JButton b = new JButton(new ImageIcon(new URL(prefix + suffix[ii])));
b.setBorderPainted(false);
b.setMargin(new Insets(0,0,0,0));
b.setContentAreaFilled(false);
buttonContainer.add(b);
}
JPanel buttonConstrainPanel = new JPanel(new BorderLayout(0, 0));
buttonConstrainPanel.add(buttonContainer, BorderLayout.PAGE_START);
ui.add(buttonConstrainPanel, BorderLayout.LINE_START);
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
ThreeButtonAlignedLeft o = new ThreeButtonAlignedLeft();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}

How to close jframe panel or window

I have 2 frames/windows, I have Exit button on window 2, an from window 1 I launch window 2 and then exit it i.e setVisible(false);
When I execute window 2 I can easily click button exit and hide the current window, however when I launch window 2 from window 1, and then click exit button I get NullPointerException Error. then I instantiated it in the beginning with static and this error was gone, however the window 2 is not being closed/hidden its still there with no effect of button.
Window 1 code:
package com.my.jlms;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class LibrarianMenu extends JFrame {
private JPanel contentPane;
private static LibrarianMenu frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame = new LibrarianMenu();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public LibrarianMenu() {
setTitle("Librarian");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 385, 230);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnPasswd = new JButton("Change Pass");
btnPasswd.setBounds(202, 76, 146, 39);
contentPane.add(btnPasswd);
btnPasswd.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
ChangePwd framee = new ChangePwd();
framee.setVisible(true);
}
});
}
}
Window 2 Code:
package com.my.jlms;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
public class ChangePwd extends JFrame {
private JPanel contentPane;
private static ChangePwd frame = new ChangePwd();;
private JButton btnExit;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame = new ChangePwd();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ChangePwd() {
setResizable(false);
setTitle("Password!");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 266, 154);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
btnExit = new JButton("Exit");
btnExit.setBounds(20, 80, 89, 30);
contentPane.add(btnExit);
btnExit.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent ae) {
frame.setVisible(false);
}
});
}
}
Is there a solution I can set window 2 to hide ?
The problem here is that you are creating your frame, as your class, and not on the object frame, but you hide the frame which represents the object frame.
Change this line (in your actionListener's actionPerformed() method):
frame.setVisible(false);
to:
setVisible(false);
You can use dispose function for the purpose.see how dispose works.
If you want to close a JFrame, you could use the dispose() method.
Example:
public void actionPerformer(ActionEvent e)
{
if(e.getSource().equals(closeFrameButton)
{
dispose(); //This will close the current JFrame
}
}
NOTE: this is different to System.exit(0);. Using this will close the Java virtual machine. if you just want to close the frame, use dispose()

Changing the Bounds of a Swing GUI and Naming of the JButtons

I know how to set the the bounds, so in the end a new setbounds() call would give the new bounds, but I dont know how long/wide should the new bound be, it depends on the input number of buttons like here for example :
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.border.EmptyBorder;
public class Book_GUI extends JFrame {
private EconomyClass eco;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Book_GUI frame = new Book_GUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Book_GUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
//contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
//this.add(contentPane);
JButton btnBookFlight;
//eco = new EconomyClass();
//eco.setSeats(5);
for(int i=0;i<45;i++){
btnBookFlight = new JButton("Book" +i);
btnBookFlight.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JButton button = (JButton)arg0.getSource();;
button.setBackground(Color.RED);
button.setOpaque(true);
}
});
btnBookFlight.setBounds(77, 351, 100, 23);
contentPane.add(btnBookFlight);
}
}
}
As you see the last 5 buttons are not visible, one has to enlarge the GUI a little bit with mouse... and first 10 buttons are smaller than others because after 9 the number digits increase which is logical but can I align all of them at the same order and size? Another issue, the button name "Book" is just for test it should be 1A Window, 1B Middle, 1C Aisle some space 1D Aisle,1E Middle,1F Middle, 1G Aisle some space 1H Aisle, 1I Middle, 1J Window and below these 2A Window... Just like in a plane, any hints how I can arrange the namings and the necessary space between them is highly appreciated!
You should avoid using null layout or absolute positioning for arranging swing components. Always use the best appropriate layout manager in the situation since it has a lot of advantages. The best layout to handle your current situation is GridLayout
Here is the modified version of your code using GridLayout
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.border.EmptyBorder;
public class Book_GUI extends JFrame {
// private EconomyClass eco;
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Book_GUI frame = new Book_GUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Book_GUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new GridLayout(9, 5));
// contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
// this.add(contentPane);
JButton btnBookFlight;
// eco = new EconomyClass();
// eco.setSeats(5);
for (int i = 0; i < 45; i++) {
btnBookFlight = new JButton("Book" + i);
btnBookFlight.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JButton button = (JButton) arg0.getSource();
;
button.setBackground(Color.RED);
button.setOpaque(true);
}
});
// btnBookFlight.setBounds(77, 351, 100, 23);
contentPane.add(btnBookFlight);
}
pack();
}
}
Further read : A Visual Guide to Layout Managers
for assign dynamically names to a collection of JButton, you can using this:
List<JButton> listOfButtons = new ArrayList<JButton>(collection.size());
for (int i=0; i < collection.size(); i++) {
JButton button = new JButton();
listOfButtons.add(button);
}

Categories

Resources