Position glCanvas alongside a JPanel containing buttons - java

I'd like to have the JButton panel consume ~30% of the frames horizontal space.
And glCanvas on the right side taking up the rest of the frames space.
How can I achieve this layout?
Currently:
Main.java
GLProfile profile = GLProfile.get(GLProfile.GL2);
GLCapabilities capabilities = new GLCapabilities(profile);
GLCanvas glcanvas = new GLCanvas(capabilities);
glcanvas.addGLEventListener(new GameRenderer());
glcanvas.setSize(100, 100);
JFrame frame = new JFrame("Tool");
JPanel panel = new JPanel();
JPanel cpanel=new JPanel();
panel.setLayout(null);
cpanel.setLayout(null);
JButton ButtonBR = new JButton("1");
JButton ButtonE = new JButton("2");
JButton ButtonR = new JButton("3");
JButton ButtonC = new JButton("4");
JButton ButtonT = new JButton("5");
JButton ButtonCR = new JButton("6");
ButtonBR.setBounds(10, 30, 150, 40);
ButtonE.setBounds(10, 80, 150, 40);
ButtonR.setBounds(10, 130, 150, 40);
ButtonC.setBounds(10, 180, 150, 40);
ButtonT.setBounds(10, 230, 150, 40);
ButtonCR.setBounds(10, 450, 150, 40);
cpanel.add(glcanvas);
panel.add(ButtonBR);
panel.add(ButtonE);
panel.add(ButtonR);
panel.add(ButtonC);
panel.add(ButtonT);
panel.add(ButtonCR);
frame.add(cpanel);
frame.add(panel);
frame.setSize(Toolkit.getDefaultToolkit().getScreenSize().width, Toolkit.getDefaultToolkit().getScreenSize().height);
frame.setVisible(true);
Animator animator = new Animator(glcanvas));
animator.start();

Consider using a MigLayout as such:
import javax.swing.JFrame;
import javax.swing.JLabel;
import net.miginfocom.swing.MigLayout;
import javax.swing.JTextField;
public class Main extends JFrame {
private static final long serialVersionUID = 1L;
public Main() {
getContentPane().setLayout(new MigLayout("", "[grow 30][grow 70]", "[]"));
JLabel label = new JLabel("30%");
getContentPane().add(label, "cell 0 0");
JTextField textField = new JTextField("70%");
getContentPane().add(textField, "cell 1 0,growx");
pack();
setVisible(true);
}
public static void main(String[] args) {
new Main();
}
}

Related

My content pane show only white even if it has components on it

