getActionCommand not working in code (watching tutorial series) - java

I'm watching a youtube tutorial series by mybringback. (38th video in the series). At the very bottom of the code, I have e.getactioncommand. When I click on the radio button, I want it to say something in the text field. For instance when I hit radio button 1, it should say "you selected radio button 1" in the text field. I followed the tutorial exactly, but I can't figure out what's wrong.
I have the driver class as well. that i didn't post here.
Here;s the video https://www.youtube.com/watch?v=pjS_IiNp008&list=SPDAA5DE54FB5215EC
package ActionCommandnActionListeners;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class FirstWindow extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
String s;
JCheckBox cb, cb2;
JTextField textField;
JLabel label;
JRadioButton b1, b2, b3, b4;
ButtonGroup group;
JTextArea tb;
public FirstWindow() {
super("Your Computer is very special");
setSize(600, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel p = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel(new GridBagLayout());
JPanel p4 = new JPanel();
b1 = new JRadioButton("Choice 1");
b1.setActionCommand("you selected num1");
b1.addActionListener(this);
b2 = new JRadioButton("Choice 2");
b2.setActionCommand("you selected num2");
b2.addActionListener(this);
b3 = new JRadioButton("Choice 3");
b3.setActionCommand("you selected num3");
b3.addActionListener(this);
b4 = new JRadioButton("Choice 4");
b4.setActionCommand("you selected num4");
b4.addActionListener(this);
group = new ButtonGroup();
group.add(b1);
group.add(b2);
group.add(b3);
group.add(b4);
p4.add(b1);
p4.add(b2);
p4.add(b3);
p4.add(b4);
JButton b = new JButton("Button 1");
JButton c = new JButton("Button 2");
p.add(b);
p.add(c);
cb = new JCheckBox("Do you LOVE bacon?");
cb2 = new JCheckBox("Do you LOVE cheese?");
p2.add(cb);
p2.add(cb2);
label = new JLabel("This is a label");
JTextArea tb = new JTextArea("This is a text area");
textField = new JTextField("text field");
c.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String s2 = textField.getText();
label.setText(s2);
}
});
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(15, 15, 15, 15);
gbc.gridx = 0;
gbc.gridy = 0;
p3.add(label, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
p3.add(tb, gbc);
gbc.gridx = 0;
gbc.gridy = 2;
p3.add(textField, gbc);
add(p, BorderLayout.SOUTH);
add(p2, BorderLayout.NORTH);
add(p3, BorderLayout.CENTER);
add(p4, BorderLayout.WEST);
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
s = "Good job kid, you harvested your corn! \n";
if (cb.isSelected()) {
s += " And of course you love bacon! \n";
}
if (cb2.isSelected()) {
s += " Most naturally you love cheese! \n";
}
JOptionPane.showMessageDialog(null, s);
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
tb.setText(e.getActionCommand());
}
}

JTextArea tb = new JTextArea("This is a text area");
You are shadowing your variables. You defined the "tb" variable as an instance variable and a local variable. You don't want the local variable because your actionPerformed() method can't reference local variables.
So the code should be:
//JTextArea tb = new JTextArea("This is a text area");
tb = new JTextArea("This is a text area");
I'm watching a youtube tutorial series by mybringback
I've never quite figured out why people use youtube for tutorials.
I would start with the Swing tutorial. This way not only can you read the tutorial at your pace but you can actually download the code and compile and test and change the code. So you start with working code and then you customize it to do what you want.

Related

Weird problem with GUI programming in Java

