Why is the window empty when I run my java program? - java

I am trying to create a GUI in java. I am adding buttons, labels, text fields, and combo boxes. When I run my program, the window that pops up is completely blank. Any ideas why this is happening?
public Project3() {
JPanel leftPanel = new JPanel();
leftPanel.setLayout(new GridLayout(7, 2));
leftPanel.setBounds(20, 10, 5, 5);
leftPanel.add(shapeLbl);
leftPanel.add(shapeBox);
leftPanel.add(fillLbl);
leftPanel.add(fillBox);
leftPanel.add(colorLbl);
leftPanel.add(colorBox);
leftPanel.add(widthLbl);
leftPanel.add(widthTxt);
leftPanel.add(heightLbl);
leftPanel.add(heightTxt);
leftPanel.add(xLbl);
leftPanel.add(xTxt);
leftPanel.add(yLbl);
leftPanel.add(yTxt);
add(leftPanel);
JPanel rightPanel = new JPanel();
rightPanel.setBounds(270, 10, 5, 5);
rightPanel.setBorder(BorderFactory.createTitledBorder("Shape Drawing"));
add(rightPanel);
JPanel botPanel = new JPanel();
botPanel.setBounds(240, 250, 5, 5);
botPanel.add(drawBtn);
add(botPanel);
drawBtn.setToolTipText("Using the information above, this button " +
"draws a shape in the area titled \"Shape Drawing.\"");
drawBtn.setMnemonic('d');
}
public static void main(String[] args) {
Project3 p3 = new Project3();
p3.setTitle("Geometric Drawing");
p3.setLayout(null);
p3.setSize(500, 301);
p3.setLocationRelativeTo(null);
p3.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p3.setVisible(true);
}
}

Related

