I have a Jframe and I want to show grids as follows:
There are 3rows and in the 2nd row there are two columns.So,but when I add a Jlabel and Jtextfield in 2nd row,then the 2nd column of 2nd grid goes below the 2nd row and acts as 3rd column. For eg:
So "hello55" needs to come side by side of the 2nd row,but it is coming downward as extra row in swing. How can I make it side to side?
So,I tried as:
public class AdminDashboard extends JFrame {
private JPanel panel,subPanel1;
public AdminDashboard() {
System.out.println("hello");
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(1000, 609);
panel=new JPanel();
panel.setLayout(new GridLayout(3,1,5,10));
JLabel labe11=new JLabel("hello11");
JLabel labe12=new JLabel("hello22");
JLabel labe13=new JLabel("hello33");
JLabel labe14=new JLabel("hello44");
JLabel labe15=new JLabel("hello55");
panel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
panel.add(labe11);
subPanel1 = new JPanel(); // sub-panel 1
subPanel1.setLayout(new GridLayout(0,2,5,10));
//creating form for 2nd row 1st column
JLabel userLabel = new JLabel("User");
userLabel.setBounds(10, 10, 80, 25);
subPanel1.add(userLabel);
JTextField userText = new JTextField(20);
userText.setBounds(100, 10, 80, 25);
subPanel1.add(userText);
JLabel passwordLabel = new JLabel("Password");
passwordLabel.setBounds(10, 40, 80, 25);
subPanel1.add(passwordLabel);
JPasswordField passwordText = new JPasswordField(20);
passwordText.setBounds(100, 40, 160, 25);
subPanel1.add(passwordText);
JButton loginButton = new JButton("login");
loginButton.setBounds(10, 80, 80, 25);
subPanel1.add(loginButton);
JButton registerButton = new JButton("register");
registerButton.setBounds(180, 80, 80, 25);
subPanel1.add(registerButton);
//2nd row 2nd column
subPanel1.add(labe15);
subPanel1.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
subPanel1.setBackground(Color.red);
panel.add(subPanel1);
panel.add(labe13);
add(panel);
}
}
The below code simply sets up your desired GUI and nothing more. It is not a complete, working application. Explanations after the code.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class AdminDashboard implements Runnable {
private JFrame frame;
#Override
public void run() {
showGui();
}
private JPanel createBottomPanel() {
JPanel bottomPanel = new JPanel();
JLabel hello33 = new JLabel("hello33");
bottomPanel.add(hello33);
return bottomPanel;
}
private JPanel createFormPanel() {
JPanel formPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.LINE_START;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets.bottom = 5;
gbc.insets.left = 5;
gbc.insets.right = 5;
gbc.insets.top = 5;
JLabel userLabel = new JLabel("User");
formPanel.add(userLabel, gbc);
gbc.gridx = 1;
JTextField userTextField = new JTextField(6);
formPanel.add(userTextField, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
JLabel passwordLabel = new JLabel("Password");
formPanel.add(passwordLabel, gbc);
gbc.gridx = 1;
JPasswordField passwordField = new JPasswordField(6);
formPanel.add(passwordField, gbc);
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridx = 0;
gbc.gridy = 2;
JButton loginButton = new JButton("login");
formPanel.add(loginButton, gbc);
gbc.gridx = 1;
JButton registerButton = new JButton("register");
formPanel.add(registerButton, gbc);
return formPanel;
}
private JPanel createMainPanel() {
JPanel mainPanel = new JPanel(new GridLayout(0, 2, 5, 10));
mainPanel.add(createFormPanel());
mainPanel.add(createTablePanel());
return mainPanel;
}
private JPanel createTablePanel() {
JPanel tablePanel = new JPanel();
JLabel hello55 = new JLabel("hello55");
tablePanel.add(hello55);
return tablePanel;
}
private JPanel createTopPanel() {
JPanel topPanel = new JPanel();
JLabel hello11 = new JLabel("hello11");
topPanel.add(hello11);
return topPanel;
}
private void showGui() {
frame = new JFrame("Admin Dashboard");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(createTopPanel(), BorderLayout.PAGE_START);
frame.add(createMainPanel(), BorderLayout.CENTER);
frame.add(createBottomPanel(), BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
/**
* Start here.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new AdminDashboard());
}
}
The default layout manager for the content pane of JFrame is BorderLayout. So I placed the hello11 as the top component and the hello33 as the bottom component.
In the center component I put a panel and set its layout manager to GridLayout so that I could nest within it two panels side by side where the left panel is your form and the right panel is hello55.
For the panel displaying the [login] form, I used GridBagLayout.
Here is a screen capture of the window displayed when running the above code.
If is this what you want to do:
public class Registration extends Application {
// Defines the text fields and respective label components that will be used.
private TextField loginField;
private TextField nameField;
private TextField cpfField;
private TextField emailField;
private TextField addressField;
private PasswordField passwordField;
private Label passwordLabel;
private Label nameLabel;
private Label cpfLabel;
private Label emailLabel;
private Label addressLabel;
private Button submit;
private Button cancel;
#Override
public void start(Stage primaryStage){
// Sets top title
primaryStage.setTitle("Registration");
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER);
// Defines the gap between grid components
grid.setHgap(10);
grid.setVgap(10);
// Defines our window size
Scene scene = new Scene(grid, 900, 500);
grid.setPadding(new Insets(25, 25, 25, 25));
// Defines the label names and add them to the grid
Label header = new Label("Registration");
grid.add(header, 1, 0, 2, 1);
nameLabel = new Label("Name:");
grid.add(nameLabel, 0, 1);
emailLabel = new Label("Email:");
grid.add(emailLabel, 0, 2);
passwordLabel = new Label("Password:");
grid.add(passwordLabel, 0, 3);
cpfLabel = new Label("Cpf:");
grid.add(cpfLabel, 0, 4);
addressLabel = new Label("Address:");
grid.add(addressLabel, 0, 5);
nameField = new TextField();
grid.add(nameField, 1, 1);
emailField = new TextField();
grid.add(emailField, 1, 2);
passwordField = new PasswordField();
grid.add(passwordField, 1, 3);
cpfField = new TextField();
grid.add(cpfField, 1, 4);
addressField = new TextField();
grid.add(addressField, 1, 5);
grid.add(infoError, 2, 7);
submit = new Button("Submit");
// Defines the submit button action
submit.setOnAction((ActionEvent event) -> {
// your registration code here ...
});
HBox hbSubmit = new HBox(10);
hbSubmit.setAlignment(Pos.CENTER_RIGHT);
hbSubmit.getChildren().add(submit);
grid.add(hbSubmit, 3, 6);
// Define a cancelling button and set its action to close the window when activated
cancel = new Button("Cancel");
cancel.setOnAction((ActionEvent event) -> {
primaryStage.close();
});
HBox hbCancel = new HBox(10);
hbCancel.setAlignment(Pos.CENTER);
hbCancel.getChildren().add(cancel);
grid.add(hbCancel, 0, 6);
primaryStage.setScene(scene);
primaryStage.show();
}
}
Related
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);
}
}
}
Recently I'm writing a mail system client using Java (I chose swing to write the GUI and use IDEA to hardcode my GUI). In the Compose module, I want to show or hide the textfield for CC and Bcc when I click the corresponding buttons.
So I googled and browsed the following questions and doc on the web:
How to make JPanel scrollable in Java?
How to make JPanel scrollable?
Scrolling a JPanel
Doc: JScrollPane
Finally, I chose the JScrollPane to implement it.
My simplified sample code is as follows (the original code is tedious):
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Demo extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JLabel lbl1;
private JTextField txf1;
private JLabel lbl2;
private JTextField txf2;
// container for lbl2 and txf2, which should be able to be shown or hidden
private JPanel pnlContainer2;
private JLabel lbl3;
private JTextField txf3;
// container for lbl3 and txf3
private JPanel pnlContainer3;
private JButton btnShow;
// the container I want to move when I click btnShow
private JPanel pnlBody;
// the panel to hold my "cards"
// In this example, I include it just to show what controls are on my interface.
private JPanel pnlContent;
private JPanel pnlContainer;
// here, I want to use JScrollPane to make my pnlContainer scrollable
// to adapt to my interface
private JScrollPane scrollPane;
public Demo() {
init();
}
private void init() {
pnlContainer = new JPanel(new CardLayout(), true);
pnlContainer.setBounds(0, 0, 200, 180);
pnlContent = new JPanel(null, true);
pnlContent.setBounds(0, 0, 200, 180 + 50);
scrollPane = new JScrollPane(pnlContent, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setBounds(0, 0, 200, 180);
pnlContainer.add(scrollPane);
pnlBody = new JPanel(null, true);
lbl1 = new JLabel("lbl1");
lbl1.setBounds(10, 20, 40, 30);
txf1 = new JTextField();
txf1.setBounds(60, 20, 120, 30);
pnlContent.add(lbl1);
pnlContent.add(txf1);
pnlContainer2 = new JPanel(null, true);
pnlContainer2.setBounds(0, 70, 180, 30);
lbl2 = new JLabel("lbl2");
lbl2.setBounds(10, 0, 40, 30);
txf2 = new JTextField();
txf2.setBounds(60, 0, 120, 30);
pnlContainer2.add(lbl2);
pnlContainer2.add(txf2);
pnlContainer2.setVisible(false);
pnlContent.add(pnlContainer2);
pnlBody = new JPanel(null, true);
pnlBody.setBounds(0, 70, 180, 90);
pnlContainer3 = new JPanel(null, true);
pnlContainer3.setBounds(0, 0, 180, 30);
pnlBody.add(pnlContainer3);
lbl3 = new JLabel("lbl3");
lbl3.setBounds(10, 0, 40, 30);
txf3 = new JTextField();
txf3.setBounds(60, 0, 120, 30);
pnlContainer3.add(lbl3);
pnlContainer3.add(txf3);
btnShow = new JButton("show");
btnShow.setBounds(60, 50, 80, 30);
btnShow.addActionListener(this);
pnlBody.add(btnShow);
pnlContent.add(pnlBody);
this.add(pnlContainer);
this.setLayout(null);
this.setTitle("Demo");
this.setSize(200, 200);
this.setLocationRelativeTo(null);
this.setVisible(true);
this.setResizable(false);
// ImageIcon icon = new ImageIcon("E:\\Javarepo\\Hmail\\src\\main\\resources\\assets\\hmail.png");
// this.setIconImage(icon.getImage());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Object src = e.getSource();
if (src instanceof JButton) {
JButton btn = (JButton) src;
boolean showSelected = false;
String altText;
if (btn == btnShow) {
showSelected = btnShow.getText() == "show";
altText = showSelected ? "hide" : "show";
btnShow.setText(altText);
}
relayout(showSelected);
}
}
private void relayout(boolean showSelected) {
int x = pnlBody.getX();
int y = pnlBody.getY();
if (showSelected) {
pnlContainer2.setVisible(true);
pnlBody.setBounds(x, y + 50, 180, 90);
} else {
pnlContainer2.setVisible(false);
pnlBody.setBounds(x, y - 50, 180, 90);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new Demo());
}
}
However, no matter which JPanel I apply JScrollPane to, I cannot make my interface adaptive to the hide and show of my JContainer2.
How can I modify it, or what control to use to replace JScrollPane? Any suggestions will be welcome.
And here is my platform information:
java -version
java version "1.8.0_212"
Java(TM) SE Runtime Environment (build 1.8.0_212-b10)
Java HotSpot(TM) 64-Bit Server VM (build 25.212-b10, mixed mode)
OS: win10 1909
arch: amd64
I rewrote your code. Explanations appear after it.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
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.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.WindowConstants;
public class Demo2 implements ActionListener, Runnable {
private static final String HIDE = "HIDE";
private static final String SHOW = "SHOW";
private JButton button;
private JLabel lbl2;
private JFrame frame;
private JTextField txf2;
#Override
public void run() {
showGui();
}
#Override
public void actionPerformed(ActionEvent event) {
boolean visible;
String text;
String actionCommand = event.getActionCommand();
switch (actionCommand) {
case HIDE:
text = SHOW;
visible = false;
break;
case SHOW:
text = HIDE;
visible = true;
break;
default:
text = "???";
visible = false;
}
button.setText(text);
lbl2.setVisible(visible);
txf2.setVisible(visible);
}
private JPanel createButtonsPanel() {
JPanel buttonsPanel = new JPanel();
button = new JButton(SHOW);
button.addActionListener(this);
buttonsPanel.add(button);
return buttonsPanel;
}
private JScrollPane createForm() {
JPanel form = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
JLabel lbl1 = new JLabel("lbl1");
form.add(lbl1, gbc);
gbc.gridx = 1;
JTextField txf1 = new JTextField(6);
form.add(txf1, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
lbl2 = new JLabel("lbl2");
lbl2.setVisible(false);
form.add(lbl2, gbc);
gbc.gridx = 1;
txf2 = new JTextField(6);
txf2.setVisible(false);
form.add(txf2, gbc);
gbc.gridx = 0;
gbc.gridy = 2;
JLabel lbl3 = new JLabel("lbl3");
form.add(lbl3, gbc);
gbc.gridx = 1;
JTextField txf3 = new JTextField(6);
form.add(txf3, gbc);
return new JScrollPane(form,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
}
private void showGui() {
frame = new JFrame("Demo");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(createForm(), BorderLayout.CENTER);
frame.add(createButtonsPanel(), BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
/**
* Start here.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Demo2());
}
}
You should always try to use a layout manager. The code above uses GridBagLayout but there are several other layout managers that are good at handling forms, including GroupLayout and SpringLayout as well as third party layout managers like MiG Layout and FormLayout.
In order to "show" and "hide" the middle row in your form, simply set the visible property to true or false. If the text of the button is SHOW, then when the user clicks on it, I change the button text to HIDE and make lbl2 and txf2 both visible. If the button text is HIDE, then when the user clicks the button I change the text to SHOW and make lbl2 and txf2 not visible.
Because I use a layout manager, it handles resizing the JPanel whenever the contents of the JPanel are changed. When you don't use a layout manager, then you have to write code that handles the resizing and of-course your code does not, hence your problem.
Why GridLayot not working in Swing Java?
I need to place element at concrete cell, but they placing wrong (picture)
How to place elements to concrete cell in Java Swing with grid layout?
My code:
package com.KvaksManYT;
import javax.swing.*;
import java.awt.*;
public class GUI extends JFrame {
public GUI() {
super("Test");
setBounds(100, 100, 250, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container container = this.getContentPane();
container.setLayout(new GridLayout(3, 2, 2, 2));
container.add(but1, onPosition(1, 2));
container.add(but2, onPosition(2, 2));
container.add(but3, onPosition(1, 1));
container.add(but4, onPosition(2, 1));
}
private JButton but1 = new JButton("Press 1");
private JButton but2 = new JButton("Press 2");
private JButton but3 = new JButton("Press 3");
private JButton but4 = new JButton("Press 4");
private GridBagConstraints onPosition(int x, int y) {
GridBagConstraints layConstraints = new GridBagConstraints();
layConstraints.fill = GridBagConstraints.BOTH;
layConstraints.gridx = x;
layConstraints.gridy = y;
return layConstraints;
}
}
The GridBagConstraints is used for Grid Bag Layout, rather than Grid Layout.
You have to start counting at 0 too:
public class GUI extends JFrame {
public GUI() {
super("Test");
setBounds(100, 100, 250, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagConstraints layConstraints = new GridBagConstraints();
layConstraints.fill = GridBagConstraints.NONE;
layConstraints.insets = new Insets(3, 2, 2, 2);
Container container = this.getContentPane();
container.setLayout(new GridBagLayout());
container.add(but1, onPosition(0, 1, layConstraints));
container.add(but2, onPosition(1, 1, layConstraints));
container.add(but3, onPosition(0, 0, layConstraints));
container.add(but4, onPosition(1, 0, layConstraints));
}
when I compile and run my code everything seems to work fine except the JButton does not appear. I'm adding it to a JPanel that is on the frame. I'm new so I might not know what to lookout for here. Thanks!
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
public class TemperatureConverter extends JFrame{
//declarations
private JLabel celJLabel, farJLabel;
private JTextField celJTextField, farJTextField;
private JSlider sliderJSlider;
private JButton closeButton;
private TitledBorder border;
private JPanel topPanel, bottomPanel;
double celsiusDegrees, farenheitDegrees, sliderValue;
DecimalFormat decimalFormat = new DecimalFormat("#.0");
public TemperatureConverter()
{
createUserInterface();
}
public void createUserInterface()
{
//create the JFrame
Container frame = getContentPane();
frame.setBackground(Color.white);
frame.setLayout(null);
border = new TitledBorder("Convert between C & F");
border.setTitleColor(Color.black);
border.setTitleFont(new Font("Default", Font.ITALIC, 12));
border.setTitleJustification(TitledBorder.LEFT);
border.setTitlePosition(TitledBorder.TOP);
topPanel = new JPanel();
topPanel.setBounds(20,10,360,300);
topPanel.setForeground(Color.black);
topPanel.setBackground(Color.white);
topPanel.setLayout(null);
topPanel.setBorder(border);
frame.add(topPanel);
bottomPanel = new JPanel();
bottomPanel.setBounds(20,310,360,50);
bottomPanel.setForeground(Color.black);
bottomPanel.setBackground(Color.white);
bottomPanel.setLayout(null);
frame.add(bottomPanel);
celJLabel = new JLabel();
celJLabel.setBounds(120, 200, 60, 20);
celJLabel.setBackground(Color.white);
celJLabel.setFont(new Font("Default", Font.PLAIN, 12));
celJLabel.setText("Celcius");
celJLabel.setHorizontalAlignment(JLabel.LEFT);
topPanel.add(celJLabel);
farJLabel = new JLabel();
farJLabel.setBounds(120, 220, 60, 20);
farJLabel.setBackground(Color.white);
farJLabel.setFont(new Font("Default", Font.PLAIN, 12));
farJLabel.setText("Faranheit");
farJLabel.setHorizontalAlignment(JLabel.LEFT);
topPanel.add(farJLabel);
celJTextField = new JTextField();
celJTextField.setBounds(195,200, 50, 15);
celJTextField.setFont(new Font("Default", Font.PLAIN, 12));
celJTextField.setHorizontalAlignment(JTextField.CENTER);
celJTextField.setForeground(Color.black);
celJTextField.setBackground(Color.white);
topPanel.add(celJTextField);
farJTextField = new JTextField();
farJTextField.setBounds(195,225, 50, 15);
farJTextField.setFont(new Font("Default", Font.PLAIN, 12));
farJTextField.setHorizontalAlignment(JTextField.CENTER);
farJTextField.setForeground(Color.black);
farJTextField.setBackground(Color.white);
topPanel.add(farJTextField);
sliderJSlider = new JSlider(JSlider.HORIZONTAL, 0,100,0);
sliderJSlider.setBounds(20, 20, 310, 120);
sliderJSlider.setMajorTickSpacing(10);
sliderJSlider.setMinorTickSpacing(5);
sliderJSlider.setPaintTicks(true);
sliderJSlider.setPaintLabels(true);
sliderJSlider.setForeground(Color.black);
sliderJSlider.setBackground(Color.white);
topPanel.add(sliderJSlider);
sliderJSlider.addChangeListener(
new ChangeListener()
{
public void stateChanged(ChangeEvent event)
{
sliderStateChanged(event);
}
}
);
closeButton = new JButton();
closeButton.setBounds(140, 250, 75, 20);
closeButton.setFont(new Font("Default", Font.PLAIN,12));
closeButton.setText("Close");
closeButton.setForeground(Color.black);
closeButton.setBackground(Color.white);
bottomPanel.add(closeButton);
closeButton.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
closeActionPerformed(event);
}
}
);
setTitle("Temperature Converter");
setSize(400,400);
setVisible(true);
}
public static void main(String[] args)
{
TemperatureConverter application = new TemperatureConverter();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void sliderStateChanged(ChangeEvent event)
{
farenheitDegrees = sliderJSlider.getValue();
calculateCelsiusTemperature();
}
public void calculateCelsiusTemperature()
{
celsiusDegrees = (farenheitDegrees - 32)*5.0/9.0;
outputTemps();
}
public void outputTemps()
{
celJTextField.setText(decimalFormat.format(celsiusDegrees));
farJTextField.setText(decimalFormat.format(farenheitDegrees));
}
public void closeActionPerformed(ActionEvent event)
{
TemperatureConverter.this.dispose();
}
}
I'd follow the advice from the comments, use a proper layout manager.
The actual fault, is the placement of the close button within the bottom panel.
closeButton.setBounds(140, 250, 75, 20);
This might be a typo or a misunderstanding of the coordinate system, each new panel has its own private system where (0,0) is the top left of at component. The button is at (140, 250), however bottomPanel is only 360 x 50, so it is outside the visible bounds..
Try changing to
closeButton.setBounds(0, 0, 75, 20);
Your first and major mistake is this: topPanel.setLayout(null);. While null layouts and setBounds() might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.
The solution is simple: learn about and how to use the layout managers, and then use them. You can find links to the Swing tutorials including those for the layout managers and other Swing resources here: Swing Info
e.g.,
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.*;
public class TempConverter extends JPanel {
private static final int PREF_W = 400;
private static final int GAP = 5;
private JTextField celJTextField = new JTextField(10);
private JTextField farJTextField = new JTextField(10);
private JSlider sliderJSlider = new JSlider(0, 100, 0);
private JButton closeButton = new JButton("Close");
public TempConverter() {
sliderJSlider.setMajorTickSpacing(10);
sliderJSlider.setMinorTickSpacing(5);
sliderJSlider.setPaintTicks(true);
sliderJSlider.setPaintLabels(true);
JPanel textFieldPanel = new JPanel(new GridBagLayout());
textFieldPanel.add(new JLabel("Celcius:"), createGbc(0, 0));
textFieldPanel.add(celJTextField, createGbc(1, 0));
textFieldPanel.add(new JLabel("Faranheit:"), createGbc(0, 1));
textFieldPanel.add(farJTextField, createGbc(1, 1));
JPanel textFieldWrapperPanel = new JPanel(new GridBagLayout());
textFieldWrapperPanel.add(textFieldPanel);
JPanel conversionPanel = new JPanel(new BorderLayout());
conversionPanel.setBorder(BorderFactory.createTitledBorder("Foo"));
conversionPanel.setLayout(new BorderLayout());
conversionPanel.add(sliderJSlider, BorderLayout.PAGE_START);
conversionPanel.add(textFieldWrapperPanel, BorderLayout.CENTER);
JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
bottomPanel.add(closeButton);
setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
setLayout(new BorderLayout());
add(conversionPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
}
private GridBagConstraints createGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(GAP, GAP, GAP, GAP);
return gbc;
}
#Override
public Dimension getPreferredSize() {
Dimension superSize = super.getPreferredSize();
;
if (isPreferredSizeSet()) {
super.getPreferredSize();
}
int prefW = Math.max(PREF_W, superSize.width);
return new Dimension(prefW, superSize.height);
}
private static void createAndShowGui() {
TempConverter mainPanel = new TempConverter();
JFrame frame = new JFrame("TempConverter");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Now you might say that this looks more complicated, and perhaps it is, but what happens when you want to add another JTextField and JLabel to represent the Kelvin temperature scale? For your GUI, you'll need to resize the GUI and recalculate the position of any component that may be effected by adding the new components. For my GUI, you just need to add a few new lines, and the chance of the changes causing a bug in my code is much smaller than that of your changes. e.g. please note the changes below just require 3 lines of code. Everything else remains the same:
public class TempConverter extends JPanel {
private static final int PREF_W = 400;
private static final int GAP = 5;
private JTextField celJTextField = new JTextField(10);
private JTextField farJTextField = new JTextField(10);
private JTextField KelvinJTextField = new JTextField(10); // !!! Added
private JSlider sliderJSlider = new JSlider(0, 100, 0);
private JButton closeButton = new JButton("Close");
public TempConverter() {
sliderJSlider.setMajorTickSpacing(10);
sliderJSlider.setMinorTickSpacing(5);
sliderJSlider.setPaintTicks(true);
sliderJSlider.setPaintLabels(true);
JPanel textFieldPanel = new JPanel(new GridBagLayout());
textFieldPanel.add(new JLabel("Celcius:"), createGbc(0, 0));
textFieldPanel.add(celJTextField, createGbc(1, 0));
textFieldPanel.add(new JLabel("Faranheit:"), createGbc(0, 1));
textFieldPanel.add(farJTextField, createGbc(1, 1));
// !!! added
textFieldPanel.add(new JLabel("Kelvin:"), createGbc(0, 2));
textFieldPanel.add(KelvinJTextField, createGbc(1, 2));
Been trying to make 4 JPanels two on top and other 2 on the bottom and manipulate each independently of each other inputing text etc...beginner with java so if anybody can help me out that would be awesome. I posted another question before but now I am stuck again. lol
package project2;
import javax.swing.JOptionPane;
import java.awt.FlowLayout; // specifies how components are arranged
import javax.swing.JFrame; // provides basic window features
import javax.swing.JLabel; // displays text and images
import javax.swing.JPanel; // Displays a Panel
import javax.swing.SwingConstants; // common constants used with Swing
import javax.swing.Icon; // interface used to manipulate images
import javax.swing.ImageIcon; // loads images
import java.awt.Color;
import java.awt.CardLayout;
import java.awt.BorderLayout;
import javax.swing.*;
import java.awt.Container;
import java.awt.Dimension;
public class GUI
{
private JPanel Checks; //Panel to Hold Checks
private JPanel Transactions;
private JPanel History;
private JPanel Graphics;
private JLabel CLabel;
public void displayGUI()
{
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel(
new GridLayout(2, 2, 5, 5));
contentPane.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
Checks = getPanel(Color.YELLOW.darker().darker());
Transactions = getPanel(Color.RED);
History = getPanel(Color.GREEN.darker().darker());
Graphics = getPanel(Color.MAGENTA);
CLabel = new JLabel("Label with on red text");
contentPane.add(Checks);
contentPane.add(Transactions);
contentPane.add(History);
contentPane.add(Graphics);
frame.setSize(1400,690); //set frame size
frame.setVisible(true); //display frame
frame.setContentPane(contentPane);
}
private JPanel getPanel(Color bColor) {
JPanel panel = new JPanel();
panel.setOpaque(true);
panel.setBackground(bColor);
return panel;
}
Expected Output :
Please have a look at this answer, and see if you need this or something else. Do let us know, we might try to add a bit more deeper.
import java.awt.*;
import java.util.Random;
import javax.swing.*;
/**
* Created with IntelliJ IDEA.
* User: Gagandeep Bali
* Date: 9/30/13
* Time: 6:02 PM
* To change this template use File | Settings | File Templates.
*/
public class UTBInCheck {
private JPanel contentPane;
private JPanel topLeftPanel;
private GridBagConstraints gbc;
private JTextArea infoArea;
private JScrollPane infoScroller;
private JTextField payOrderField;
private JTextField amountField;
private JButton orderSubmitButton;
private JButton orderClearButton;
private JPanel topRightPanel;
private JTextArea recentTransArea;
private JScrollPane recentTransScroller;
private JButton updateButton;
private JPanel bottomLeftPanel;
private JTextField atmWithdrawalField;
private JTextField atmDepositField;
private JTextField directDepositField;
private JTextField wireTransferField;
private JTextField electronicBillField;
private JTextField bankFeeField;
private JButton etSubmitButton;
private JButton etClearButton;
private JPanel bottomRightPanel;
private Random random;
private static final int GAP = 5;
private int checkNumber;
public UTBInCheck() {
random = new Random();
gbc = new GridBagConstraints();
gbc.insets = new Insets(GAP, GAP, GAP, GAP);
checkNumber = 811;
}
private void displayGUI() {
JFrame frame = new JFrame("University of Texas at Brownsville");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
contentPane = getPanel();
contentPane.setBorder(
BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
contentPane.setLayout(new GridLayout(2, 2, GAP, GAP));
topLeftPanel = getPanel();
setTopLeftPanel(topLeftPanel);
topRightPanel = getPanel();
setTopRightPanel(topRightPanel);
bottomLeftPanel = getPanel();
setBottomLeftPanel(bottomLeftPanel);
bottomRightPanel = getPanel();
contentPane.add(topLeftPanel);
contentPane.add(topRightPanel);
contentPane.add(bottomLeftPanel);
contentPane.add(bottomRightPanel);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private void setTopLeftPanel(JPanel panel) {
panel.setBorder(
BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
panel.setLayout(new BorderLayout(GAP, GAP));
JPanel topPanel = getPanel();
topPanel.setLayout(new GridBagLayout());
JLabel universityLabel = getLabel("University of Texas at Brownsville");
addComp(topPanel, universityLabel, 0, 0, 1, 1, 0.5, 0.2,
GridBagConstraints.HORIZONTAL, GridBagConstraints.NORTHWEST);
JLabel checkNumberLabel = getLabel("Check Number : " + checkNumber);
addComp(topPanel, checkNumberLabel, 1, 0, 1, 1, 0.5, 0.2,
GridBagConstraints.HORIZONTAL, GridBagConstraints.NORTHEAST);
infoArea = new JTextArea(5, 10);
infoArea.setLineWrap(true);
infoArea.setWrapStyleWord(true);
infoScroller = new JScrollPane();
infoScroller.setViewportView(infoArea);
addComp(topPanel, infoScroller, 0, 1, 2, 1, 1.0, 0.4,
GridBagConstraints.BOTH, GridBagConstraints.WEST);
JPanel centerPanel = getPanel();
centerPanel.setBorder(
BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
centerPanel.setLayout(new GridLayout(0, 2, GAP, GAP));
JLabel payOrderLabel = getLabel("Pay to the order of : ");
payOrderField = new JTextField(10);
JLabel amountLabel = getLabel("Amount : ");
amountField = new JTextField(10);
JLabel chrisBankLabel = getLabel("Cris' Bank");
JPanel buttonPanel = getPanel();
buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER, GAP, GAP));
orderSubmitButton = new JButton("Submit");
orderClearButton = new JButton("Clear");
buttonPanel.add(orderSubmitButton);
buttonPanel.add(orderClearButton);
centerPanel.add(payOrderLabel);
centerPanel.add(payOrderField);
centerPanel.add(amountLabel);
centerPanel.add(amountField);
centerPanel.add(chrisBankLabel);
centerPanel.add(buttonPanel);
addComp(topPanel, centerPanel, 0, 2, 2, 1, 1.0, 0.4,
GridBagConstraints.BOTH, GridBagConstraints.SOUTHWEST);
panel.add(topPanel, BorderLayout.CENTER);
}
private void addComp(JPanel panel, JComponent comp,
int gridx, int gridy, int gridwidth, int gridheight,
double weightx, double weighty, int fill, int anchor) {
gbc.gridx = gridx;
gbc.gridy = gridy;
gbc.gridwidth = gridwidth;
gbc.gridheight = gridheight;
gbc.weightx = weightx;
gbc.weighty = weighty;
gbc.fill = fill;
gbc.anchor = anchor;
panel.add(comp, gbc);
}
private void setTopRightPanel(JPanel panel) {
panel.setBorder(BorderFactory.createTitledBorder("Recent Transactions"));
panel.setLayout(new BorderLayout(GAP, GAP));
recentTransArea = new JTextArea(10, 10);
recentTransArea.setLineWrap(true);
recentTransArea.setWrapStyleWord(true);
recentTransScroller = new JScrollPane();
recentTransScroller.setViewportView(recentTransArea);
JPanel buttonPanel = getPanel();
updateButton = new JButton("Update");
buttonPanel.add(updateButton);
panel.add(recentTransScroller, BorderLayout.CENTER);
panel.add(buttonPanel, BorderLayout.PAGE_END);
}
private void setBottomLeftPanel(JPanel panel) {
panel.setBorder(
BorderFactory.createTitledBorder("Electronic Transactions"));
panel.setLayout(new GridLayout(0, 2, GAP, GAP));
JLabel atmWithdrawLabel = getLabel("ATM Withdrawals : ");
atmWithdrawalField = new JTextField(10);
JLabel atmdepositLabel = getLabel("ATM Deposit : ");
atmDepositField = new JTextField(10);
JLabel directDepositLabel = getLabel("Direct Deposit : ");
directDepositField = new JTextField(10);
JLabel wireTransferLabel = getLabel("Wire Transfers : ");
wireTransferField = new JTextField(10);
JLabel electronicBillLabel = getLabel("Electronic Bills : ");
electronicBillField = new JTextField(10);
JLabel bankFeeLabel = getLabel("Bank Fees : ");
bankFeeField = new JTextField(10);
JPanel buttonPanel = getPanel();
buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER, GAP, GAP));
etSubmitButton = new JButton("Submit");
etClearButton = new JButton("Clear");
buttonPanel.add(etSubmitButton);
buttonPanel.add(etClearButton);
panel.add(atmWithdrawLabel);
panel.add(atmWithdrawalField);
panel.add(atmdepositLabel);
panel.add(atmDepositField);
panel.add(directDepositLabel);
panel.add(directDepositField);
panel.add(wireTransferLabel);
panel.add(wireTransferField);
panel.add(electronicBillLabel);
panel.add(electronicBillField);
panel.add(bankFeeLabel);
panel.add(bankFeeField);
//Adding JPanel just to occupy space;
panel.add(getPanel());
panel.add(buttonPanel);
}
private JLabel getLabel(String text) {
return (new JLabel(text, JLabel.LEFT));
}
private JPanel getPanel() {
JPanel panel = new JPanel();
panel.setOpaque(true);
panel.setBackground(getRandomColor());
/*panel.setBorder(
BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));*/
return panel;
}
private Color getRandomColor() {
return (new Color(random.nextInt(256),
random.nextInt(256), random.nextInt(256)));
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new UTBInCheck().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
OUTPUT :