how to edit awt textfield via code - java

I can't find out how to change text in my AWT textboxes. I already tried this:
textBox1.setText("text");
textBox1.validate();
or
textBox1.setText("text");
textBox1.repaint();
None of them works. What could be this issue?

Look this example how I am setting text to text field
import java.awt.*;
import java.awt.event.*;
public class AwtControlDemo {
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public AwtControlDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showTextFieldDemo();
}
private void prepareGUI(){
mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showTextFieldDemo(){
headerLabel.setText("Control in action: TextField");
Label namelabel= new Label("User ID: ", Label.CENTER);
final TextField userText = new TextField(16);
userText.setText("name");
Button displayButton = new Button("Display");
displayButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Username: " + userText.getText();
statusLabel.setText(data);
}
});
controlPanel.add(namelabel);
controlPanel.add(userText);
controlPanel.add(displayButton);
mainFrame.setVisible(true);
}
}

Related

How can I transfer data between one jframe to another jframe?

I'm new to java and for some reason I don't know any other way to transfer the data from another frame after pressing submit. For example, it will show the output frame the label and textfield that the user wrote in the first frame like this "Name: "user's name". If you do know please post the code I should put, thank you!
package eventdriven;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class EventDriven extends JFrame {
JPanel items = new JPanel();
JLabel fName = new JLabel("First Name: ");
JLabel lName = new JLabel("Last Name: ");
JLabel mName = new JLabel("Middle Name: ");
JLabel mNum = new JLabel("Mobile Number: ");
JLabel eAdd = new JLabel("Email Address: ");
JTextField fname = new JTextField(15);
JTextField lname = new JTextField(15);
JTextField mname = new JTextField(15);
JTextField mnum = new JTextField(15);
JTextField eadd = new JTextField(15);
JButton submit = new JButton("Submit");
JButton clear = new JButton("Clear All");
JButton okay = new JButton("Okay");
JTextArea infos;
JFrame output;
public EventDriven()
{
this.setTitle("INPUT");
this.setResizable(false);
this.setSize(230, 300);
this.setLocation(300, 300);
this.setLayout(new FlowLayout(FlowLayout.CENTER));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(fName);
this.add(fname);
this.add(lName);
this.add(lname);
this.add(mName);
this.add(mname);
this.add(mNum);
this.add(mnum);
this.add(eAdd);
this.add(eadd);
submit.addActionListener(new btnSubmit());
this.add(submit);
clear.addActionListener(new btnClearAll());
this.add(clear);
okay.addActionListener(new btnOkay());
this.add(items);
this.setVisible(true);
}
class btnSubmit implements ActionListener{
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == submit)
{
submit.setEnabled(false);
output = new JFrame("OUTPUT");
output.show();
output.setSize(300,280);
output.setTitle("OUTPUT");
output.add(okay);
output.setLayout(new FlowLayout(FlowLayout.CENTER));
}
}
}
class btnClearAll implements ActionListener{
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == clear)
{
fname.setText(null);
lname.setText(null);
mname.setText(null);
mnum.setText(null);
eadd.setText(null);
submit.setEnabled(true);
output.dispose();
}
}
}
class btnOkay implements ActionListener{
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == okay)
{
fname.setText(null);
lname.setText(null);
mname.setText(null);
mnum.setText(null);
eadd.setText(null);
submit.setEnabled(true);
output.dispose();
}
}
}
public static void main(String[] args)
{
EventDriven window = new EventDriven();
}
}
It's not clear what problem you are having displaying a value from one field in another frame. But here's an example of doing that (with fields reduced to just one for demonstration):
public class EventDriven extends JFrame {
private final JTextField nameField = new JTextField(15);
private final JButton submit = new JButton("Submit");
private final JButton clear = new JButton("Clear All");
public EventDriven() {
setTitle("Input");
setLayout(new FlowLayout(FlowLayout.CENTER));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new JLabel("Name: "));
add(nameField);
submit.addActionListener(this::showOutput);
add(submit);
clear.addActionListener(this::clearInput);
add(clear);
pack();
}
private void showOutput(ActionEvent ev) {
submit.setEnabled(false);
JDialog output = new JDialog(EventDriven.this, "Output", true);
output.add(new Label("Name: " + nameField.getText()), BorderLayout.CENTER);
JButton okButton = new JButton("OK");
output.add(okButton, BorderLayout.SOUTH);
okButton.addActionListener(bv -> output.setVisible(false));
output.pack();
output.setVisible(true);
}
private void clearInput(ActionEvent ev) {
nameField.setText(null);
submit.setEnabled(true);
}
public static void main(String[] args) {
EventDriven window = new EventDriven();
window.setVisible(true);
}
}
You will also see that I've simplified your action listeners to demonstrate an easier way to respond to user driven event.s