How to create custom panel layout with Swing? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
public class BattleShipsMain {
public static void main(String[] args) {
// JButton arrays to hold buttons
JButton[] userButtons = new JButton[100];
JButton[] compButtons = new JButton[100];
// Text for ships label
String shipsText = "Ships Size (Squares)" + "Carrier 5"
+ "Battleship 4" + "Destroyer 3"
+ "Patrol Boat 2";
// Draw main window and set layout
JFrame window = new JFrame("Battle Ships");
window.setSize(1200, 1900);
window.getContentPane().setLayout(new BorderLayout());
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Draw top game panel
JPanel gridPanTop = new JPanel();
gridPanTop.setLayout(new BorderLayout());
gridPanTop.setPreferredSize(new Dimension(1300, 400));
gridPanTop.setBackground(Color.GRAY);
// Top panel text
JLabel ships = new JLabel();
ships.setText(shipsText);
// Bottom panel buttons
JButton submit = new JButton("Submit");
Dimension submitSize = new Dimension(20, 20);
submit.setSize(submitSize);
// Draw bottom game panel
JPanel panBottom = new JPanel();
panBottom.setBackground(Color.WHITE);
panBottom.setLayout(new BorderLayout());
panBottom.setPreferredSize(new Dimension(200, 200));
panBottom.add(submit);
// Set position of game panels
window.getContentPane().add(gridPanTop, BorderLayout.PAGE_START);
window.getContentPane().add(panBottom, BorderLayout.CENTER);
// Set border for grid buttons
Border border = new LineBorder(Color.gray);
// Draw panel for grids
JPanel user = new JPanel();
JPanel comp = new JPanel();
user.setBackground(Color.gray);
comp.setBackground(Color.gray);
user.setBorder(border);
comp.setBorder(border);
// Set layout for grid panels
user.setLayout(new GridLayout(10, 10));
comp.setLayout(new GridLayout(10, 10));
int x = userButtons.length;
// Set user buttons as JButtons, set size and add to grid
for (int i = 0; i < x; i++) {
userButtons[i] = new JButton();
userButtons[i].setPreferredSize(new Dimension(40, 40));
user.add(userButtons[i]);
}
// Set computer buttons as JButtons, set size and add to grid
for (int i = 0; i < x; i++) {
compButtons[i] = new JButton();
compButtons[i].setPreferredSize(new Dimension(40, 40));
comp.add(compButtons[i]);
}
// Add panels to main frame and set visible
window.pack();
window.add(gridPanTop);
window.add(panBottom);
gridPanTop.add(user, BorderLayout.WEST);
gridPanTop.add(comp, BorderLayout.EAST);
gridPanTop.setVisible(true);
panBottom.setVisible(true);
window.setVisible(true);
user.setVisible(true);
comp.setVisible(true);
// Start main game
MainGame start = new MainGame();
}
}
I have an assignment and am having lot of trouble creating the below panel layout in Java Swing. I have had no luck using any of the layouts.
Could anyone help my with this layout?
At present the code displays the following output:
You can probably tell I am a beginner so please excuse rookie errors. The panel layout I have at the moment LOOKS like the ideal one I attached but clearly is not the correct layout as I'd like.
You can achive this with different layouts and compound of layouts (using subpanels). I would have used GridBagLayout, that is definitely one of the most versatile layouts.
Example code
public class TestLayout extends JFrame {
private static final long serialVersionUID = -7619921429181915663L;
public TestLayout(){
super("TestLayout");
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
init();
}
private void init() {
this.getContentPane().setLayout(new GridBagLayout());
//Setup some test panel with labels
JPanel panel1 = new JPanel(new BorderLayout());
panel1.setBorder(BorderFactory.createEtchedBorder());
JLabel label1 = new JLabel("Panel 1");
label1.setHorizontalAlignment(SwingConstants.CENTER);
panel1.add(label1,BorderLayout.CENTER);
JPanel panel2 = new JPanel(new BorderLayout());
panel2.setBorder(BorderFactory.createEtchedBorder());
JLabel label2 = new JLabel("Panel 2");
label2.setHorizontalAlignment(SwingConstants.CENTER);
panel2.add(label2,BorderLayout.CENTER);
JPanel panel3 = new JPanel(new BorderLayout());
panel3.setBorder(BorderFactory.createEtchedBorder());
JLabel label3 = new JLabel("Panel 3");
label3.setHorizontalAlignment(SwingConstants.CENTER);
panel3.add(label3,BorderLayout.CENTER);
JPanel panel4 = new JPanel(new BorderLayout());
panel4.setBorder(BorderFactory.createEtchedBorder());
JLabel label4 = new JLabel("Panel 4");
label4.setHorizontalAlignment(SwingConstants.CENTER);
panel4.add(label4,BorderLayout.CENTER);
//Here goes the interesting code
this.getContentPane().add(panel1, new GridBagConstraints(0, 0, 1, 1, 1.0, 0.6, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(2, 2,
2, 2), 0, 0));
this.getContentPane().add(panel2, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.6, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(2, 2,
2, 2), 0, 0));
this.getContentPane().add(panel3, new GridBagConstraints(2, 0, 1, 1, 1.0, 0.6, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(2, 2,
2, 2), 0, 0));
//next row
this.getContentPane().add(panel4, new GridBagConstraints(0, 1, 3, 1, 1.0, 0.4, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(2, 2,
2, 2), 0, 0));
this.setPreferredSize(new Dimension(400, 200));
this.pack();
}
public static void main(String[] args) {
TestLayout frame = new TestLayout();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Generated output
The key part of the GridBagLayout is the GridBagConstraints
new GridBagConstraints(columnNumber, rowNumber, columnSpan, rowSpan, columnWeigth, rowWeigth, alignment, fillType, insets, padX, pady)
see in example how rowWeigth is set to 0.6 for first row and 0.4 to second row so that first row takes up some more space (60%). Adjust them as you like (if you like same space, just set 0.5 to both).

Button does not create JPanel

I am new in Java and am doing some window application for my college.
I am trying to do some kind of menu with three buttons in start, and when one of buttons is clicked it's supposed to create a JPanel with two more buttons, but my code doesn't work.
Here is the code:
import java.awt.*;
public class mainScreen extends JFrame {
private JPanel contentPane;
public mainScreen() {
super("Aplikacija za atletska natjecanja");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(0, 0, screenSize.width, screenSize.height);
contentPane = new JPanel();
contentPane.setBackground(SystemColor.info);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
setContentPane(contentPane);
JPanel top = new JPanel();
top.setBounds(200, 11, screenSize.width - 400, screenSize.height - (screenSize.height - 100));
contentPane.add(top);
JPanel mainMenu = new JPanel();
mainMenu.setBounds(200, 110, screenSize.width - 400, screenSize.height - (screenSize.height - 30));
contentPane.add(mainMenu);
mainMenu.setLayout(new GridLayout(1, 0, 0, 0));
JButton btnTrkacke = new JButton("Trka\u010Dke");
btnTrkacke.setBackground(SystemColor.text);
mainMenu.add(btnTrkacke);
btnTrkacke.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JPanel panTrk = new JPanel();
panTrk.setBounds(201, 140, (screenSize.width - 400) / 3, 30);
contentPane.add(panTrk);
panTrk.setLayout(new GridLayout(1, 0, 0, 0));
JButton btnTrkAtl = new JButton("Atleti\u010Dari");
btnTrkAtl.setBackground(SystemColor.text);
panTrk.add(btnTrkAtl);
JButton btnTrkDisc = new JButton("Discipline");
btnTrkDisc.setBackground(SystemColor.text);
panTrk.add(btnTrkDisc);
}
});
JButton btnSkakacke = new JButton("Skaka\u010Dke");
btnSkakacke.setBackground(SystemColor.text);
mainMenu.add(btnSkakacke);
JButton btnBacacke = new JButton("Baca\u010Dke");
btnBacacke.setBackground(SystemColor.text);
mainMenu.add(btnBacacke);
}
}
That same panel should also be created when I click on the other two buttons, but on other the position... Is it better to create class for that pane and then call it when button is clicked?
You're forgetting to call revalidate and repaint on the contentPane after changing its components:
contentPane.revalidate();
contentPane.repaint();
e.g.,
#Override
public void actionPerformed(ActionEvent e) {
JPanel panTrk = new JPanel();
panTrk.setBounds(201, 140, (screenSize.width - 400) / 3, 30);
contentPane.add(panTrk);
panTrk.setLayout(new GridLayout(1, 0, 0, 0));
JButton btnTrkAtl = new JButton("Atleti\u010Dari");
btnTrkAtl.setBackground(SystemColor.text);
panTrk.add(btnTrkAtl);
JButton btnTrkDisc = new JButton("Discipline");
btnTrkDisc.setBackground(SystemColor.text);
panTrk.add(btnTrkDisc);
contentPane.revalidate(); // ***** added *****
contentPane.repaint(); // ***** added *****
}
revalidate tells the container to re-lay out its components.
repaint requests to the paint manager that the component and any children should be re-drawn.
As an aside: you're using null layout manager and absolute positioning with setBounds(...), and you really don't want to do this. While to a newbie this seems the best way to create complex GUI's, the more you deal with Swing GUI creation, the more you will find that doing this will put your GUI in a straight-jacket, painting it in a very tight corner and making it very hard to extend or enhance. Just don't do this.
will ask here, coz its same project
so it shuld work like this.... 3 buttons, and under each button is hiden panel with two button, so whan some button is clicked under him shuld show panel, whan some ather button is clicked under him shuld show panel, but ather two panels shuld hide.... and this works great until some button is clicked 2 time in a row, after that whan i click some ather button panel under that button dont wont to hide..
here is the code
JPanel mainMenu = new JPanel();
mainMenu.setBounds(200, 110, screenSize.width - 400, screenSize.height - (screenSize.height - 30));
contentPane.add(mainMenu);
mainMenu.setLayout(new GridLayout(1, 0, 0, 0));
JButton btnTrkacke = new JButton("Trka\u010Dke");
btnTrkacke.setBackground(SystemColor.text);
mainMenu.add(btnTrkacke);
btnTrkacke.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
panTrk = new JPanel();
panTrk.setBounds(201, 140, (screenSize.width - 400) / 3, 30);
contentPane.add(panTrk);
panTrk.setLayout(new GridLayout(1, 0, 0, 0));
JButton btnTrkAtl = new JButton("Atleti\u010Dari");
btnTrkAtl.setBackground(SystemColor.text);
panTrk.add(btnTrkAtl);
JButton btnTrkDisc = new JButton("Discipline");
btnTrkDisc.setBackground(SystemColor.text);
panTrk.add(btnTrkDisc);
contentPane.revalidate();
contentPane.repaint();
panSka.setVisible(false);
panBac.setVisible(false);
}
});
JButton btnSkakacke = new JButton("Skaka\u010Dke");
btnSkakacke.setBackground(SystemColor.text);
mainMenu.add(btnSkakacke);
btnSkakacke.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
panSka = new JPanel();
panSka.setBounds(201 + (screenSize.width - 400) / 3, 140, (screenSize.width - 400) / 3, 30);
contentPane.add(panSka);
panSka.setLayout(new GridLayout(1, 0, 0, 0));
JButton btnSkaAtl = new JButton("Atleti\u010Dari");
btnSkaAtl.setBackground(SystemColor.text);
panSka.add(btnSkaAtl);
JButton btnSkaDisc = new JButton("Discipline");
btnSkaDisc.setBackground(SystemColor.text);
panSka.add(btnSkaDisc);
contentPane.revalidate();
contentPane.repaint();
panTrk.setVisible(false);
panBac.setVisible(false);
}
});
JButton btnBacacke = new JButton("Baca\u010Dke");
btnBacacke.setBackground(SystemColor.text);
mainMenu.add(btnBacacke);
btnBacacke.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
panBac = new JPanel();
panBac.setBounds(201 + (screenSize.width - 400) / 3 * 2, 140, (screenSize.width - 400) / 3, 30);
contentPane.add(panBac);
panBac.setLayout(new GridLayout(1, 0, 0, 0));
JButton btnBacAtl = new JButton("Atleti\u010Dari");
btnBacAtl.setBackground(SystemColor.text);
panBac.add(btnBacAtl);
JButton btnBacDisc = new JButton("Discipline");
btnBacDisc.setBackground(SystemColor.text);
panBac.add(btnBacDisc);
contentPane.revalidate();
contentPane.repaint();
panSka.setVisible(false);
panTrk.setVisible(false);
}
});