I'm doing this as a challenge for myself. My problem is that when I click on the button, the content pane appears plain even if the JPanel has components in it.
I've tried adding the components on the frame but I get an error: >Cannot read field "parent" because "comp" is null.
I've tried other layout on JFrame and JPanel and still it didn't show.
Here's the full code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
public class test implements ActionListener{
public static void main(String [] args) {
new test();
}
static JPanel mainPanel, cubePanel;
static JFrame frame;
static Container container = new Container();
static JLabel calculatorFor;
static JButton sphereButton, rightCylinderButton, rightConeButton, rectangularPrismButton, triangularPrismButton,
cubeButton, squarePyramidButton, rectangularPyramidButton, ellipsoidButton, tetrahedronButton ,backToPreviousFrameButton;
static Font font = new Font(null, Font.PLAIN, 30);
static JLabel enterValueForEdge;
static JTextField edgeTextField;
static JTextArea surfaceAreaTextArea, surfaceAreaFormulaTextArea, surfaceAreaSolutionTextArea;
static JButton calculateButton;
static double edge;
static DecimalFormat surfaceAreaDecimal;
public test(){
frame = new JFrame("Calculating for Surface Area");
calculatorFor = new JLabel("Calculator for the Surface Area of:");
calculatorFor.setSize(600, 40);
calculatorFor.setLocation(100, 50);
calculatorFor.setFont(font);
calculatorFor.setFocusable(false);
sphereButton = new JButton("Sphere ");
sphereButton.setSize(400, 40);
sphereButton.setLocation(100, 100);
sphereButton.setFont(font);
sphereButton.addActionListener(this);
sphereButton.setFocusable(false);
rightCylinderButton = new JButton("Right Cylinder");
rightCylinderButton.setSize(400, 40);
rightCylinderButton.setLocation(100, 150);
rightCylinderButton.setFont(font);
rightCylinderButton.addActionListener(this);
rightCylinderButton.setFocusable(false);
rightConeButton = new JButton("Right Cone");
rightConeButton.setSize(400, 40);
rightConeButton.setLocation(100, 200);
rightConeButton.setFont(font);
rightConeButton.addActionListener(this);
rightConeButton.setFocusable(false);
rectangularPrismButton = new JButton("Rectangular Prism");
rectangularPrismButton.setSize(400, 40);
rectangularPrismButton.setLocation(100, 250);
rectangularPrismButton.setFont(font);
rectangularPrismButton.addActionListener(this);
rectangularPrismButton.setFocusable(false);
triangularPrismButton = new JButton("Triangular Prism");
triangularPrismButton.setSize(400, 40);
triangularPrismButton.setLocation(100, 300);
triangularPrismButton.setFont(font);
triangularPrismButton.addActionListener(this);
triangularPrismButton.setFocusable(false);
cubeButton = new JButton("Cube");
cubeButton.setSize(400, 40);
cubeButton.setLocation(100, 350);
cubeButton.setFont(font);
cubeButton.addActionListener(this);
cubeButton.setFocusable(false);
squarePyramidButton = new JButton("Square Pyramid");
squarePyramidButton.setSize(400, 40);
squarePyramidButton.setLocation(100, 400);
squarePyramidButton.setFont(font);
squarePyramidButton.addActionListener(this);
squarePyramidButton.setFocusable(false);
rectangularPyramidButton = new JButton("Rectangular Pyramid");
rectangularPyramidButton.setSize(400, 40);
rectangularPyramidButton.setLocation(100, 450);
rectangularPyramidButton.setFont(font);
rectangularPyramidButton.addActionListener(this);
rectangularPyramidButton.setFocusable(false);
ellipsoidButton = new JButton("Ellipsoid");
ellipsoidButton.setSize(400, 40);
ellipsoidButton.setLocation(100, 500);
ellipsoidButton.setFont(font);
ellipsoidButton.addActionListener(this);
ellipsoidButton.setFocusable(false);
tetrahedronButton = new JButton("Tetrahedron");
tetrahedronButton.setSize(400, 40);
tetrahedronButton.setLocation(100, 550);
tetrahedronButton.setFont(font);
tetrahedronButton.addActionListener(this);
tetrahedronButton.setFocusable(false);
backToPreviousFrameButton = new JButton("Back");
backToPreviousFrameButton.setSize(100, 40);
backToPreviousFrameButton.setLocation(900, 600);
backToPreviousFrameButton.setFont(font);
backToPreviousFrameButton.addActionListener(this);
backToPreviousFrameButton.setFocusable(false);
mainPanel = new JPanel();
mainPanel.setBounds(0, 0, 1080, 720);
mainPanel.setLayout(null);
mainPanel.setBackground(Color.decode("#FAF7FC"));
mainPanel.add(calculatorFor);
mainPanel.add(sphereButton);
mainPanel.add(rightCylinderButton);
mainPanel.add(rightConeButton);
mainPanel.add(rectangularPrismButton);
mainPanel.add(triangularPrismButton);
mainPanel.add(cubeButton);
mainPanel.add(squarePyramidButton);
mainPanel.add(rectangularPyramidButton);
mainPanel.add(ellipsoidButton);
mainPanel.add(tetrahedronButton);
mainPanel.add(backToPreviousFrameButton);
frame.getContentPane().add(mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(Color.decode("#FAF7FC"));
frame.setLayout(new BorderLayout());
frame.setSize(1080,720);
frame.setResizable(false);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
public void cubePanel(){
enterValueForEdge = new JLabel("Enter Edge:");
enterValueForEdge.setSize(200, 40);
enterValueForEdge.setLocation(100, 50);
enterValueForEdge.setFont(font);
enterValueForEdge.setFocusable(false);
edgeTextField = new JTextField();
edgeTextField.setSize(400, 40);
edgeTextField.setLocation(300, 50);
edgeTextField.setFont(font);
calculateButton = new JButton("Calculate");
calculateButton.setSize(200, 40);
calculateButton.setLocation(100, 100);
calculateButton.setFont(font);
calculateButton.addActionListener(this);
calculateButton.setFocusable(false);
surfaceAreaFormulaTextArea = new JTextArea("SA = 6a²");
surfaceAreaFormulaTextArea.setSize(400, 40);
surfaceAreaFormulaTextArea.setLocation(100, 150);
surfaceAreaFormulaTextArea.setFont(font);
surfaceAreaFormulaTextArea.setEditable(false);
surfaceAreaTextArea = new JTextArea("SA: ");
surfaceAreaTextArea.setSize(500, 40);
surfaceAreaTextArea.setLocation(100, 200);
surfaceAreaTextArea.setFont(font);
surfaceAreaTextArea.setEditable(false);
surfaceAreaSolutionTextArea = new JTextArea();
surfaceAreaSolutionTextArea.setSize(900, 80);
surfaceAreaSolutionTextArea.setLocation(100, 250);
surfaceAreaSolutionTextArea.setFont(font);
surfaceAreaSolutionTextArea.setEditable(false);
surfaceAreaSolutionTextArea.setLineWrap(true);
backToPreviousFrameButton = new JButton("Back");
backToPreviousFrameButton.setSize(100, 40);
backToPreviousFrameButton.setLocation(900, 600);
backToPreviousFrameButton.setFont(font);
backToPreviousFrameButton.addActionListener(this);
backToPreviousFrameButton.setFocusable(false);
cubePanel = new JPanel();
cubePanel.setBounds(0, 0, 1080, 720);
cubePanel.setLayout(null);
cubePanel.setBackground(Color.decode("#FAF7FC"));
container = new Container();
cubePanel.add(enterValueForEdge);
cubePanel.add(edgeTextField);
cubePanel.add(calculateButton);
cubePanel.add(surfaceAreaFormulaTextArea);
cubePanel.add(surfaceAreaTextArea);
cubePanel.add(surfaceAreaSolutionTextArea);
cubePanel.add(backToPreviousFrameButton);
container.add(cubePanel);
container.setLayout(null);
container.setBackground(Color.decode("#FAF7FH"));
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == sphereButton){
new sphereFrame();
frame.dispose();
}
if(e.getSource() == rightCylinderButton){
new rightCylinderFrame();
frame.dispose();
}
if(e.getSource() == rightConeButton){
new rightConeFrame();
frame.dispose();
}
if(e.getSource() == rectangularPrismButton){
new rectangularPrismFrame();
frame.dispose();
}
if(e.getSource() == triangularPrismButton){
new triangularPrismFrame();
frame.dispose();
}
if(e.getSource() == cubeButton){
frame.getContentPane().removeAll();
frame.add(cubePanel);
frame.repaint();
frame.revalidate();
System.out.println("Remove");
frame.getContentPane().add(container);
}
}
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section. Pay particular attention to the Laying Out Components Within a Container section.
Here's the GUI I created.
Press the "Cube" button to bring up the page for the cube calculation.
All Swing applications must start with a call to the SwingUtilities invokeLater method. This method ensures that the Swing components are created and executed on the Event Dispatch Thread.
The JFrame has a default BorderLayout and holds the main JPanel. The main JPanel uses a CardLayout to display the various calculation JPanels. Using a CardLayout is much easier than managing multiple JFrames and provides a nicer user experience.
I used Swing layout managers to position the Swing components on the various JPanels.
The start JPanel consists of two subordinate JPanels. The title JPanel uses a FlowLayout to display the title. The button JPanel uses a GridLayout to display the various calculation JButtons. You can create complex JPanels by nesting multiple simple JPanels.
The cube calculation JPanel was the only one you had in your code, so it was the only one I created. I made it a method, but you can create a separate class for each of the calculations. The cube calculation JPanel uses a GridBagLayout to create a form-like JPanel. I used lambda expressions to create the ActionListener for each of the JButtons, since they were so simple.
I made the start JPanel button ActionListener a separate class just to get the code away from the for loop that creates the JButtons.
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class CardLayoutGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new CardLayoutGUI());
}
private CardLayout cardLayout;
private JTextField edgeTextField, surfaceAreaSolutionTextField;
private JPanel mainPanel;
#Override
public void run() {
JFrame frame = new JFrame("Calculating for Surface Area");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.mainPanel = createMainPanel();
frame.add(mainPanel, BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
cardLayout = new CardLayout();
JPanel panel = new JPanel(cardLayout);
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
panel.add(createStartPanel(), "Start");
panel.add(createCubeCalculationPanel(), "Cube");
return panel;
}
private JPanel createStartPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
panel.add(createTitlePanel(), BorderLayout.NORTH);
panel.add(createButtonPanel(), BorderLayout.CENTER);
return panel;
}
private JPanel createTitlePanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
Font font = new Font(Font.DIALOG, Font.PLAIN, 36);
JLabel label = new JLabel("Calculator for the Surface Area of:");
label.setFont(font);
panel.add(label);
return panel;
}
private JPanel createButtonPanel() {
String[] text = { "Sphere", "Right Cylinder", "Right Cone",
"Rectangular Prism", "Triangular Prism", "Cube",
"Square Pyramid", "Rectangular Pyramid", "Ellipsoid",
"Tetrahedron" };
JPanel panel = new JPanel(new GridLayout(0, 3, 5, 5));
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
Font font = new Font(null, Font.PLAIN, 24);
ButtonListener listener = new ButtonListener();
for (String s : text) {
JButton button = new JButton(s);
button.addActionListener(listener);
button.setFont(font);
panel.add(button);
}
return panel;
}
private JPanel createCubeCalculationPanel() {
JPanel panel = new JPanel(new GridBagLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
Font titleFont = new Font(null, Font.PLAIN, 32);
Font font = new Font(null, Font.PLAIN, 16);
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.LINE_START;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(0, 5, 5, 5);
gbc.weighty = 1.0;
gbc.gridwidth = 2;
gbc.gridx = 0;
gbc.gridy = 0;
JLabel label = new JLabel("SA = 6a²");
label.setFont(titleFont);
panel.add(label, gbc);
gbc.gridwidth = 1;
gbc.gridy++;
label = new JLabel("Edge:");
label.setFont(font);
panel.add(label, gbc);
gbc.gridx++;
edgeTextField = new JTextField(10);
edgeTextField.setFont(font);
panel.add(edgeTextField, gbc);
gbc.gridx = 0;
gbc.gridy++;
label = new JLabel("SA:");
label.setFont(font);
panel.add(label, gbc);
gbc.gridx++;
surfaceAreaSolutionTextField = new JTextField(10);
surfaceAreaSolutionTextField.setFont(font);
surfaceAreaSolutionTextField.setEditable(false);
panel.add(surfaceAreaSolutionTextField, gbc);
gbc.gridwidth = 2;
gbc.gridx = 0;
gbc.gridy++;
JButton calculateButton = new JButton("Calculate");
calculateButton.addActionListener(event -> {
double edge = Double.valueOf(edgeTextField.getText());
double sa = 6.0 * edge * edge;
surfaceAreaSolutionTextField.setText(Double.toString(sa));
});
calculateButton.setFont(font);
panel.add(calculateButton, gbc);
gbc.gridy++;
JButton backButton = new JButton("Back");
backButton.addActionListener(event -> {
cardLayout.show(mainPanel, "Start");
});
backButton.setFont(font);
panel.add(backButton, gbc);
return panel;
}
public class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
JButton button = (JButton) event.getSource();
String text = button.getText();
cardLayout.show(mainPanel, text);
}
}
}
Try this :
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
public class Test2 implements ActionListener {
public static void main(String[] args) {
new Test2();
}
static JPanel mainPanel, cubePanel;
static JFrame frame;
static Container container = new Container();
static JLabel calculatorFor;
static JButton sphereButton, rightCylinderButton, rightConeButton, rectangularPrismButton, triangularPrismButton,
cubeButton, squarePyramidButton, rectangularPyramidButton, ellipsoidButton, tetrahedronButton, backToPreviousFrameButton;
static Font font = new Font(null, Font.PLAIN, 30);
static JLabel enterValueForEdge;
static JTextField edgeTextField;
static JTextArea surfaceAreaTextArea, surfaceAreaFormulaTextArea, surfaceAreaSolutionTextArea;
static JButton calculateButton;
static double edge;
static DecimalFormat surfaceAreaDecimal;
public Test2() {
frame = new JFrame("Calculating for Surface Area");
calculatorFor = new JLabel("Calculator for the Surface Area of:");
calculatorFor.setSize(600, 40);
calculatorFor.setLocation(100, 50);
calculatorFor.setFont(font);
calculatorFor.setFocusable(false);
sphereButton = new JButton("Sphere ");
sphereButton.setSize(400, 40);
sphereButton.setLocation(100, 100);
sphereButton.setFont(font);
sphereButton.addActionListener(this);
sphereButton.setFocusable(false);
rightCylinderButton = new JButton("Right Cylinder");
rightCylinderButton.setSize(400, 40);
rightCylinderButton.setLocation(100, 150);
rightCylinderButton.setFont(font);
rightCylinderButton.addActionListener(this);
rightCylinderButton.setFocusable(false);
rightConeButton = new JButton("Right Cone");
rightConeButton.setSize(400, 40);
rightConeButton.setLocation(100, 200);
rightConeButton.setFont(font);
rightConeButton.addActionListener(this);
rightConeButton.setFocusable(false);
rectangularPrismButton = new JButton("Rectangular Prism");
rectangularPrismButton.setSize(400, 40);
rectangularPrismButton.setLocation(100, 250);
rectangularPrismButton.setFont(font);
rectangularPrismButton.addActionListener(this);
rectangularPrismButton.setFocusable(false);
triangularPrismButton = new JButton("Triangular Prism");
triangularPrismButton.setSize(400, 40);
triangularPrismButton.setLocation(100, 300);
triangularPrismButton.setFont(font);
triangularPrismButton.addActionListener(this);
triangularPrismButton.setFocusable(false);
cubeButton = new JButton("Cube");
cubeButton.setSize(400, 40);
cubeButton.setLocation(100, 350);
cubeButton.setFont(font);
cubeButton.addActionListener(this);
cubeButton.setFocusable(false);
squarePyramidButton = new JButton("Square Pyramid");
squarePyramidButton.setSize(400, 40);
squarePyramidButton.setLocation(100, 400);
squarePyramidButton.setFont(font);
squarePyramidButton.addActionListener(this);
squarePyramidButton.setFocusable(false);
rectangularPyramidButton = new JButton("Rectangular Pyramid");
rectangularPyramidButton.setSize(400, 40);
rectangularPyramidButton.setLocation(100, 450);
rectangularPyramidButton.setFont(font);
rectangularPyramidButton.addActionListener(this);
rectangularPyramidButton.setFocusable(false);
ellipsoidButton = new JButton("Ellipsoid");
ellipsoidButton.setSize(400, 40);
ellipsoidButton.setLocation(100, 500);
ellipsoidButton.setFont(font);
ellipsoidButton.addActionListener(this);
ellipsoidButton.setFocusable(false);
tetrahedronButton = new JButton("Tetrahedron");
tetrahedronButton.setSize(400, 40);
tetrahedronButton.setLocation(100, 550);
tetrahedronButton.setFont(font);
tetrahedronButton.addActionListener(this);
tetrahedronButton.setFocusable(false);
backToPreviousFrameButton = new JButton("Back");
backToPreviousFrameButton.setSize(100, 40);
backToPreviousFrameButton.setLocation(900, 600);
backToPreviousFrameButton.setFont(font);
backToPreviousFrameButton.addActionListener(this);
backToPreviousFrameButton.setFocusable(false);
mainPanel = new JPanel();
mainPanel.setBounds(0, 0, 1080, 720);
mainPanel.setLayout(null);
mainPanel.setBackground(Color.decode("#FAF7FC"));
mainPanel.add(calculatorFor);
mainPanel.add(sphereButton);
mainPanel.add(rightCylinderButton);
mainPanel.add(rightConeButton);
mainPanel.add(rectangularPrismButton);
mainPanel.add(triangularPrismButton);
mainPanel.add(cubeButton);
mainPanel.add(squarePyramidButton);
mainPanel.add(rectangularPyramidButton);
mainPanel.add(ellipsoidButton);
mainPanel.add(tetrahedronButton);
mainPanel.add(backToPreviousFrameButton);
frame.getContentPane().add(mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(Color.decode("#FAF7FC"));
frame.setLayout(new BorderLayout());
frame.setSize(1080, 720);
frame.setResizable(false);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
public Container cubePanel() {
enterValueForEdge = new JLabel("Enter Edge:");
enterValueForEdge.setSize(200, 40);
enterValueForEdge.setLocation(100, 50);
enterValueForEdge.setFont(font);
enterValueForEdge.setFocusable(false);
edgeTextField = new JTextField();
edgeTextField.setSize(400, 40);
edgeTextField.setLocation(300, 50);
edgeTextField.setFont(font);
calculateButton = new JButton("Calculate");
calculateButton.setSize(200, 40);
calculateButton.setLocation(100, 100);
calculateButton.setFont(font);
calculateButton.addActionListener(this);
calculateButton.setFocusable(false);
surfaceAreaFormulaTextArea = new JTextArea("SA = 6a²");
surfaceAreaFormulaTextArea.setSize(400, 40);
surfaceAreaFormulaTextArea.setLocation(100, 150);
surfaceAreaFormulaTextArea.setFont(font);
surfaceAreaFormulaTextArea.setEditable(false);
surfaceAreaTextArea = new JTextArea("SA: ");
surfaceAreaTextArea.setSize(500, 40);
surfaceAreaTextArea.setLocation(100, 200);
surfaceAreaTextArea.setFont(font);
surfaceAreaTextArea.setEditable(false);
surfaceAreaSolutionTextArea = new JTextArea();
surfaceAreaSolutionTextArea.setSize(900, 80);
surfaceAreaSolutionTextArea.setLocation(100, 250);
surfaceAreaSolutionTextArea.setFont(font);
surfaceAreaSolutionTextArea.setEditable(false);
surfaceAreaSolutionTextArea.setLineWrap(true);
backToPreviousFrameButton = new JButton("Back");
backToPreviousFrameButton.setSize(100, 40);
backToPreviousFrameButton.setLocation(900, 600);
backToPreviousFrameButton.setFont(font);
backToPreviousFrameButton.addActionListener(this);
backToPreviousFrameButton.setFocusable(false);
cubePanel = new JPanel();
cubePanel.setBounds(0, 0, 1080, 720);
cubePanel.setLayout(null);
cubePanel.setBackground(Color.decode("#FAF7FC"));
container = new Container();
cubePanel.add(enterValueForEdge);
cubePanel.add(edgeTextField);
cubePanel.add(calculateButton);
cubePanel.add(surfaceAreaFormulaTextArea);
cubePanel.add(surfaceAreaTextArea);
cubePanel.add(surfaceAreaSolutionTextArea);
cubePanel.add(backToPreviousFrameButton);
container.add(cubePanel);
container.setLayout(null);
container.setBackground(Color.getColor("#FAF7FH"));
return container;
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == sphereButton) {
new sphereFrame();
frame.dispose();
}
if (e.getSource() == rightCylinderButton) {
new rightCylinderFrame();
frame.dispose();
}
if (e.getSource() == rightConeButton) {
new rightConeFrame();
frame.dispose();
}
if (e.getSource() == rectangularPrismButton) {
new rectangularPrismFrame();
frame.dispose();
}
if (e.getSource() == triangularPrismButton) {
//new triangularPrismFrame();
frame.dispose();
}
if (e.getSource() == cubeButton) {
frame.getContentPane().removeAll();
frame.add(cubePanel());
frame.repaint();
frame.revalidate();
System.out.println("Remove");
frame.getContentPane().add(container);
}
}
}

How to add spacing between JPanel and JFrame's contentPane?

This is the picture I am trying to replicate
This is what I have (didn't add icon images yet)
I can't seem to find a solution, been staring at it for quite some time.
I am trying to replicate the following picture, using GridLayout for the buttons and the figure out the rest on my own using Java Swing. Furthermore, I've added my buttons into a JPanel and now I'm trying to add spacing between the panel and the pane.
This is what I have, how can I go about it?
super(title);
this.setLayout(new BoxLayout(this.getContentPane(), BoxLayout.PAGE_AXIS));
Container pane = this.getContentPane();
JButton b1 = new JButton();
b1.setBackground(Color.white);
JButton b2 = new JButton();
b2.setBackground(Color.white);
JButton b3 = new JButton();
b3.setBackground(Color.white);
JButton b4 = new JButton();
b4.setBackground(Color.white);
JButton b5 = new JButton();
b5.setBackground(Color.white);
JButton b6 = new JButton();
b6.setBackground(Color.white);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(2,3,10,10));
panel.setBackground(Color.black);
panel.add(b1);
panel.add(b2);
panel.add(b3);
panel.add(b4);
panel.add(b5);
panel.add(b6);
pane.add(panel);
this.setSize(500,500);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
The easiest way to do it would be to add an empty border to your JPanel (see this post on empty borders):
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 2, 10, 10));
// ...
panel.setBorder(new EmptyBorder(50, 50, 50, 50));
Another good approach (depending always on your application needs), if you have the JButton preferred size set, would be to have the main JPanel's grid layout set to have two columns and one row, with another JPanel inside each column. Adding to the interior JPanels a BoxLayout in Y_AXIS mode and aligning the buttons with setAlignmentX() would work great too (note this approach wouldn't center the JButtons vertically) (see How to use BoxLayout):
public class MyFrame extends JFrame {
private String title = "Title";
public MyFrame(){
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout(1,2,10,10));
JPanel rightPanel = new JPanel();
rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
JPanel leftPanel = new JPanel();
leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));
mainPanel.add(leftPanel);
mainPanel.add(rightPanel);
JButton b1 = new JButton();
b1.setBackground(Color.white);
//b1.setIcon(new ImageIcon(img1));
b1.setAlignmentX(Component.RIGHT_ALIGNMENT);
leftPanel.add(b1);
JButton b2 = new JButton();
b2.setBackground(Color.white);
//b2.setIcon(new ImageIcon(img2));
b2.setAlignmentX(Component.RIGHT_ALIGNMENT);
leftPanel.add(b2);
JButton b3 = new JButton();
b3.setBackground(Color.white);
//b3.setIcon(new ImageIcon(img3));
b3.setAlignmentX(Component.RIGHT_ALIGNMENT);
leftPanel.add(b3);
JButton b4 = new JButton();
b4.setBackground(Color.white);
//b4.setIcon(new ImageIcon(img4));
b4.setAlignmentX(Component.LEFT_ALIGNMENT);
rightPanel.add(b4);
JButton b5 = new JButton();
b5.setBackground(Color.white);
//b5.setIcon(new ImageIcon(img5));
b5.setAlignmentX(Component.LEFT_ALIGNMENT);
rightPanel.add(b5);
JButton b6 = new JButton();
b6.setBackground(Color.white);
//b6.setIcon(new ImageIcon(img6));
b6.setAlignmentX(Component.LEFT_ALIGNMENT);
rightPanel.add(b6);
add(mainPanel); //Adding our mainPanel to the contentPane of the JFrame
this.setSize(500,500); //or pack();
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setTitle(title);
this.setVisible(true);
}
}
Here's a little demonstration I whipped up.
All Swing applications must start with a call to the SwingUtilities invokeLater method. This method ensures that all Swing components are created and executed on the Event Dispatch Thread.
You don't set the size of the JFrame and try and make the Swing components fit. You let the JFrame pack with all the Swing components.
You create a GridLayout JPanel inside of a FlowLayout JPanel. The FlowLayout JPanel uses an empty border of the appropriate size.
I used the image the OP provided to get the icons.
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class EmptySpaceDemo implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new EmptySpaceDemo());
}
private Image[] images;
public EmptySpaceDemo() {
this.images = createImages();
}
private Image[] createImages() {
BufferedImage image = readImage();
Image[] images = new Image[6];
images[0] = image.getSubimage(155, 113, 110, 90);
images[1] = image.getSubimage(276, 113, 110, 90);
images[2] = image.getSubimage(155, 217, 110, 90);
images[3] = image.getSubimage(276, 217, 110, 90);
images[4] = image.getSubimage(155, 321, 110, 90);
images[5] = image.getSubimage(276, 321, 110, 90);
return images;
}
#Override
public void run() {
JFrame frame = new JFrame("Empty Space Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBackground(Color.BLACK);
panel.setBorder(BorderFactory.createEmptyBorder(40, 100, 40, 100));
JPanel innerPanel = new JPanel(new GridLayout(0, 2, 10, 10));
innerPanel.setBackground(Color.BLACK);
for (int i = 0; i < images.length; i++) {
JButton button = new JButton(new ImageIcon(images[i]));
innerPanel.add(button);
}
panel.add(innerPanel);
return panel;
}
private BufferedImage readImage() {
try {
return ImageIO.read(getClass().getResourceAsStream("/icons.png"));
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}

background image hidding the other components like buttons labels and other, and vicce versa

how to solve hidding of components in this code
code is running without errors
but background image not displayed
how to change code to get the background image
when using validation method, its creating error in validation()
public class TEST{
public TEST() {
String[] strm = {"Jan", "Feb", "Mar", "Apr", "May"};
String[] stry = {"2016", "2017", "2018","2019"};
String[] strf={"NEW Delhi", "Bangalore", "Chennai"};
String[] strt={"Goa","Kashmir","Hyderabad"};
JFrame f = new JFrame("test");
f.setSize(500, 500);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel lfr = new JLabel("FROM");
JLabel lto = new JLabel("TO");
JLabel lda = new JLabel("DATE");
JLabel ld = new JLabel("DAY");
JLabel lm = new JLabel("MONTH");
JLabel y = new JLabel("YEAR");
JComboBox cfr = new JComboBox(strf);
JComboBox cto = new JComboBox(strt);
JComboBox cd = new JComboBox();
JComboBox cm = new JComboBox(strm);
JComboBox cy = new JComboBox(stry);
JButton bs = new JButton("Search");
JPanel p1 = new JPanel(null);
p1.setPreferredSize(new Dimension(500,500));
JLabel jimage = new JLabel();
jimage.setIcon(new ImageIcon("air.jpg"));
for(int i = 1; i <= 31; i++)
cd.addItem(i);
lfr.setBounds(20, 40, 100, 20);
cfr.setBounds(100, 40, 100, 20);
lto.setBounds(20, 100, 25, 20);
cto.setBounds(100, 100, 100, 20);
lda.setBounds(20, 160, 50, 20);
cd.setBounds(100, 160, 50, 20);
cm.setBounds(160, 160, 65, 20);
cy.setBounds(240, 160, 75, 20);
ld.setBounds(100, 190, 50, 20);
lm.setBounds(160, 190, 50, 20);
y.setBounds(240, 190, 50, 20);
bs.setBounds(20, 230, 100, 20);
p1.add(lfr);
p1.add(cfr);
p1.add(lto);
p1.add(cto);
p1.add(lda);
p1.add(cd);
p1.add(cm);
p1.add(cy);
p1.add(ld);
p1.add(lm);
p1.add(y);
p1.add(bs);
p1.add(jimage);
// validate();
f.add(p1);
f.setVisible(true);
}
public static void main(String[] args) {
new TEST();
}
}
The best you can do is something like:
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Test {
JLabel label;
JComboBox combo;
JButton button;
JPanel pane;
JFrame frame;
JPanel create1stRow() {
JPanel pane = new JPanel();
pane.setLayout(new FlowLayout(FlowLayout.LEFT));
pane.setOpaque(false);
String options[] = {"New Delhi", "Bangalore", "Chennai"};
label = new JLabel("FROM");
combo = new JComboBox(options);
pane.add(label);
pane.add(combo);
return pane;
}
JPanel create2ndRow() {
JPanel pane = new JPanel();
pane.setLayout(new FlowLayout(FlowLayout.LEFT));
pane.setOpaque(false);
String options[] = {"Goa", "Kashmir", "Hyderabad"};
label = new JLabel("TO");
combo = new JComboBox(options);
pane.add(label);
pane.add(combo);
return pane;
}
JPanel create3rdRow() {
JPanel pane = new JPanel();
JPanel dataPane = new JPanel();
pane.setLayout(new FlowLayout(FlowLayout.LEFT));
pane.setOpaque(false);
dataPane.setOpaque(false); //forgot to add this line when I took the pic
dataPane.setLayout(new GridLayout(2, 3)); //2 rows, 3 cols, so we can have the combos with their text aligned
String days[] = {"1", "2", "3", "4", "5"}; //Too lazy to write 31 days
String months[] = {"Jan", "Feb", "Mar", "Apr", "May"}; //Too lazy to write 12 months
String years[] = {"2016", "2017", "2018", "2019", "2020"};
label = new JLabel("DATE");
combo = new JComboBox(days);
//We add the combos
dataPane.add(combo);
combo = new JComboBox(months); //We're reusing the object, but change the data
dataPane.add(combo);
combo = new JComboBox(years); //The same as above
dataPane.add(combo);
//Now we add the labels
dataPane.add(new JLabel("DAYS"));
dataPane.add(new JLabel("MONTHS"));
dataPane.add(new JLabel("YEARS"));
pane.add(label);
pane.add(dataPane); //We add the whole pane to another one
return pane;
}
JPanel create4thRow() {
JPanel pane = new JPanel();
pane.setLayout(new FlowLayout(FlowLayout.LEFT));
pane.setOpaque(false);
button = new JButton("Search");
pane.add(button);
return pane;
}
public Test() {
frame = new JFrame("Test");
frame.setContentPane(new JLabel(new ImageIcon("C:/Users/Frakcool/workspace/StackOverflowProjects/src/test/Air.jpg")));
frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.PAGE_AXIS));
pane = create1stRow();
frame.add(pane);
pane = create2ndRow();
frame.add(pane);
pane = create3rdRow();
frame.add(pane);
pane = create4thRow();
frame.add(pane);
frame.pack();
//frame.setSize(500, 500); //If your image is too large use this
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main (String args[]) {
new Test();
}
}
As you can see in the above code, I'm not using a null layout but a combination of multiple Layout Managers and I suggest you to do it like this in the future.
But if you still want to use that ugly null layout, you were missing this line:
jimage.setBounds(0, 0, 500, 500);
before this one:
lfr.setBounds(20, 40, 100, 20);
The output that my above code gives is:
And the output given by your code with the line I added is:
As you can see, both are really similar, and I could have done them identical but I don't have enough time to do so, but you can by combining the Layout Managers I posted above.
Note: I forgot to mention that to make this program to show the background image, I needed to make every other panels not opaque with pane.setOpaque(false); so, be sure to use this whenever you need to show something that is behind another panel.

JButton on JFrame with Graphics [duplicate]

This question already has answers here:
Components in second JFrame not showing up
(2 answers)
Closed 7 years ago.
I'm trying to make a JFrame that will have graphics and 5 JButtons (which correspond with graphics on screen).
Yesterday my code ran, but now it is glitching and the graphics and buttons only appear when I am resizing the JFrame (pulling it with the cursor!). This is for a game I am making for a class project. If know what the problem may be/is, please tell me. I've been staring at this for so long and I think someone with fresh eyes or more skill than myself could see why the code is wrong. >.<
It has 2 classes, one for graphics and one with a main.
The class for the graphics:
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
import java.awt.Color;
import java.awt.Polygon;
public class drawingComponentMap extends JComponent {
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
drawingComponentMap DCM = new drawingComponentMap(); // this is used in
// the class
// below
Color door = new Color(255, 218, 185); // the graphics are making a
// house, hence the colours
Color glass = new Color(173, 216, 230);
Color mapGrass = new Color(144, 238, 144);
g.setColor(mapGrass);
g2.fillRect(0, 0, 500, 500);
// circles to correspond with buttons (as in each button reps a circle)
Color minigame = new Color(221, 160, 221);
g.setColor(minigame);
g2.fillOval(10, 20, 50, 50);
g2.fillOval(220, 70, 50, 50);
g2.fillOval(20, 200, 50, 50);
g2.fillOval(100, 300, 50, 50);
g2.fillOval(200, 200, 50, 50);
Color black = new Color(0, 0, 0);
g.setColor(black);
g2.drawOval(10, 20, 50, 50);
g2.drawOval(220, 70, 50, 50);
g2.drawOval(20, 200, 50, 50);
g2.drawOval(100, 300, 50, 50);
g2.drawOval(200, 200, 50, 50);
// the house graphic
Color walls = new Color(210, 105, 3);
g.setColor(walls);
g2.fillRect(300, 300, 150, 200);
Color roof = new Color(165, 42, 42);
g.setColor(roof);
g2.drawRect(300, 300, 150, 200);
int[] xPoints = { 300, 375, 450 };
int[] yPoints = { 300, 225, 300 };
Polygon imageTriangle = new Polygon(xPoints, yPoints, 3);
g2.fillPolygon(imageTriangle);
g.setColor(black);
g2.drawPolygon(imageTriangle);
g.setColor(glass);
g2.fillRect(380, 350, 50, 50);
g.setColor(door);
g2.fillRect(325, 450, 30, 50);
g.setColor(black);
g2.drawRect(325, 450, 30, 50);
g2.fillOval(330, 470, 5, 5);
g2.drawRect(380, 350, 50, 50);
g2.drawString("Where do you want to go?", 10, 400);
}
}
this is the class which uses the graphics, and where the jframe, jlabel, and jbuttons are made.
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Map {
JFrame window = new JFrame();
JPanel panel = new JPanel();
JButton button = new JButton();
public static void main(String[] args) {
JFrame window = new JFrame();
JPanel panel = new JPanel();
window.setSize(500, 500);
window.setTitle("Map");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
JButton button1 = new JButton("World 1");
JButton button2 = new JButton("World 2");
JButton button3 = new JButton("World 3");
JButton button4 = new JButton("World 4");
JButton button5 = new JButton("World 5");
panel.add(button1);
panel.add(button2);
panel.add(button3);
panel.add(button4);
panel.add(button5);
window.add(panel);
panel.setVisible(true);
drawingComponentMap DCM = new drawingComponentMap();
window.add(DCM);
}
}
Sorry about the formatting of the code/text portion of this question. I'm in class right now.
It's just a single statement issue - window.setVisible(true).
Move your window.setVisible(true) statement to the end. Your main method contents should now look like this (just for your reference):
JFrame window = new JFrame();
JPanel panel = new JPanel();
window.setSize(500, 500);
window.setTitle("Map");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button1 = new JButton("World 1");
JButton button2 = new JButton("World 2");
JButton button3 = new JButton("World 3");
JButton button4 = new JButton("World 4");
JButton button5 = new JButton("World 5");
panel.add(button1);
panel.add(button2);
panel.add(button3);
panel.add(button4);
panel.add(button5);
window.add(panel);
panel.setVisible(true);
drawingComponentMap DCM = new drawingComponentMap();
window.add(DCM);
window.setVisible(true);