Fails to display label and text field in Swing

I just started learning Swing with a simple code to create login form.
package swingbeginner;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class LoginForm {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel inputLabel;
private JPanel inputPanel;
private JPanel controlPanel;
private JLabel statusLabel;
public LoginForm() {
prepareGUI();
}
public static void main(String[] args) {
LoginForm loginForm = new LoginForm();
loginForm.loginProcess();
}
private void prepareGUI() {
mainFrame = new JFrame("Login");
mainFrame.setSize(600, 600);
mainFrame.setLayout(new FlowLayout());
headerLabel = new JLabel("",JLabel.CENTER );
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent) {
}
});
inputLabel = new JLabel();
inputLabel.setLayout(null);
inputPanel = new JPanel();
inputPanel.setLayout(null);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(inputLabel);
mainFrame.add(inputPanel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void loginProcess() {
headerLabel.setText("Please Login to Continue!");
JLabel usernameLabel = new JLabel("Username");
usernameLabel.setBounds(10,20,80,25);
JLabel passwordLabel = new JLabel("Password");
passwordLabel.setBounds(10, 20, 80, 25);
JTextField usernameTextbox = new JTextField();
usernameTextbox.setBounds(100,20,165,25);
JPasswordField passwordTextbox = new JPasswordField();
passwordTextbox.setBounds(100,20,165,25);
JButton loginButton = new JButton("Login");
JButton cancelButton = new JButton("Cancel");
loginButton.setActionCommand("Login");
cancelButton.setActionCommand("Cancel");
loginButton.addActionListener(new ButtonClickListener());
cancelButton.addActionListener(new ButtonClickListener());
inputLabel.add(usernameLabel);
inputPanel.add(usernameTextbox);
inputLabel.add(passwordLabel);
inputPanel.add(passwordTextbox);
controlPanel.add(loginButton);
controlPanel.add(cancelButton);
mainFrame.setVisible(true);
}
private class ButtonClickListener implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
String command = actionEvent.getActionCommand();
if(command.equals("Login")) {
statusLabel.setText("Logging In");
}
else if(command.equals("Cancel")) {
statusLabel.setText("Login Cancelled");
}
}
}
}
My code displays header along with Login and Cancel button. But the Labels/Text field (Username and Password) are not been displayed in the panel.
Where am I going wrong?
since everyone is missing the fact of the null layout ill create an answer myself.
inputPanel.setLayout(null);
if you add components to this, you will have to specify the position or you simply use a layoutmanager like BorderLayout or FlowLayout.
inputPanel.setLayout(new FlowLayout());
if you use this you will be able to simply add the components to the JPanel. Also as stated in the other answers, don't add JLabels to other JLables, because the most top one will override the others. With that being said a solution code which should work would looks like this:
public class LoginForm {
private JFrame mainFrame;
private JLabel headerLabel;
private JPanel inputPanel;
private JPanel controlPanel;
private JLabel statusLabel;
public LoginForm() {
prepareGUI();
}
public static void main(String[] args) {
LoginForm loginForm = new LoginForm();
loginForm.loginProcess();
}
private void prepareGUI() {
mainFrame = new JFrame("Login");
mainFrame.setSize(600, 600);
mainFrame.setLayout(new FlowLayout());
headerLabel = new JLabel("",JLabel.CENTER );
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent) {
}
});
//changes here
inputPanel = new JPanel();
inputPanel.setLayout(new FlowLayout());
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(inputLabel);
mainFrame.add(inputPanel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void loginProcess() {
headerLabel.setText("Please Login to Continue!");
JLabel usernameLabel = new JLabel("Username");
usernameLabel.setBounds(10,20,80,25);
JLabel passwordLabel = new JLabel("Password");
passwordLabel.setBounds(10, 20, 80, 25);
JTextField usernameTextbox = new JTextField();
usernameTextbox.setBounds(100,20,165,25);
JPasswordField passwordTextbox = new JPasswordField();
passwordTextbox.setBounds(100,20,165,25);
JButton loginButton = new JButton("Login");
JButton cancelButton = new JButton("Cancel");
loginButton.setActionCommand("Login");
cancelButton.setActionCommand("Cancel");
loginButton.addActionListener(new ButtonClickListener());
cancelButton.addActionListener(new ButtonClickListener());
inputPanel.add(usernameLabel); //changes here
inputPanel.add(usernameTextbox);
inputPanel.add(passwordLabel); //changes here
inputPanel.add(passwordTextbox);
controlPanel.add(loginButton);
controlPanel.add(cancelButton);
mainFrame.setVisible(true);
}
private class ButtonClickListener implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
String command = actionEvent.getActionCommand();
if(command.equals("Login")) {
statusLabel.setText("Logging In");
}
else if(command.equals("Cancel")) {
statusLabel.setText("Login Cancelled");
}
}
}
}
Here is your solution:
package swingbeginner;
public class LoginForm {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel inputLabel;
private JPanel inputPanel;
private JPanel controlPanel;
private JLabel statusLabel;
public LoginForm() {
prepareGUI();
}
public static void main(String[] args) {
LoginForm loginForm = new LoginForm();
loginForm.loginProcess();
}
private void prepareGUI() {
mainFrame = new JFrame("Login");
mainFrame.setSize(600, 600);
mainFrame.setLayout(new BorderLayout());
headerLabel = new JLabel("header", JLabel.CENTER);
statusLabel = new JLabel("status", JLabel.CENTER);
statusLabel.setSize(350, 100);
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent) {
}
});
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 100, 100));
mainFrame.add(headerLabel, BorderLayout.NORTH);
mainFrame.add(controlPanel, BorderLayout.CENTER);
mainFrame.add(statusLabel, BorderLayout.SOUTH);
mainFrame.setVisible(true);
}
private void loginProcess() {
headerLabel.setText("Please Login to Continue!");
JLabel usernameLabel = new JLabel("Username");
usernameLabel.setBounds(10, 20, 80, 25);
JLabel passwordLabel = new JLabel("Password");
passwordLabel.setBounds(10, 20, 80, 25);
JTextField usernameTextbox = new JTextField(20);
usernameTextbox.setBounds(100, 20, 165, 25);
JPasswordField passwordTextbox = new JPasswordField(20);
passwordTextbox.setBounds(100, 20, 165, 25);
JButton loginButton = new JButton("Login");
JButton cancelButton = new JButton("Cancel");
loginButton.setActionCommand("Login");
cancelButton.setActionCommand("Cancel");
loginButton.addActionListener(new ButtonClickListener());
cancelButton.addActionListener(new ButtonClickListener());
controlPanel.add(usernameLabel);
controlPanel.add(usernameTextbox);
controlPanel.add(passwordLabel);
controlPanel.add(passwordTextbox);
controlPanel.add(loginButton);
controlPanel.add(cancelButton);
mainFrame.setVisible(true);
}
private class ButtonClickListener implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
String command = actionEvent.getActionCommand();
if (command.equals("Login")) {
statusLabel.setText("Logging In");
}
else if (command.equals("Cancel")) {
statusLabel.setText("Login Cancelled");
}
}
}
}
You are adding usernameLabel and passwordLabel onto another label inputLabel. [When stacking labels, the topmost label will overwrite and those labels will disappear.] (JLabel on top of another JLabel)! Why don't you add all the labels and fields directly to the mainFrame i.e. the JFrame object?
You are adding Labels/Textfield(Username and Password) to inputLabel which is an instance of JLabel which is not of type of a container.
Change
inputLabel.add(usernameLabel);
inputPanel.add(usernameTextbox);
inputLabel.add(passwordLabel);
inputPanel.add(passwordTextbox);
to
controlPanel.add(usernameLabel);
controlPanel.add(usernameTextbox);
controlPanel.add(passwordLabel);
controlPanel.add(passwordTextbox);
Also give JTextField a default size, so change
JTextField usernameTextbox = new JTextField();
JPasswordField passwordTextbox = new JPasswordField();
to
JTextField usernameTextbox = new JTextField(20);
JPasswordField passwordTextbox = new JPasswordField(20);
Or you can change the type of inputLabel variable to JPanel and set it a layout like FlowLayout.
In this case no need to use setBounds method on components.
Note: that you use the same bounds for multiple components which will make them one on top of another.