Border with spacing in Java?

I'm trying to make a border, which as been successful. I want there to be some spacing before the border starts. Using this code now, the border is wrapped very tight around the text box. This is what I want to do: Ideal
public static void main(String[] args) {
// TODO code application logic here
//Variables
JFrame mainframe = new JFrame();
mainframe.setSize(500, 435);
JPanel cards = new JPanel(new CardLayout());
CardLayout cl = (CardLayout)(cards.getLayout());
mainframe.setTitle("Future Retro Gaming Launcher");
//Screen1
JPanel screen1 = new JPanel();
JTextPane TextPaneScreen1 = new JTextPane();
TextPaneScreen1.setEditable(false);
TextPaneScreen1.setBackground(new java.awt.Color(240, 240, 240));
TextPaneScreen1.setText("Welcome to the install wizard for Professor Phys!\n\nPlease agree to the following terms and click the next button to continue.");
TextPaneScreen1.setSize(358, 48);
TextPaneScreen1.setLocation(0, 0);
TextPaneScreen1.setBorder(BorderFactory.createLineBorder(Color.black));
TextPaneScreen1.setMargin(new Insets(3,3,3,3));
screen1.add(TextPaneScreen1);
cards.add(screen1);
mainframe.add(cards);
mainframe.setVisible(true);
}
Try creating a compound border with your line border and an empty border:
BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.black),
BorderFactory.createEmptyBorder(5, 5, 5, 5))

