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.
Related
So I want to have a CardLayout class that switches between a menu page and a main app page, but I want to design those two panels in their own classes, then add an ActionListener and a CardLayout in a different class, and have the ActionListener use a button created in one of the panel classes.
Here is a (Not so short) SSCCE that kind of covers what I'm trying to say:
import java.awt.*;
import javax.swing.*;
public class MenuPanel extends Frame{
JPanel menuPanel;
JButton login;
JButton signup;
public MenuPanel(){
menuPanel = new JPanel(new GridBagLayout());
login = new JButton("Login");
signup = new JButton("Signup");
menuPanel.add(login);
menuPanel.add(signup);
}
}
import java.awt.*;
import javax.swing.*;
public class MainPanel extends JFrame{
JPanel menuPanel;
JButton login;
JButton signup;
public MainPanel(){
mainPanel = new JPanel(new GridBagLayout());=
menuPanel.setBackground(Color.grey);
}
}
import java.awt.*;
import javax.swing.*;
public class CardLayout extends Frame implements ActionL {
//Now how do I add the frames from the other classes so that I can add them to my CardLayout?
CardLayout cl = new CardLayout();
JPanel panelCont;
public CardLayout() {
frame.add(panelCont);
panelCont = new JPanel(cl);
//Here is where I'm having trouble
panelCont.add(menuPanel, "1");
panelCont.add(mainPanel, "2");
cl.show(panelCont, "1");
login.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
cl.show(panelCont, "2");
}
});
}
}
public class Main {
public static void main(String[] args) {
new CardLayout();
}
}
You cannot add Frames to another component. Frame is a top level component with a native peer. You should subclass from something else (JPanel?) instead
Also, btw what you are doing is not good design. Generally, in MVC Swing design, all view and control aspects should be in one class. Don't split the view into multiple classes unless each of those classes stands up as its own reusable widget
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section. Pay close attention to the Concurrency in Swing and the Laying Out Components Within a Container sections.
In Java Swing, you create one JFrame and as many JPanels as you need to create the GUI.
I created a card JPanel, a menu JPanel, and a login JPanel in three separate classes. The card JPanel class creates the JPanel with the CardLayout. The menu JPanel creates the JPanel that contains the menu JButtons. The login JPanel class creates the JPanel that contains the login Swing components.
Here's the JFrame with the menu JPanel.
Here's the GUI after you left-click on the Login JButton.
Notice how I named the classes. CardPanel, MenuPanel, LoginPanel. By appending Panel to the end of the class name, that tells me they use a JPanel.
When I create a separate ActionListener class, I'd name it ButtonListener or SignupListener.
The only ActionListener I created ties the menu login JButton to displaying the login JPanel. Since it consists of one line, I made it an anonymous class using a lambda expression.
Here's the complete runnable code. I made all the additional classes inner classes so I could post this code as one block. You can and should put these classes in separate files.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
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.SwingUtilities;
public class CardLayoutExample implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new CardLayoutExample());
}
#Override
public void run() {
JFrame frame = new JFrame("CardLayout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new CardPanel().getPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public class CardPanel {
private final CardLayout cardLayout;
private final JPanel panel;
public CardPanel() {
this.cardLayout = new CardLayout();
this.panel = createCardPanel();
}
private JPanel createCardPanel() {
JPanel panel = new JPanel(cardLayout);
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
panel.add(new MenuPanel(this).getPanel(), "menu");
panel.add(new LoginPanel().getPanel(), "login");
return panel;
}
public void showLoginPanel() {
cardLayout.show(panel, "login");
}
public JPanel getPanel() {
return panel;
}
}
public class MenuPanel {
private final CardPanel cardPanel;
private final JPanel panel;
public MenuPanel(CardPanel cardPanel) {
this.cardPanel = cardPanel;
this.panel = createMenuPanel();
}
private JPanel createMenuPanel() {
JPanel panel = new JPanel(new GridLayout(0, 1, 5, 5));
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JButton login = new JButton("Login");
login.addActionListener(event -> cardPanel.showLoginPanel());
panel.add(login);
JButton signup = new JButton("Signup");
panel.add(signup);
return panel;
}
public JPanel getPanel() {
return panel;
}
}
public class LoginPanel {
private final JPanel panel;
private final JPasswordField passwordField;
private final JTextField useridField;
public LoginPanel() {
this.useridField = new JTextField(30);
this.passwordField = new JPasswordField(30);
this.panel = createLoginPanel();
}
private JPanel createLoginPanel() {
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.NONE;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy = 0;
JLabel label = new JLabel("Userid:");
panel.add(label, gbc);
gbc.gridx++;
panel.add(useridField, gbc);
gbc.gridx = 0;
gbc.gridy++;
label = new JLabel("Password:");
panel.add(label, gbc);
gbc.gridx++;
panel.add(passwordField, gbc);
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridwidth = 2;
gbc.gridx = 0;
gbc.gridy++;
JButton button = new JButton("Submit");
panel.add(button, gbc);
return panel;
}
public String getUserid() {
return useridField.getText();
}
public char[] getPassword() {
return passwordField.getPassword();
}
public JPanel getPanel() {
return panel;
}
}
}
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;
}
This may come off as an odd question, but I would like to make a program that makes a new Jbutton instance in an existing group every time a button(called new) is pressed. It will be added under the previously added button, all buttons must be part of a group(so when one button is pressed it will deselect previously selected button if the button in the group is pressed) and should be able to make an infinite number of buttons given n number of clicks. Here is what I have so far, but honestly I don't even know how to approach this one.
public static void makebuttonpane() {
buttonpane.setLayout(new GridBagLayout());
GridBagConstraints d = new GridBagConstraints();
nbutton = new JButton("New");
d.insets = new Insets(10, 10, 0, 10);
d.anchor = GridBagConstraints.PAGE_START;
buttonpane.add(nbutton,d);
nbutton.addActionListener(new ButtonMaker());
//d.anchor = GridBagConstraints.CENTER;
}
public static void addbutton(JButton button) {
System.out.println("button made");
buttonpane.removeAll();
nbutton = new JButton("New");
d.insets = new Insets(10, 10, 0, 10);
d.anchor = GridBagConstraints.PAGE_START;
buttonpane.add(nbutton,d);
nbutton.addActionListener(new ButtonMaker());
d.gridx=0;
System.out.println(ButtonMaker.getNumb());
d.gridy= ButtonMaker.getNumb();
buttonpane.add(button,d);
frame.setVisible(true);
buttonpane.validate();
}
public static void makebuttonpane() {
buttonpane.setLayout(new GridBagLayout());
GridBagConstraints d = new GridBagConstraints();
nbutton = new JButton("New");
d.insets = new Insets(10, 10, 0, 10);
d.anchor = GridBagConstraints.PAGE_START;
buttonpane.add(nbutton,d);
nbutton.addActionListener(new ButtonMaker());
//d.anchor = GridBagConstraints.CENTER;
}
public static void addbutton(JButton button) {
System.out.println("button made");
buttonpane.removeAll();
nbutton = new JButton("New");
d.insets = new Insets(10, 10, 0, 10);
d.anchor = GridBagConstraints.PAGE_START;
buttonpane.add(nbutton,d);
nbutton.addActionListener(new ButtonMaker());
d.gridx=0;
System.out.println(ButtonMaker.getNumb());
d.gridy= ButtonMaker.getNumb();
buttonpane.add(button,d);
frame.setVisible(true);
buttonpane.validate();
}
class ButtonMaker implements ActionListener{
public static int i=1;
public void actionPerformed(ActionEvent e) {
//System.out.println("I hear you");
//System.out.println(i);
JButton button = new JButton("Button "+i);
MultiListener.addbutton(button);
i++;
}
public static int getNumb() {
return i;
}
}
It adds the first button instance but pressing 'New' only changes that first created button instead of making a new one underneath
I created a GUI that adds a JButton when you click on the "Add Button" button.
Feel free to modify this any way you want.
Mainly, I separated the construction of the JFrame, the construction of the JPanel, and the action listener. Focusing on one part at a time, I was able to code and test this GUI quickly.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
public class JButtonCreator implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new JButtonCreator());
}
private static int buttonCount = 0;
private JButtonPanel buttonPanel;
#Override
public void run() {
JFrame frame = new JFrame("JButton Creator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buttonPanel = new JButtonPanel();
JScrollPane scrollPane = new JScrollPane(
buttonPanel.getPanel());
frame.add(scrollPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public class JButtonPanel {
private ButtonGroup buttonGroup;
private JPanel buttonPanel;
private JPanel panel;
public JButtonPanel() {
createPartControl();
}
private void createPartControl() {
panel = new JPanel();
panel.setPreferredSize(new Dimension(640, 480));
panel.setLayout(new BorderLayout());
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(0, 5));
buttonGroup = new ButtonGroup();
panel.add(buttonPanel, BorderLayout.CENTER);
JButton newButton = new JButton("Add Button");
newButton.addActionListener(new ButtonListener(this));
panel.add(newButton, BorderLayout.AFTER_LAST_LINE);
}
public void addJButton() {
String text = "Button " + ++buttonCount;
JButton button = new JButton(text);
buttonPanel.add(button);
buttonGroup.add(button);
}
public JPanel getPanel() {
return panel;
}
}
public class ButtonListener implements ActionListener {
private JButtonPanel buttonPanel;
public ButtonListener(JButtonPanel buttonPanel) {
this.buttonPanel = buttonPanel;
}
#Override
public void actionPerformed(ActionEvent event) {
buttonPanel.addJButton();
buttonPanel.getPanel().revalidate();;
}
}
}
I'm having a problem with a JFrame not showing a JTable that is added to it. I've tried getContentPane().add(..), I've switched to just add to keep the code a little shorter. Any help is more than appreciated!
package com.embah.Accgui;
import java.awt.*;
import javax.swing.*;
public class accCreator extends JFrame {
private String[] columnNames = {"Username", "Password", "Members", "World"};
private Object[][] data = {{"b", "b", "b", "b"},
{ "e", "e", "e", "e"}};
private JTable tbl_Accounts;
private JScrollPane scrollPane;
private JLabel lbl_Account = new JLabel();
private JLabel lbl_Username = new JLabel();
private JLabel lbl_Password = new JLabel();
private JLabel lbl_Homeworld = new JLabel();
private JButton btn_Select = new JButton();
private JButton btn_Addacc = new JButton();
private JButton btn_Delacc = new JButton();
private JTextArea txt_Username = new JTextArea();
private JTextArea txt_Password = new JTextArea();
private JTextArea txt_Homeworld = new JTextArea();
private JCheckBox cbox_Members = new JCheckBox();
private JCheckBox cbox_RanWrld = new JCheckBox();
public accCreator() {
setLayout(null);
setupGUI();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
void setupGUI() {
tbl_Accounts = new JTable(data, columnNames);
tbl_Accounts.setLocation(5, 30);
tbl_Accounts.setPreferredScrollableViewportSize(new Dimension(420, 250));
tbl_Accounts.setFillsViewportHeight(true);
tbl_Accounts.setVisible(true);
add(tbl_Accounts);
scrollPane = new JScrollPane(tbl_Accounts);
add(scrollPane);
lbl_Account.setLocation(4, 5);
lbl_Account.setSize(100, 20);
lbl_Account.setText("Select Account:");
add(lbl_Account);
lbl_Username.setLocation(5, 285);
lbl_Username.setSize(70, 20);
lbl_Username.setText("Username:");
add(lbl_Username);
lbl_Password.setLocation(5, 310);
lbl_Password.setSize(70, 20);
lbl_Password.setText("Password:");
add(lbl_Password);
lbl_Homeworld.setLocation(310, 310);
lbl_Homeworld.setSize(80, 20);
lbl_Homeworld.setText("Home World:");
add(lbl_Homeworld);
btn_Select.setLocation(305, 5);
btn_Select.setSize(120, 20);
btn_Select.setText("Select Account");
add(btn_Select);
btn_Addacc.setLocation(300, 285);
btn_Addacc.setSize(60, 20);
btn_Addacc.setText("Add");
btn_Addacc.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
String worldSel = "";
if(cbox_RanWrld.isSelected()){
worldSel = "Random";
} else {
worldSel = txt_Homeworld.getText();
}
Object[] row = {txt_Username.getText(), txt_Password.getText(), cbox_Members.isSelected(), worldSel};
DefaultTableModel model = (DefaultTableModel) tbl_Accounts.getModel();
model.addRow(row);
}
});
add(btn_Addacc);
btn_Delacc.setLocation(365, 285);
btn_Delacc.setSize(60, 20);
btn_Delacc.setText("Del");
btn_Delacc.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
DefaultTableModel model = (DefaultTableModel) tbl_Accounts.getModel();
}
});
add(btn_Delacc);
txt_Username.setLocation(80, 285);
txt_Username.setSize(100, 20);
txt_Username.setText("");
txt_Username.setRows(5);
txt_Username.setColumns(5);
add(txt_Username);
txt_Password.setLocation(80, 310);
txt_Password.setSize(100, 20);
txt_Password.setText("");
txt_Password.setRows(5);
txt_Password.setColumns(5);
txt_Password.setTabSize(0);
add(txt_Password);
txt_Homeworld.setLocation(395, 310);
txt_Homeworld.setSize(30, 20);
txt_Homeworld.setText("82");
txt_Homeworld.setRows(5);
txt_Homeworld.setColumns(5);
txt_Homeworld.setTabSize(0);
add(txt_Homeworld);
cbox_Members.setLocation(185, 285);
cbox_Members.setSize(80, 20);
cbox_Members.setText("Members");
cbox_Members.setSelected(false);
add(cbox_Members);
cbox_RanWrld.setLocation(185, 310);
cbox_RanWrld.setSize(115, 20);
cbox_RanWrld.setText("Random World");
cbox_RanWrld.setSelected(false);
add(cbox_RanWrld);
setTitle("Account Manager");
setSize(440, 370);
setVisible(true);
setResizable(false);
}
public static void main(String args[]) {
new accCreator();
}
}
I know thats not the problem tho because everything else shows up just fine
Oh... really? Not in my computer...
Let's have a picture of your actual GUI shown in my PC:
Does the GUI looks the same in your computer? I bet no.
But... why does it looks like that in my PC?
Well, as stated above in the comments by #MadProgrammer this is because of the setLayout(null); line. You might want to read Why is it frowned upon to use a null layout in Java Swing? for more information.
Now, that being said, you should also want to read and learn how to use the various layout managers that will let you create complex GUIs.
In your code you never set the location / bounds for scrollPane, and the size of it, so the component has a default size of 0, 0.
But... I think it's better to show you how you can get a really similar GUI (I'm in a hurry so I didn't make an even more similar GUI). You can copy-paste my code and see the same output (with slight differences because of the OS maybe) but text won't be cropped.
The code that produces the above image is this one:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridLayout;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class AccountCreator {
private JFrame frame;
private JPanel mainPane;
private JPanel topPane;
private JPanel tablePane;
private JPanel bottomPane;
private JLabel selectAccountLabel;
private JLabel userNameLabel;
private JLabel passwordLabel;
private JLabel homeWorldLabel;
private JTextField userNameField;
private JTextField homeWorldField;
private JPasswordField passwordField;
private JCheckBox membersBox;
private JCheckBox randomBox;
private JButton selectAccountButton;
private JButton addButton;
private JButton deleteButton;
private JTable table;
private JScrollPane scroll;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new AccountCreator().createAndShowGui();
}
});
}
public void createAndShowGui() {
frame = new JFrame(getClass().getSimpleName());
int rows = 30;
int cols = 3;
String[][] data = new String[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
data[i][j] = i + "-" + j;
}
}
String[] columnNames = { "Column1", "Column2", "Column3" };
table = new JTable(data, columnNames);
scroll = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
table.setPreferredScrollableViewportSize(new Dimension(420, 250));
table.setFillsViewportHeight(true);
selectAccountLabel = new JLabel("Select Account");
userNameLabel = new JLabel("Username: ");
passwordLabel = new JLabel("Password: ");
homeWorldLabel = new JLabel("Home world");
selectAccountButton = new JButton("Select Account");
addButton = new JButton("Add");
deleteButton = new JButton("Del");
userNameField = new JTextField(10);
passwordField = new JPasswordField(10);
homeWorldField = new JTextField(3);
membersBox = new JCheckBox("Members");
randomBox = new JCheckBox("Random world");
topPane = new JPanel();
topPane.setLayout(new BorderLayout());
topPane.add(selectAccountLabel, BorderLayout.WEST);
topPane.add(selectAccountButton, BorderLayout.EAST);
tablePane = new JPanel();
tablePane.add(scroll);
bottomPane = new JPanel();
bottomPane.setLayout(new GridLayout(0, 5, 3, 3));
bottomPane.add(userNameLabel);
bottomPane.add(userNameField);
bottomPane.add(membersBox);
bottomPane.add(addButton);
bottomPane.add(deleteButton);
bottomPane.add(passwordLabel);
bottomPane.add(passwordField);
bottomPane.add(randomBox);
bottomPane.add(homeWorldLabel);
bottomPane.add(homeWorldField);
mainPane = new JPanel();
mainPane.setLayout(new BoxLayout(mainPane, BoxLayout.PAGE_AXIS));
frame.add(topPane, BorderLayout.NORTH);
frame.add(tablePane, BorderLayout.CENTER);
frame.add(bottomPane, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Also, you might have noticed that the main() method is different, well, the code inside it is placing the program on the Event Dispatch Thread (EDT).
So, be sure to include it in your future programs
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.