This GUI is displaying nothing after setting BoxLayout - java

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;
}

Related

Accessing JPanel components from a seperate class

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;
}
}
}

GridBagLayout not moving components no matter what values entered?

I currently have a jpanel with layout set to GridBagLayout, with gbc = new GridBagConstraints();, However for whatever value of x, y or gridwidth,gridheight the items don't move at all.
I would greatly appreciate an expert eye to look over my code to see what I am missing, Thanks in advance.
Edit: Added the imports and the main method
Edit 2: turns out I was thinking the x and y values were pixels and that was the reason it wasn't working
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class HomeScreenUI {
public void addobjects(Component componente, Container yourcontainer, GridBagLayout layout, GridBagConstraints gbc, int gridx, int gridy, int gridwidth, int gridheight){
gbc.gridx = gridx;
gbc.gridy = gridy;
gbc.gridwidth = gridwidth;
gbc.gridheight = gridheight;
layout.setConstraints(componente, gbc);
yourcontainer.add(componente);
}
HomeScreenUI(){
//frame
JFrame frame = new JFrame("Opisa");
//panels, one before button click and one after
JPanel panel = new JPanel();
JPanel panelAfterButtonClick = new JPanel();
GridBagLayout ourlayout;
ourlayout = new GridBagLayout();
panel.setLayout(ourlayout);
panelAfterButtonClick.setLayout(ourlayout);
GridBagConstraints gbc = new GridBagConstraints();
//jlabel that isnt displaying + dimensions
JLabel label = new JLabel("Opisa");
label.setFont(new Font("Helvetica", Font.PLAIN, 70));
//second jlabel that isn't displaying
JLabel label2 = new JLabel("Home");
label2.setFont(new Font("Helvetica", Font.PLAIN, 70));
//adding the labels to the panels
panel.add(label);
panelAfterButtonClick.add(label2);
//button that is displaying both before and after
JButton button = new JButton("Click Me..");
JButton buttonAfterClick = new JButton("Clicked Me..");
//adding the buttons to the jpanel
this.addobjects(label, panel, ourlayout, gbc, 0,0, 3, 1);
this.addobjects(button, panel, ourlayout, gbc, 700, 100, 2, 0);
this.addobjects(label2, panelAfterButtonClick, ourlayout, gbc, 200, 200, 1, 1);
this.addobjects(buttonAfterClick, panelAfterButtonClick, ourlayout, gbc, 700, 10, 2, 0);
//function that changes the panel after the button is clicked
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
frame.setContentPane(panelAfterButtonClick);
frame.invalidate();
frame.validate();
}
});
//adding the panel to the frame and setting the size
frame.add(panel);
frame.setSize(720,1280);
frame.setVisible(true);
}
}
public static void main (String args[]) {
HomeScreenUI hs = new HomeScreenUI();
}
It seems you are using GridBagLayout completely different than it was designed for.
Note you have one instance of GridBagLayout but want to use it for two panels. Each panel needs to have it's own LayoutManager instance.
Then look how many GridBagConstraints you have. Each Component that shall be added needs it's own instance to be properly managed.
Then there are strange values you are passing into GridBagConstraints. I suggest you take the time and go through How to Use GridBagLayout.
I modified your code to create the following GUI.
Here's what it looks like after you left-click the button.
You can swap back and forth between the two panels.
Here are the major changes I made to your code.
Code should be organized like an essay. The most important code should come first, followed by the less important code.
Break your code up into methods and classes. Each method should do one thing and do it well. This is called separation of concerns and it helps you to focus on one part of your code at a time.
To start the Swing application, I made a call to the SwingUtilities invokeLater method. This method ensures that all Swing components are created and executed on the Event Dispatch Thread.
The JFrame code is in the class constructor. The JFrame code has to be called in a certain order. This is the order I use for most of my Swing applications. Don't forget to call the setDefaultCloseOperation method. The JFrame.EXIT_ON_CLOSE parameter exits the application when you close the JFrame.
I used a CardLayout to hold the two subordinate JPanels. I created the CardLayout in its own method.
I created each subordinate JPanel in its own method. I used a GridBagLayout for both subordinate JPanels. As you can see in the code, you have to set quite a few GridBagConstraints parameters.
I created an anonymous ActionListener for each of the JButtons. The ActionListeners swap the two subordinate JPanels in the CardLayout.
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.CardLayout;
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.SwingUtilities;
public class HomeScreenUI {
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new HomeScreenUI();
}
});
}
private CardLayout cardLayout;
private JPanel cardPanel;
public HomeScreenUI() {
JFrame frame = new JFrame("Opisa");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.cardPanel = createCardPanel();
frame.add(cardPanel, BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createCardPanel() {
cardLayout = new CardLayout();
JPanel panel = new JPanel(cardLayout);
panel.add(createOpisaPanel(), "Opisa");
panel.add(createHomePanel(), "Home");
return panel;
}
private JPanel createOpisaPanel() {
JPanel panel = new JPanel(new GridBagLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.CENTER;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.gridx = 0;
gbc.gridy = 0;
// jlabel that isnt displaying + dimensions
JLabel label = new JLabel("Opisa");
label.setFont(new Font("Helvetica", Font.PLAIN, 72));
panel.add(label, gbc);
gbc.gridy++;
JButton button = new JButton("Click Me..");
// function that changes the panel after the button is clicked
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
cardLayout.show(cardPanel, "Home");
}
});
panel.add(button, gbc);
return panel;
}
private JPanel createHomePanel() {
JPanel panel = new JPanel(new GridBagLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.CENTER;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.gridx = 0;
gbc.gridy = 0;
// second jlabel that isn't displaying
JLabel label2 = new JLabel("Home");
label2.setFont(new Font("Helvetica", Font.PLAIN, 72));
panel.add(label2, gbc);
gbc.gridy++;
JButton buttonAfterClick = new JButton("Clicked Me..");
buttonAfterClick.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
cardLayout.show(cardPanel, "Opisa");
}
});
panel.add(buttonAfterClick, gbc);
return panel;
}
}