Get text field information from one class and show it on a JTextArea on another class

I have a class BasicInfoWindow that gets the user information such as name, address, etc. I then have another class ReviewandSubmit where it show the the texts the user entered from BasicInfoWindow in the JTextArea. I am using card layout to switch between each panel. I am not sure how to send the info from BasicInfoWindow and receive it from ReviewandSubmit. Here is my code so far:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main extends JPanel
{
private static void createAndShowGUI()
{
final Main test = new Main();
JPanel buttonPanel = new JPanel(new BorderLayout());
JPanel southPanel = new JPanel();
buttonPanel.add(southPanel, BorderLayout.SOUTH);
final JButton btnNext = new JButton("NEXT");
final JButton btnPrev = new JButton("PREVIOUS");
buttonPanel.add(btnNext, BorderLayout.EAST);
buttonPanel.add(btnPrev, BorderLayout.WEST);
btnNext.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
test.nextCard();
}
});
btnPrev.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
test.prevCard();
}
});
JFrame frame = new JFrame("Employment Application");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(test);
frame.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
//frame.setSize(750,500);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
}
public static void main(String [] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
createAndShowGUI();
}
});
}
private CardLayout cardLayout = new CardLayout();
private JPanel cardShowingPanel = new JPanel(cardLayout);
public Main()
{
BasicInfoWindow window1 = new BasicInfoWindow();
cardShowingPanel.add(window1, "1");
EmploymentHistoryWindow window2 = new EmploymentHistoryWindow();
cardShowingPanel.add(window2, "2");
EducationAndAvailbleWindow window3 = new EducationAndAvailbleWindow();
cardShowingPanel.add(window3, "3");
ReviewAndSubmitWindow window4 = new ReviewAndSubmitWindow();
cardShowingPanel.add(window4, "4");
setLayout(new BorderLayout());
add(cardShowingPanel, BorderLayout.CENTER);
}
public void nextCard()
{
cardLayout.next(cardShowingPanel);
}
public void prevCard()
{
cardLayout.previous(cardShowingPanel);
}
public void showCard(String key)
{
cardLayout.show(cardShowingPanel, key);
}
}
BasicInfo Class
ommitted some methods
public class BasicInfoWindow extends JPanel
{
private JTextField txtName, txtAddress, txtCity, txtState, txtZipCode, txtPhoneNumber, txtEmail;
private JComboBox cbDate, cbYear, cbMonth;
private JLabel labelName, labelAddress, labelCity, labelState, labelZipCode, labelPhoneNumber, labelEmail, labelDOB;
private JButton btnClear;
public BasicInfoWindow()
{
createView();
}
private void createView()
{
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
add(panel);
northPanel(panel);
centerPanel(panel);
southPanel(panel);
}
public ArrayList<HiringPersonInfo> sendInfo()
{
String name = txtName.getText();
String address = txtAddress.getText();
String city = txtCity.getText();
String state = txtState.getText();
String zip = txtZipCode.getText();
String phone = txtPhoneNumber.getText();
String email = txtEmail.getText();
String DOB = cbMonth.getSelectedItem() + " " + cbDate.getSelectedItem() + " " + cbYear.getSelectedItem();
HiringPersonInfo addNewInfo = new HiringPersonInfo(name, address, city, state, zip, phone, email, DOB);
ArrayList<HiringPersonInfo> personInfo = new ArrayList();
personInfo.add(addNewInfo);
return personInfo;
}
ReviewAndSubmit class
public class ReviewAndSubmitWindow extends JPanel
{
private JButton btnSubmit;
public ReviewAndSubmitWindow()
{
createView();
}
private void createView()
{
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
add(panel);
northPanel(panel);
centerPanel(panel);
southPanel(panel);
}
private void northPanel(JPanel panel)
{
JPanel northPanel = new JPanel();
panel.add(northPanel, BorderLayout.NORTH);
JLabel labelMessage = new JLabel("Review and Submit");
labelMessage.setFont(new Font("Serif", Font.BOLD, 25));
northPanel.add(labelMessage, BorderLayout.CENTER);
}
private void centerPanel(JPanel panel)
{
JPanel centerPanel = new JPanel();
JTextArea showReview = new JTextArea();
showReview.setLineWrap(true);
showReview.setWrapStyleWord(true);
showReview.setEditable(false);
JScrollPane scrollPane = new JScrollPane(showReview);
scrollPane.setPreferredSize(new Dimension(600, 385));
centerPanel.add(scrollPane, BorderLayout.CENTER);
BasicInfoWindow getInfo = new BasicInfoWindow();
showReview.append(getInfo.sendInfo().toString());
panel.add(centerPanel);
}
private void southPanel(JPanel panel)
{
JPanel southPanel = new JPanel();
panel.add(southPanel, BorderLayout.SOUTH);
btnSubmit = new JButton("SUBMIT");
// creates a new file
southPanel.add(btnSubmit);
}
}
You could use a Singleton Pattern in the HiringPersonInfo class to instantiate one instance of the class and then during the submit you could add that instance of that class to an ArrayList.
Singleton Patterns can be used to create one instance of the object that can be shared by all the classes in that package. You can think of it like a "global" variable in a way for OOP.

Open new window in swing - Contents not visible

I am completely new to programming: I have two classes in my Java Swing application, and when I press the button a new window opens, but only the frame is visible and not the content of the frame.
I appreciate any help.
The first class:
public class Learning {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public Learning(){
prepareGUI();
}
public static void main(String[] args) {
Learning swingControlDemo = new Learning();
swingControlDemo.showEventDemo();
}
private void prepareGUI() {
mainFrame = new JFrame("software component architecture quizess");
mainFrame.setSize(600,400);
mainFrame.setLayout(new GridLayout(3, 1));
headerLabel = new JLabel("",JLabel.CENTER );
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showEventDemo() {
headerLabel.setText("Learning invironment for CBSC and SOA");
JButton okButton = new JButton("Drag and Drop");
JButton submitButton = new JButton("multiple choice quizess");
JButton cancelButton = new JButton("true false quizzes");
JButton newButton = new JButton("Component Description Language");
okButton.setActionCommand("Drag and Drop");
submitButton.setActionCommand("multiple choice quizess");
cancelButton.setActionCommand("true false quizzes");
newButton.setActionCommand("true false quizzes");
controlPanel.add(okButton);
controlPanel.add(submitButton);
controlPanel.add(cancelButton);
controlPanel.add(newButton);
mainFrame.setVisible(true);
newButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
mainFrame.dispose();
new DLC1();
}
});
}
}
And the second class:
public class DLC1 {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
private JLabel msglabel;
public DLC1(){
prepareGUI();
}
public static void main(String[] args){
DLC1 swingLayoutDemo = new DLC1();
swingLayoutDemo.showBorderLayoutDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("component description language");
mainFrame.setSize(600,400);
mainFrame.setLayout(new GridLayout(3, 1));
headerLabel = new JLabel("",JLabel.CENTER );
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showBorderLayoutDemo(){
headerLabel.setText("Layout in action: BorderLayout");
JPanel panel = new JPanel();
panel.setBackground(Color.darkGray);
panel.setSize(300,300);
BorderLayout layout = new BorderLayout();
layout.setHgap(10);
layout.setVgap(10);
panel.setLayout(layout);
panel.add(new JButton("dlgggggggggc"),BorderLayout.CENTER);
panel.add(new JButton("Line Start"),BorderLayout.LINE_START);
panel.add(new JButton("Line End"),BorderLayout.LINE_END);
panel.add(new JButton("East"),BorderLayout.EAST);
panel.add(new JButton("West"),BorderLayout.WEST);
panel.add(new JButton("North"),BorderLayout.NORTH);
panel.add(new JButton("South"),BorderLayout.SOUTH);
controlPanel.add(panel);
mainFrame.setVisible(true);
}
}

Java grid layout GUI - how to enter new pane on event?

How can I set a button to link to a completely different grid pane? If I click the JButton "More options" for example, I want it to link me to a new page with more JButton options. Right now, everything is static.
The program right now just calculates the area of a rectangle given an length and width when you press "Calculate." The grid layout is 4 x 2, denoted by JLabel, JTextField, and JButton listed below.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class RectangleProgram extends JFrame
{
private static final int WIDTH = 400;
private static final int HEIGHT = 300;
private JLabel lengthL, widthL, areaL;
private JTextField lengthTF, widthTF, areaTF;
private JButton calculateB, exitB;
//Button handlers:
private CalculateButtonHandler cbHandler;
private ExitButtonHandler ebHandler;
public RectangleProgram()
{
lengthL = new JLabel("Enter the length: ", SwingConstants.RIGHT);
widthL = new JLabel("Enter the width: ", SwingConstants.RIGHT);
areaL = new JLabel("Area: ", SwingConstants.RIGHT);
lengthTF = new JTextField(10);
widthTF = new JTextField(10);
areaTF = new JTextField(10);
//SPecify handlers for each button and add (register) ActionListeners to each button.
calculateB = new JButton("Calculate");
cbHandler = new CalculateButtonHandler();
calculateB.addActionListener(cbHandler);
exitB = new JButton("Exit");
ebHandler = new ExitButtonHandler();
exitB.addActionListener(ebHandler);
setTitle("Sample Title: Area of a Rectangle");
Container pane = getContentPane();
pane.setLayout(new GridLayout(4, 2));
//Add things to the pane in the order you want them to appear (left to right, top to bottom)
pane.add(lengthL);
pane.add(lengthTF);
pane.add(widthL);
pane.add(widthTF);
pane.add(areaL);
pane.add(areaTF);
pane.add(calculateB);
pane.add(exitB);
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private class CalculateButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double width, length, area;
length = Double.parseDouble(lengthTF.getText()); //We use the getText & setText methods to manipulate the data entered into those fields.
width = Double.parseDouble(widthTF.getText());
area = length * width;
areaTF.setText("" + area);
}
}
public class ExitButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
public static void main(String[] args)
{
RectangleProgram rectObj = new RectangleProgram();
}
}
You can use CardLayout. It allows the two or more components share the same display space.
Here is a simple example
public class RectangleProgram {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Area of a Rectangle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField lengthField = new JTextField(10);
JTextField widthField = new JTextField(10);
JTextField areaField = new JTextField(10);
JButton calculateButton = new JButton("Calculate");
JButton exitButton = new JButton("Exit");
final JPanel content = new JPanel(new CardLayout());
JButton optionsButton = new JButton("More Options");
optionsButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
CardLayout cardLayout = (CardLayout) content.getLayout();
cardLayout.next(content);
}
});
JPanel panel = new JPanel(new GridLayout(0, 2)) {
#Override
public Dimension getPreferredSize() {
return new Dimension(250, 100);
}
};
panel.add(new JLabel("Enter the length: ", JLabel.RIGHT));
panel.add(lengthField);
panel.add(new JLabel("Enter the width: ", JLabel.RIGHT));
panel.add(widthField);
panel.add(new JLabel("Area: ", JLabel.RIGHT));
panel.add(areaField);
panel.add(calculateButton);
panel.add(exitButton);
JPanel optionsPanel = new JPanel();
optionsPanel.add(new JLabel("Options", JLabel.CENTER));
content.add(panel, "Card1");
content.add(optionsPanel, "Card2");
frame.add(content);
frame.add(optionsButton, BorderLayout.PAGE_END);
frame.pack();
frame.setVisible(true);
}
});
}
}
Read How to Use CardLayout

Categories

Resources