I have made a simple GUI in Java. The problem is, when I add label to the frame before buttons and check-buttons I get weird flickering when hovering over buttons, and GUI doesn't look right. But when I add label after buttons and check-buttons everything is working fine. Why is this happening?
Here is my code:
package javaapplication13;
import java.awt.*;
import javax.swing.*;
public class JavaApplication13 {
public static void main(String[] args) {
ButtonFrame bf = new ButtonFrame();
}
}
class ButtonFrame extends JFrame {
public ButtonFrame() {
JButton b1 = new JButton("1. Dugme");
JButton b2 = new JButton("2. Dugme");
JLabel l1 = new JLabel();
JCheckBox c1 = new JCheckBox("Prvo dugme");
JCheckBox c2 = new JCheckBox("Drugo dugme");
Container cp = getContentPane();
setTitle("Dugme");
setSize(400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
this.add(b1);
this.add(b2);
this.add(c1);
this.add(c2);
this.add(l1);
b1.setBounds(20, 30, 90, 20);
b2.setBounds(20,70,90,20);
l1.setBounds(70,120,90,20);
c1.setBounds(120,30,120,20);
c2.setBounds(120,70,120,20);
l1.setText("");
}
}
I did not see the flickering you claim to be getting when I copied and ran your code on my Windows 10 computer with JDK 17. However, when I changed your code and added the label to the frame before adding the buttons and check-boxes (as you stated in your question), I did see "flickering".
Although you have already accepted #Antoniossss answer, it is not recommended to not use a layout manager. Refer to the following excerpts from Doing Without a Layout Manager
Although it is possible to do without a layout manager, you should use a layout manager if at all possible.
If a container holds components whose size is not affected by the container's size or by font, look-and-feel, or language changes, then absolute positioning might make sense.
One of the layout managers that your GUI lends itself to is GridBagLayout, although that is not the only suitable one. The below code shows how. (Note that in the below code I set the text of the JLabel so that you can see it.)
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class BtnFrame {
private void createAndDisplayGui() {
JFrame frame = new JFrame("Dugme");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
createForm(frame.getContentPane());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private void createForm(Container contentPane) {
if (contentPane instanceof JComponent) {
JComponent jCmpt = (JComponent) contentPane;
jCmpt.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
}
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;
JButton b1 = new JButton("1. Dugme");
contentPane.add(b1, gbc);
gbc.gridx = 1;
JCheckBox c1 = new JCheckBox("Prvo dugme");
contentPane.add(c1, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
JButton b2 = new JButton("2. Dugme");
contentPane.add(b2, gbc);
gbc.gridx = 1;
JCheckBox c2 = new JCheckBox("Drugo dugme");
contentPane.add(c2, gbc);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.anchor = GridBagConstraints.CENTER;
JLabel l1 = new JLabel("label");
contentPane.add(l1, gbc);
}
public static void main(String[] args) {
final BtnFrame gui = new BtnFrame();
EventQueue.invokeLater(() -> gui.createAndDisplayGui());
}
}
Here is a screen capture of the application.
When setting the layout manager to null in your code (as #Antoniossss said in his answer), the GUI looks like the below screen capture. (Again, I also set the text of the JLabel so that you can see it.)
As you can see, the two screen captures are practically identical.
For completeness, here is your code, with my changes, that produce the above screen capture. As you can see, I moved the line this.add(l1) and also added the line cp.setLayout(null).
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ButtonFrame extends JFrame {
public ButtonFrame(){
JButton b1 = new JButton("1. Dugme");
JButton b2 = new JButton("2. Dugme");
JLabel l1 = new JLabel();
JCheckBox c1 = new JCheckBox("Prvo dugme");
JCheckBox c2 = new JCheckBox("Drugo dugme");
Container cp = getContentPane();
cp.setLayout(null); // Added this line.
setTitle("Dugme");
setSize(400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
this.add(l1);
this.add(b1);
this.add(b2);
this.add(c1);
this.add(c2);
// this.add(l1);
b1.setBounds(20, 30, 90, 20);
b2.setBounds(20,70,90,20);
l1.setBounds(70,120,90,20);
c1.setBounds(120,30,120,20);
c2.setBounds(120,70,120,20);
l1.setText("label");
}
public static void main(String[] args) {
ButtonFrame bf = new ButtonFrame();
}
}
It is because of the default LayoutManager which you dont want to use anyway since you are using strict bounds on your components. Remove layout manager with
setLayout(null);
And it will work as intended
public ButtonFrame(){
setLayout(null); //this will do the trick
JButton b1 = new JButton("1. Dugme");
...rest of your code
}

How to update JInternalFrame by click button on JDialog (JAVA)

I am creating a MDI Application by Java.
I design a JInternalFrame
public class account extends javax.swing.JInternalFrame
{account GUI here}
that show data get from SQL. On this account, I create a JButton named btnReName
private javax.swing.JButton btnReName;
to open a new JDialog ReName.
public class ReName extends javax.swing.JDialog
This JDialog ReName is created to change the name in SQL. After rename successfull, I click on a JButton named btnConfirm
private javax.swing.JButton btnConfirm;
to close this JDialog. After click button Confirm, a JOption appear
like that. I want after click OK, the JDialog ReName is closed, and at the same time, the data on the JInternalFrame account update exactly to what i changed in this JDialog ReName by re-query data from SQL(in other words, i want to update the account by clicking on a Button btnConfirm created on ReName that opened by this JInternalFrame account)
but i dont know how to design it.
Can someone guide me how to create the Button with the function like i was description?
Link to my full-code
The below code does what you want. I did not find a minimal, reproducible example in your question so I guessed that you are using a JTable to display the Player Information. I also only added the Rename button since your question only concerns that button. Here is the code.
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.JDesktopPane;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
public class GamePlay {
private JFrame frame;
private void createAndShowGui() {
frame = new JFrame("Game");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JDesktopPane desktop = new JDesktopPane();
Account iFrame = new Account("iFrame");
iFrame.setVisible(true);
desktop.add(iFrame);
frame.setContentPane(desktop);
frame.setSize(600, 580);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new GamePlay().createAndShowGui());
}
}
class Account extends JInternalFrame implements ActionListener {
private JButton btnReName;
private JTable table;
public Account(String title) {
super(title);
String[] columnNames = {"Ten Nguoi Choi","So Lan Thang","So Lan Choi"};
Object[][] data = {{"Player Name", 1, 7},
{"Nguoi choi 1", 10, 10},
{"Nguoi choi 2", 10, 100},
{"Nguoi choi 3", 0, 10}};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table = new JTable(model);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane, BorderLayout.CENTER);
btnReName = new JButton("Rename");
btnReName.addActionListener(this);
JPanel panel = new JPanel();
panel.add(btnReName);
add(panel, BorderLayout.LINE_END);
pack();
}
public void actionPerformed(ActionEvent event) {
ReName dlg = new ReName(this);
dlg.setVisible(true);
}
public void changeName(String newName) {
int row = table.getSelectedRow();
if (row >= 0) {
table.setValueAt(newName, row, 0);
}
}
}
class ReName extends JDialog implements ActionListener {
private Account account;
private JButton btnConfirm;
private JButton cancel;
private JPasswordField passwordField;
private JTextField nameTextField;
public ReName(Account acct) {
account = acct;
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
add(createForm(), BorderLayout.CENTER);
add(createButtons(), BorderLayout.PAGE_END);
pack();
setLocationRelativeTo(acct);
}
public void actionPerformed(ActionEvent event) {
JOptionPane.showMessageDialog(this,
"Successful",
"Noitication",
JOptionPane.INFORMATION_MESSAGE);
dispose();
account.changeName(nameTextField.getText());
}
private JPanel createButtons() {
JPanel panel = new JPanel();
btnConfirm = new JButton("Confirm");
btnConfirm.addActionListener(this);
cancel = new JButton("Cancel");
panel.add(cancel);
panel.add(btnConfirm);
return panel;
}
private JPanel createForm() {
JPanel form = 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 nameLabel = new JLabel("Enter new name:");
form.add(nameLabel, gbc);
gbc.gridx = 1;
nameTextField = new JTextField(10);
form.add(nameTextField, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
JLabel passwordLabel = new JLabel("Password:");
form.add(passwordLabel, gbc);
gbc.gridx = 1;
passwordField = new JPasswordField(10);
form.add(passwordField, gbc);
return form;
}
}
When I run the above code, the GUI initially looks as follows (using JDK 11 on Windows 10)
This is a screen capture after selecting the name to change and pressing button Rename.
This is a screen capture after entering the new name and pressing button Confirm.
And finally, a screen capture after pressing button OK. Notice that the first column of the selected row in the JTable has changed to what was entered in the JDialog.

This GUI is displaying nothing after setting BoxLayout

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUI_Borrower extends JFrame implements ActionListener {
JPanel panel = new JPanel();
JLabel lblName = new JLabel("Name:");
JLabel lblProg = new JLabel("Program:");
JLabel lblId = new JLabel("Library ID: ");
JLabel lblTitle = new JLabel("Add Borrower");
JTextField txtName = new JTextField(10);
JTextField txtProg = new JTextField(10);
JTextField txtId = new JTextField(10);
static int counter = 19000;
JButton btnSubmit = new JButton("Submit");
public GUI_Borrower() {
super("Add Borrower");
makeFrame();
showFrame();
}
public void makeFrame() {
lblTitle.setFont(new Font("Forte", Font.PLAIN, 40));
lblTitle.setForeground(Color.BLUE);
add(lblTitle);
add(lblName);
add(txtName);
add(lblProg);
add(txtProg);
add(lblId);
add(txtId);
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.add(btnSubmit);
btnSubmit.addActionListener(this);
}
public void showFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 200);
setLocationRelativeTo(null);
setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
Object source = ae.getSource();
if (ae.getActionCommand().equals("Confirm")) {
txtName.setText("");
txtProg.setText("");
btnSubmit.setText("Submit");
} else if (source == btnSubmit) {
if (txtName.getText().equals("") && txtProg.getText().equals("")) {
txtId.setText("No entry of both");
} else if (txtName.getText().equals("")) {
txtId.setText("No entry of Name");
} else if (txtProg.getText().equals("")) {
txtId.setText("No entry of Program");
} else {
counter++;
txtId.setText("" + counter);
btnSubmit.setText("Confirm");
}
}
}
public static void main(String[] args) {
new GUI_Borrower();
}
}
I tried adding BoxLayout because all the text fields and labels are on one line. So I tried box Layout and failed.
Can anyone show me how to make it like the title one line, label Different line, button different line?
Like this:
As camickr says in his comment, you generally use a GridBagLayout to create a form.
I reworked your code because I hope to show a better way to code a GUI panel.
Here's the GUI.
The major changes I made include:
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.
I organized the GUI code into three methods so I could focus on one part of the GUI at a time. The JFrame is created in the run method. The title JPanel is created in the createTitlePanel method. The form JPanel is created in the createFormPanel method. The code for the JFrame will rarely change from Swing application to Swing application.
I use Swing components. I don't extend Swing components, or any Java class, unless I intend to override one of the class methods.
The createFormPanel class uses the GridBagLayout to organize the labels and text fields in columns. You can think of the GridBagLayout as a flexible grid. The cells of the grid don't have to be the same size. The Oracle tutorial, How to Use GridBagLayout, has another example.
I put the ActionListener in a separate class. I made it an inner class in this example so I could paste the code as one file. Generally, you should put separate classes in separate files. It makes each class shorter and easier to understand.
Here's the runnable, example code.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
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 BorrowerGUI implements Runnable {
private static int ID_COUNTER = 19000;
public static void main(String[] args) {
SwingUtilities.invokeLater(new BorrowerGUI());
}
private JButton btnSubmit;
private JTextField txtName;
private JTextField txtProg;
private JTextField txtId;
#Override
public void run() {
JFrame frame = new JFrame("Add Borrower");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createTitlePanel(), BorderLayout.BEFORE_FIRST_LINE);
frame.add(createFormPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createTitlePanel() {
JPanel panel = new JPanel(new FlowLayout());
JLabel lblTitle = new JLabel("Add Borrower");
lblTitle.setFont(new Font("Forte", Font.PLAIN, 40));
lblTitle.setForeground(Color.BLUE);
panel.add(lblTitle);
return panel;
}
private JPanel createFormPanel() {
JPanel panel = new JPanel(new GridBagLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.LINE_START;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.gridx = 0;
gbc.gridy = 0;
JLabel lblName = new JLabel("Name:");
panel.add(lblName, gbc);
gbc.gridx++;
txtName = new JTextField(20);
panel.add(txtName, gbc);
gbc.gridx = 0;
gbc.gridy++;
JLabel lblProg = new JLabel("Program:");
panel.add(lblProg, gbc);
gbc.gridx++;
txtProg = new JTextField(20);
panel.add(txtProg, gbc);
gbc.gridx = 0;
gbc.gridy++;
JLabel lblId = new JLabel("Library ID:");
panel.add(lblId, gbc);
gbc.gridx++;
txtId = new JTextField(20);
txtId.setEditable(false);
panel.add(txtId, gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.gridwidth = 2;
btnSubmit = new JButton("Submit");
btnSubmit.addActionListener(new SubmitListener());
panel.add(btnSubmit, gbc);
return panel;
}
public class SubmitListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
Object source = ae.getSource();
if (ae.getActionCommand().equals("Confirm")) {
txtName.setText("");
txtName.requestFocus();
txtProg.setText("");
txtId.setText("");
btnSubmit.setText("Submit");
} else if (source == btnSubmit) {
if (txtName.getText().equals("") &&
txtProg.getText().equals("")) {
txtId.setText("No entry of both");
} else if (txtName.getText().equals("")) {
txtId.setText("No entry of Name");
} else if (txtProg.getText().equals("")) {
txtId.setText("No entry of Program");
} else {
ID_COUNTER++;
txtId.setText("" + ID_COUNTER);
btnSubmit.setText("Confirm");
}
}
}
}
}
Edited to add: If you want the title JLabel to be right-justified, you'll have to switch to a BorderLayout. I added an empty border so the text wouldn't be on the right edge of the JFrame.
Here's the changed method.
private JPanel createTitlePanel(String title) {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 0, 10));
JLabel lblTitle = new JLabel(title);
lblTitle.setFont(new Font("Forte", Font.PLAIN, 40));
lblTitle.setForeground(Color.BLUE);
panel.add(lblTitle, BorderLayout.AFTER_LINE_ENDS);
return panel;
}

How do I use GridBagConstraints setRows and setColumns?

How do I use setRows and setColumns to change the amount of rows and columns in my window?
Here's a copy of my code and where I tried to implement the set rows and columns:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Toolkit;
import java.awt.*;
#SuppressWarnings("unused")
public class GUI
{
public static void main(String[] args)
{
new GUI();
}
public GUI()
{
JFrame AG = new JFrame("Adventure Game");
AG.setExtendedState(JFrame.MAXIMIZED_BOTH);
AG.setResizable(true);
AG.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p=new JPanel();
p.setLayout (new GridBagLayout());
AG.add(p);
GridBagConstraints GBC = new GridBagConstraints();
GridLayout.setRows(100);//heres the set rows<<<<<<<<<<<<<<<<<<<
GridLayout.setColumns(100);//heres the set columns<<<<<<<<<<<<<<<<<<<
AG.getContentPane().add(p, BorderLayout.NORTH);
JButton saveButton =new JButton("Save");
JButton loadButton =new JButton("Load");
JButton optionsButton = new JButton("Options");
JLabel textBox= new JLabel("Story line will go here.");
JLabel label11 = new JLabel("Test 1");
GBC.gridx = 0;
GBC.gridy = 1;
p.add(label11,GBC);
JLabel label12 = new JLabel("Test 2");
GBC.gridx = 0;
GBC.gridy = 2;
p.add(label12,GBC);
JLabel label13 = new JLabel("Test 3");
GBC.gridx = 0;
GBC.gridy = 3;
p.add(label13,GBC);
JLabel label14 = new JLabel("Test 4");
GBC.gridx = 0;
GBC.gridy = 5;
p.add(label14,GBC);
AG.setVisible(true);
}
}
GridBagConstraints work with the GridBagLayout, not the GridLayout. Your call to GridLayout doesn't do anything.
To set the rows and columns with GridBagConstraints, you need to use GBC.gridx = ...; and GBC.gridy = ...;
If you are trying to place gaps between your buttons, empty GridBag cells are not the way to do it; use the insets of your GridBagConstraints for that.
To make a component in a GridBagLayout disappear without the other components shifting around, place the button in a JPanel with a CardLayout, and make sure you add that JPanel to your GridBagLayout instead of the button:
private JButton optionalButton;
private void buildWindow() {
// ...
optionalButton = new JButton("Optional Action");
JPanel optionalButtonPanel = new JPanel(new CardLayout());
optionalButtonPanel.add(optionalButton, "BUTTON");
optionalButtonPanel.add(new JLabel(), "BLANK");
// ...
}
private void setOptionalButtonVisible(boolean visible) {
Container optionalButtonPanel = optionalButton.getParent();
CardLayout layout = (CardLayout) optionalButtonPanel.getLayout();
layout.show(optionalButtonPanel, visible ? "BUTTON" : "BLANK");
}
CardLayout always displays one and only one of its components, but it sizes its associated container to fit all the components, including the invisible ones.

my japplet compiles, but it comes up as blank in applet viewer

import javax.swing.BoxLayout;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
public class LoginApplet extends JApplet { /**
*
*/
private static final long serialVersionUID = 1L;
JLabel titlePage;
JLabel[] txt;
JTextField[] jtf;
JButton accept, decline;
JPanel jp1, jp2, jp3;
public void init(){
setSize(400,400);
JPanel content = (JPanel)getContentPane();
GridBagConstraints firstCol = new GridBagConstraints();
firstCol.weightx = 1.0;
firstCol.anchor = GridBagConstraints.WEST;
firstCol.insets = new Insets(5, 20, 5, 5);
GridBagConstraints lastCol = new GridBagConstraints();
lastCol.gridwidth = GridBagConstraints.REMAINDER;
lastCol.weightx = 1.0;
lastCol.fill = GridBagConstraints.HORIZONTAL;
lastCol.insets = new Insets(5, 5, 5, 20);
String[] labeltxt = {"Username", "Password"};
titlePage = new JLabel("Create New Account");
txt = new JLabel[2];
jtf = new JTextField[2];
accept = new JButton("Create");
decline = new JButton("Decline");
jp1 = new JPanel();
jp2 = new JPanel(new GridBagLayout());
jp3 = new JPanel();
for(int i=0; i<labeltxt.length; i++) {
txt[i] = new JLabel();
txt[i].setText(labeltxt[i]);
jp2.add(txt[i], firstCol);
jtf[i] = new JTextField();
jtf[i].setPreferredSize(new Dimension(300, 20));
jp2.add(jtf[i], lastCol);
}
jp1.add(titlePage);
jp3.add(accept);
jp3.add(decline);
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
content.add(jp1);
content.add(jp2);
content.add(jp3);
}
public void setVisible(boolean b) {
// TODO Auto-generated method stub
}
}
Hi guys.. This code I have posted up is from class LoginApplet which gets called by an ActionPerformed from another class.... I had no problem with it set as JFrame (the rubric for this assignment was in JApplet). Now when I converted it to JApplet problems show up. I am not familiar with JApplet, and is there anything wrong with the code showing up as blank when ran?
Get rid of
public void setVisible(boolean b) {
// TODO Auto-generated method stub
}
It's preventing the applet from thinking it's visible...

Categories