Why isn't anything showing up in my JFrame?

Why is my GUI not showing any buttons, labels, or text fields?
I think I have it all setup, but when I run it, only the frame shows, and none of the contents appear.
package BasicGame;
import java.awt.Container;
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.JTextField;
import javax.swing.SwingConstants;
public class Gui extends JFrame{
private static final long serialVersionUID = 1L;
private JLabel label;
private JTextField textField;
private JButton button;
private buttonHandler bHandler;
public Gui(){
setTitle("Basic Gui");
setResizable(false);
setSize(500, 200);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container pane = getContentPane();
pane.setLayout(null);
button = new JButton("button");
button.setBounds(50, 60, 50, 70);
bHandler = new buttonHandler();
button.addActionListener(bHandler);
label = new JLabel("Hello", SwingConstants.RIGHT);
label.setBounds(50, 60, 50, 70);
textField = new JTextField(10);
textField.setBounds(50, 60, 50, 70);
pane.add(button);
pane.add(label);
pane.add(textField);
}
public class buttonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
System.exit(0);
}
}
#SuppressWarnings("unused")
public static void main(String[] args){
Gui gui = new Gui();
}
}
Move your setVisible() to the end of the constructor. You are adding all of your components after you set your JFrame up and make is visible, so you don't see any of the changes.
This should show your JFrame with all the components:
public Gui(){
setTitle("Basic Gui");
setResizable(false);
setSize(500, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container pane = getContentPane();
pane.setLayout(null);
button = new JButton("button");
button.setBounds(50, 60, 50, 70);
bHandler = new buttonHandler();
button.addActionListener(bHandler);
label = new JLabel("Hello", SwingConstants.RIGHT);
label.setBounds(50, 60, 50, 70);
textField = new JTextField(10);
textField.setBounds(50, 60, 50, 70);
pane.add(button);
pane.add(label);
pane.add(textField);
setVisible(true); // Move it to here
}
Here's what the frame's looked like before and after I moved the setVisible statement and compiled your code.
Before:
After:

Categories

Resources