Use Spring layout For Hand GUI

I have a jframe that has a lable and two radiobuttons.
I use spring layout, But my second radioButton seen in top left of page!
public class tester extends JFrame {
public tester() {
add(create());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 500);
setVisible(true);
}
public JPanel create() {
JPanel panel = new JPanel();
ButtonGroup group = new ButtonGroup();
JRadioButton r1 = new JRadioButton("Yes");
JRadioButton r2 = new JRadioButton("No");
group.add(r1);
group.add(r2);
JLabel lable = new JLabel("Today is sunday?");
panel.add(lable);
// panel.add(group); // How add this?
panel.add(r1);
panel.add(r2);
JButton savebt= new JButton("Save");
JButton cancelbt=new JButton("Cancell");
panel.add(savebt);
panel.add(cancelbt);
panel.setLayout(new SpringLayout());
SpringUtilities.makeCompactGrid(panel, 1, 3, 50, 100, 25, 50);
return panel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new tester();
}
});
}
}
Now this exception occur:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: No such child: 5
I want to display my two buttons on below of radio button's line!
There are three items in your panel, so the number of columns should be 3:
SpringUtilities.makeCompactGrid(panel, 1, 3, 50, 100, 25, 50);
// panel.add(group); // How add this?
You don't need this. ButtonGroups don't get added to a panel. They are for button selection management and are not displayed.