Remove line from JTextArea

I have a JTextArea that is filled with numbers with no duplicates. There is an add and remove button. I have programmed the add button, but I am struggling with programming the remove button. I know how to remove the number from the array, but I'm not sure how to remove the number from the text area.
How do I remove a line from a text area that contains a certain number?
Extra notes:
The only input is integers.
Your question may in fact be an XY Problem where you ask how to fix a specific code problem when the best solution is to use a different approach entirely. Consider using a JList and not a JTextArea. You can easily rig it up to look just like a JTextArea, but with a JList, you can much more easily remove an item such as a line by removing it from its model.
For example:
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class NumberListEg extends JPanel {
private static final int VIS_ROW_COUNT = 10;
private static final int MAX_VALUE = 10000;
private DefaultListModel<Integer> listModel = new DefaultListModel<>();
private JList<Integer> numberList = new JList<>(listModel);
private JSpinner spinner = new JSpinner(new SpinnerNumberModel(0, 0, MAX_VALUE, 1));
private JButton addNumberButton = new JButton(new AddNumberAction());
public NumberListEg() {
JPanel spinnerPanel = new JPanel();
spinnerPanel.add(spinner);
JPanel addNumberPanel = new JPanel();
addNumberPanel.add(addNumberButton);
JPanel removeNumberPanel = new JPanel();
JButton removeNumberButton = new JButton(new RemoveNumberAction());
removeNumberPanel.add(removeNumberButton);
JPanel eastPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
// gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(3, 3, 3, 3);
eastPanel.add(spinner, gbc);
gbc.gridy = GridBagConstraints.RELATIVE;
eastPanel.add(addNumberButton, gbc);
eastPanel.add(removeNumberButton, gbc);
// eastPanel.add(Box.createVerticalGlue(), gbc);
numberList.setVisibleRowCount(VIS_ROW_COUNT);
numberList.setPrototypeCellValue(1234567);
numberList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane listPane = new JScrollPane(numberList);
listPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
setLayout(new BorderLayout());
add(listPane, BorderLayout.CENTER);
add(eastPanel, BorderLayout.LINE_END);
}
private class AddNumberAction extends AbstractAction {
public AddNumberAction() {
super("Add Number");
putValue(MNEMONIC_KEY, KeyEvent.VK_A);
}
#Override
public void actionPerformed(ActionEvent arg0) {
int value = (int) spinner.getValue();
if (!listModel.contains(value)) {
listModel.addElement(value);
}
}
}
private class RemoveNumberAction extends AbstractAction {
public RemoveNumberAction() {
super("Remove Number");
putValue(MNEMONIC_KEY, KeyEvent.VK_R);
}
#Override
public void actionPerformed(ActionEvent e) {
Integer selection = numberList.getSelectedValue();
if (selection != null) {
listModel.removeElement(selection);
}
}
}
private static void createAndShowGui() {
NumberListEg mainPanel = new NumberListEg();
JFrame frame = new JFrame("Gui");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
can not be remove from the array,you can to make index to be empty,for example String a= Integer.toString(type for int),then a.replace("your int","");

How to get my JButtons to be on the left and not in the middle

I'm a little lost here, when I run the program the buttons are in the middle of the input and not directly on the bottom aligned with it. I'm not sure what I'm doing wrong. I'm also trying to find out how to get statistics for my input like min and max value, and average word size. I'm a little lost, thanks!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.util.Arrays;
public class CopyTextPanel extends JPanel
{
private JTextField input;
private JLabel output, inlabel, outlabel;
private JButton compute, clear;
private JPanel panel, panel1, panel2;
public CopyTextPanel()
{
setLayout (new BoxLayout(this, BoxLayout.Y_AXIS));
inlabel = new JLabel("Input: ");
outlabel = new JLabel("Text Statistics Result: ");
input = new JTextField (50);
output = new JLabel();
compute = new JButton("Compute Statistics");
compute.addActionListener (new ButtonListener());
clear = new JButton("Clear Text");
clear.addActionListener (new ButtonListener());
panel = new JPanel();
panel1 = new JPanel();
panel2 = new JPanel();
output.setMaximumSize (new Dimension(500, 30));
output.setMinimumSize (new Dimension(500, 30));
panel.setMaximumSize (new Dimension(500, 30));
panel.setMinimumSize (new Dimension(500, 30));
panel.setBackground(Color.gray);
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.add(inlabel);
panel.add(input);
panel1.setLayout(new BoxLayout(panel1, BoxLayout.X_AXIS));
panel1.add(compute);
panel1.add(clear);
add (Box.createRigidArea (new Dimension(0, 10)));
panel2.setLayout(new BoxLayout(panel2, BoxLayout.X_AXIS));
panel2.add(outlabel);
panel2.add(output);
setMaximumSize (new Dimension(600, 250));
setMinimumSize (new Dimension(600, 250));
setBackground(Color.white);
add (panel);
add (panel1);
add (panel2);
}
private class ButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
String inputText = input.getText();//sets what is typed by the user
to a String object
String[] splitted = inputText.trim().split("\\p{javaSpaceChar}
{1,}");//makes a String array, and trims all the whitespaces from the user
input
int numberofWords = splitted.length;//it then sets splitted length
to an integer
String numow = Integer.toString(numberofWords);// finally it makes
the numberofwords int into a string
Arrays.sort(splitted);
if (event.getSource()==compute)//if the user presses the compute
button
{
output.setText (numow + " words; " );//the output is the string
of integers of how many words were typed
}
else//if the user presses another button
input.setText(" "); // clear text filed after copying
}
}
}
So based on the desired result...
I would recommend considering using a series of panels, dedicated to generating the layout requirements for each row, then wrapping those together into a single container.
For my money, GridBagLayout presents the most flexible option, while also presenting one of the more complicated at the same time.
This example focuses solely on the layout requirements, you'll have to figure out how to apply the functionality to it later.
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.HeadlessException;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Test");
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() throws HeadlessException {
setBorder(new EmptyBorder(5, 5, 5, 5));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(2, 2, 2, 2);
JPanel fieldPane = new JPanel(new GridBagLayout());
JTextField inputField = new JTextField("Computer Science 1");
fieldPane.add(new JLabel("Input Text:"), gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
fieldPane.add(inputField, gbc);
JPanel buttonPane = new JPanel(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.insets = new Insets(2, 2, 2, 2);
buttonPane.add(new JButton("Computer Statistics"), gbc);
gbc.anchor = GridBagConstraints.LINE_START;
gbc.weightx = 1;
buttonPane.add(new JButton("Clear Text"), gbc);
JPanel resultsPane = new JPanel(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.insets = new Insets(2, 2, 2, 2);
resultsPane.add(new JLabel("Text Statistics Result:"));
gbc.anchor = GridBagConstraints.LINE_START;
gbc.weightx = 1;
resultsPane.add(new JLabel("3 words"), gbc);
gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(fieldPane, gbc);
add(buttonPane, gbc);
add(resultsPane, gbc);
}
}
}
I strongly recommend having a look at Laying Out Components Within a Container for more details about how various layout managers work
You should use Layouts such as BorderLayout that might help you.
Change the JPanels by doing panel.add(new JButton("East"),BorderLayout.EAST);
etc.. I hope it helps. If you dont use layouts they will end up randomized.

positionnig myJTextField beside JComboBox

I want to creat a palet with many JComboBox. like that :
for(int x=0; x<MAX; x++){
box[x] = new JComboBox(new String[]{"op1", "op2", "op3");
}
at the right of each JComboBox i want to create many JTextField. So, in my palet i will have some think like that:
myJComboBox1 myJTextField
anotherJTextField
anotherJTextField
myJComboBox2 myJTextField
anotherJTextField
anotherJTextField
...
How can i do that please ? I tried by setBounds and other layout like FlowLayout and GridLayout but without success.
GridBagLayout is the best solution. However, if you are new to Swing, it might be a bit over complicated. In that case:
Use GridLayout(0, 2) for the main panel.
Wrap the combobox in a Panel with a border layout and add it to north. Add it to the main panel.
Use another panel with GridLayout(0,1) add your text fields to it and add it to the main panel.
and loop...
Adding sample code:
package snippet;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.GridLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class BorderLayoutTest extends JFrame {
static private int MAX = 10 ;
public BorderLayoutTest() {
super(BorderLayoutTest.class.getName());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initComponents();
}
private void initComponents() {
setLayout(new GridLayout(0, 2));
for(int i = 0; i < MAX; i++) {
add(createComboPanel());
add(createPanelWithTextFields());
}
pack();
}
public Component createComboPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.add(new JComboBox<>(new String[] { "First Option", "Second Option", "Third Option" }), BorderLayout.NORTH);
return panel;
}
private Component createPanelWithTextFields() {
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.add(new JTextField(30));
panel.add(new JTextField(30));
panel.add(new JTextField(30));
return panel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override public void run() {
new BorderLayoutTest().setVisible(true);
}
});
}
}
Take a look at GridBagLayout. You can use your window like a table.
myPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
JLabel lbl = new JLabel("bla");
myPanel.add(lbl, gbc);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.weightx = 3;
JTextField tf = new JTextField();
myPanel.add(tf, gbc);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 1;
gbc.weightx = 3;
JTextField othertf = new JTextField();
myPanel.add(othertf, gbc);
You can even set weights and so on for the GridBagConstraints. It is completly adjusted as table. That will result in something like that:
label textfield
textfield
Just re-read the question. Just replace the JLabels with JComboBoxes and it answers your question a little bit better ;)

Categories