Panels overlap each other when box not big enough

I have this gui; and when the height is not big enough the panes will overlap each other. I have to set it at least 200, so I can completely see the two rows; but when it is set at 200, then I have like a big empty row at the end, and I don't want that. How could I fix this? Thanks.
import java.awt.FlowLayout;
import javax.swing.*;
import java.awt.*;
public class MyFrame extends JFrame {
JButton panicButton;
JButton dontPanic;
JButton blameButton;
JButton newsButton;
JButton mediaButton;
JButton saveButton;
JButton dontSave;
public MyFrame() {
super("Crazy App");
setSize(400, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel row1 = new JPanel();
panicButton = new JButton("Panic");
dontPanic = new JButton("No Panic");
blameButton = new JButton("Blame");
newsButton = new JButton("News");
//adding first row
GridLayout grid1 = new GridLayout(4, 2, 10, 10);
setLayout(grid1);
FlowLayout flow1 = new FlowLayout(FlowLayout.CENTER, 10, 10);
row1.setLayout(flow1);
row1.add(panicButton);
row1.add(dontPanic);
row1.add(blameButton);
row1.add(newsButton);
add(row1);
//adding second row
JPanel row2 = new JPanel();
mediaButton = new JButton("Blame");
saveButton = new JButton("Save");
dontSave = new JButton("No Save");
GridLayout grid2 = new GridLayout(3, 2, 10, 10);
setLayout(grid2);
FlowLayout flow2 = new FlowLayout(FlowLayout.CENTER, 10, 10);
row2.setLayout(flow2);
row2.add(mediaButton);
row2.add(saveButton);
row2.add(dontSave);
add(row2);
setVisible(true);
}
public static void main(String[] args) {
MyFrame frame = new MyFrame();
}
}
The original code set the layout for one panel on two separate occasions. For clarity, set it once in the constructor.
The 2nd layout specified 3 rows
Call pack() on the top-level container to have the GUI reduce to the minum sze needed for the components.
End result
import java.awt.FlowLayout;
import javax.swing.*;
import java.awt.*;
public class MyFrame17 extends JFrame {
JButton panicButton;
JButton dontPanic;
JButton blameButton;
JButton newsButton;
JButton mediaButton;
JButton saveButton;
JButton dontSave;
public MyFrame17() {
super("Crazy App");
setLayout(new GridLayout(2, 2, 10, 10));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel row1 = new JPanel();
panicButton = new JButton("Panic");
dontPanic = new JButton("No Panic");
blameButton = new JButton("Blame");
newsButton = new JButton("News");
FlowLayout flow1 = new FlowLayout(FlowLayout.CENTER, 10, 10);
row1.setLayout(flow1);
row1.add(panicButton);
row1.add(dontPanic);
row1.add(blameButton);
row1.add(newsButton);
add(row1);
//adding second row
JPanel row2 = new JPanel();
mediaButton = new JButton("Blame");
saveButton = new JButton("Save");
dontSave = new JButton("No Save");
FlowLayout flow2 = new FlowLayout(FlowLayout.CENTER, 10, 10);
row2.setLayout(flow2);
row2.add(mediaButton);
row2.add(saveButton);
row2.add(dontSave);
add(row2);
pack();
setVisible(true);
}
public static void main(String[] args) {
MyFrame17 frame = new MyFrame17();
}
}
Further tips
Don't extend frame, just use an instance of one.
Build the entire GUI in a panel which can then be added to a frame, applet, dialog..
When developing test classes, give them a more sensible name than MyFrame. A good word to add is Test, then think about what is being tested. This is about the layout of buttons, so ButtonLayoutTest might be a good name.
GUIs should be started on the EDT.

Categories