i'm learning JSwing and i discovered the GridBagLayout.
I'm trying to create a simple calculator, i did it with adding multiple JPanel setting each preferedSize but when i resize the window frame the panels won't resize too.
Then i found out the GridBagLayout.
But this i what i get: Wrong calculator with GridBagLayout
import javax.swing.*;
import java.awt.*;
public class Calc extends JFrame {
private final int WIDTH = 300;
private final int HEIGHT = 450;
public Calc(){
setSize(WIDTH, HEIGHT);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
mainPanel.add(createButtons(), BorderLayout.SOUTH);
add(mainPanel);
}
private JPanel createButtons(){
JPanel panel = new JPanel();
GridBagLayout layout = new GridBagLayout();
panel.setLayout(layout);
GridBagConstraints g = new GridBagConstraints();
g.gridx = 0;
g.gridy = 0;
for(int i = 0; i < 9; i++){
panel.add(new JButton(""+i), g);
g.gridx++;
if(g.gridx == 3) {
g.gridx = 0;
g.gridy++;
}
}
return panel;
}
public static void main(String... args){
Calc calc = new Calc();
calc.setVisible(true);
}
}
it should be something like this:
Right calculator
i tried:
to set an anchor... but it doesn't work,
to create multiple JPanel(one with GridLayout) but doesn't work
if you don't want to spoon code, it's okay.. but from where should i start?
Edit:
I figure out how to arrange the buttons... but i can't set the header to fill all the x-axis:
Code:
import javax.swing.*;
import java.awt.*;
public class ButtonPanel extends JPanel {
JPanel top;
JPanel left;
JPanel right;
private class CButton extends JButton{
private Operation operation;
public CButton(){
}
}
public ButtonPanel(){
initComponent();
initLayout();
}
private void initLayout() {
GridBagLayout layout = new GridBagLayout();
this.setLayout(layout);
layout.columnWeights = new double[] {3,1};
layout.rowWeights = new double[] {1, 1};
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.BOTH;
c.weightx = 5;
this.add(top, c);
c.gridy++;
c.weighty=1;
this.add(left, c);
c.gridx++;
this.add(right, c);
}
private void initComponent() {
top = new JPanel();
top.setLayout(new GridLayout(1, 3));
for(int i = 0; i < 3; i++){
top.add(new JButton("bbb"));
}
left = new JPanel();
left.setLayout(new GridLayout(3,3));
for(int i = 0; i < 9; i++){
left.add(new JButton(""+i));
}
right = new JPanel();
right.setLayout(new GridLayout(3,1));
for(int i = 0; i < 3; i++){
JButton btn = new JButton("aa");
right.add(btn);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("test");
frame.setLayout(new BorderLayout());
frame.add(new ButtonPanel(), BorderLayout.SOUTH);
frame.setSize(300, 450);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
It should be: Image
You can probably do everything within a single panel, having some buttons that span over multiple columns.
So I give you a different example to layout buttons using a single GridBagLayout, here you can define your button arrangement as an array of values, check if it could be a good starting point for your project.
package test;
import static test.Calculator.Buttons.*;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Calculator extends JPanel {
//Here define all possible buttons with labels
public enum Buttons {
PERCENT("%"), CE("CE"), CLEAR("C"),
ONE("1"), TWO("2"), THREE("3"), FOUR("4"), FIVE("5"), SIX("6"), SEVEN("7"), EIGHT("8"), NINE("9"), ZERO("0"),
ADD("+"), SUB("-"), MULT("x"), DIV("/"), RESULT("="), DECPOINT(".");
protected String text;
Buttons(String txt) {
this.text=txt;
}
public String getText() {
return text;
}
};
//This array contains your keypad layout, contiguous repeated elements will span across multiple columns (e.g. ZERO).
protected Buttons[][] keyPad = {
{PERCENT, CE, CLEAR, DIV},
{SEVEN, EIGHT, NINE, MULT},
{FOUR, FIVE, SIX, ADD},
{ONE, TWO, THREE, SUB},
{ZERO, ZERO, DECPOINT, RESULT}
};
Map<JButton, Buttons> sourceMap=new HashMap<>();
ActionListener padListener=new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
onKeyPadPressed(sourceMap.get(e.getSource()));
}
};
public Calculator() {
setLayout(new GridBagLayout());
GridBagConstraints c=new GridBagConstraints();
c.weightx=1.0;
c.weighty=1.0;
c.fill=GridBagConstraints.BOTH;
for (int y=0;y<keyPad.length;y++) {
for (int x=0;x<keyPad[y].length;) {
Buttons b=keyPad[y][x];
if (b==null) {
continue;
}
JButton btn=new JButton(b.getText());
c.gridx=x;
c.gridy=y;
c.gridwidth=0;
while(x<keyPad[y].length&&keyPad[y][x]==b) {
c.gridwidth++;
x++;
}
add(btn,c);
sourceMap.put(btn,b);
btn.addActionListener(padListener);
}
}
}
//Callback method, whenever a button is clicked you get the associated enum value here
protected void onKeyPadPressed(Buttons b) {
System.out.println("Pressed "+b);
switch (b) {
// case ZERO:
// .... here your logic
}
}
public static void main(String[] args) {
JFrame frame=new JFrame("Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new Calculator());
frame.pack();
frame.setVisible(true);
}
}
The code above produces this result, but it's really easy to add/remove buttons and change the layout.
Related
I was wondering if there is an easier way to add vertical labels to the game board instead of adding individual Jlabels and moving them. I currently have a single letter set up and when i try to change the font size to anything over 10 font the text will become a small dot or just disaster.
public class View {
private JFrame frameMain;
private JPanel panelBoard;
private JPanel panelTitle;
private JPanel panelMain;
private JPanel panelY;
private JPanel panel2;
private JTextArea text;
private JLabel jlabel;
private JLabel jlabelY;
private List<JButton> list;
public View(){
frameMain = new JFrame();
frameMain.setLayout(new FlowLayout());
list = new ArrayList<>();
panelMain = new JPanel();
panelY = new JPanel();
panelY.setLayout(null);
panelBoard = new JPanel();
panelTitle = new JPanel();
panelMain.setLayout(new BorderLayout());
Board x = new Board();
GridLayout grid = new GridLayout(15,15);
x.createBoard();
panelBoard.setLayout(grid);
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
list.add(new JButton());
}
}
for(JButton x5:list){
panelBoard.add(x5);
}
jlabel = new JLabel("game");
jlabelY = new JLabel("A");
Dimension size = jlabelY.getPreferredSize();
jlabelY.setBounds(17,10 ,size.width,size.height);
jlabelY.setFont(new Font("Ariel", Font.BOLD, 10));
panelTitle.setPreferredSize(new Dimension(50,50));
panelY.setPreferredSize(new Dimension(25,600));
panelBoard.setPreferredSize(new Dimension(400,400));
panelMain.setPreferredSize(new Dimension(600,600));
panelY.add(jlabelY);
panelTitle.add(jlabel);
panelMain.add(panelTitle, BorderLayout.NORTH);
panelMain.add(panelBoard, BorderLayout.CENTER);
panelMain.add(panelY, BorderLayout.WEST);
frameMain.add(panelMain);
frameMain.setSize(600, 600);
frameMain.pack();
frameMain.setVisible(true);
}
You "could" do this using a GridLayout, but where's the fun in that. The following example makes use of GridBagLayout to layout the text and the buttons.
Trying to align components across containers is, well, let's just "hard" and leave it there, for this reason, the row labels and buttons are added to the same container. This ensures that the height of each row is based on the needs of the components within the row.
There's a few other ways you could do this, but this gives you the basic idea.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new View();
}
});
}
public class View {
private JFrame frameMain;
private JPanel panelBoard;
private JPanel panelTitle;
private JPanel panelMain;
private JPanel panel2;
private JTextArea text;
private JLabel jlabel;
private JLabel jlabelY;
private List<JButton> list;
public View() {
frameMain = new JFrame();
frameMain.setLayout(new FlowLayout());
list = new ArrayList<>();
panelMain = new JPanel();
panelBoard = new JPanel();
panelTitle = new JPanel();
panelMain.setLayout(new BorderLayout());
panelBoard.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
for (int y = 0; y < 15; y++) {
gbc.gridx = 0;
gbc.gridy = y;
JLabel rowLabel = new JLabel(Character.toString('A' + y));
rowLabel.setFont(new Font("Ariel", Font.BOLD, 24));
panelBoard.add(rowLabel, gbc);
for (int x = 0; x < 15; x++) {
gbc.gridx++;
JButton btn = new JButton();
list.add(btn);
panelBoard.add(btn, gbc);
}
}
jlabel = new JLabel("game");
panelTitle.add(jlabel);
panelMain.add(panelTitle, BorderLayout.NORTH);
panelMain.add(panelBoard, BorderLayout.CENTER);
frameMain.add(panelMain);
frameMain.pack();
frameMain.setVisible(true);
}
}
}
My friend has given me a practice problem regarding prime number. Numbers 1 to n needs to be displayed in a new window. I also can't figure out on how I can use the input I got from panel1 to panel2. I'm very new to GUI since I haven't gone there when I studied Java a few years back. Hope you can help!
I haven't done much with the GUI since I don't really know where to start, but I've watched youtube videos and have gone through many sites on how to start with a GUI. Here's what I have done:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class sieve
{
private JPanel contentPane;
private MyPanel input;
private MyPanel2 sieve;
private void displayGUI()
{
JFrame frame = new JFrame("Input");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new CardLayout());
input = new MyPanel(contentPane);
sieve = new MyPanel2();
contentPane.add(input, "Input");
contentPane.add(sieve, "Sieve of Erasthoneses");
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new CardLayoutExample().displayGUI();
}
});
}
}
class MyPanel extends JPanel {
private JTextField text;
private JLabel label1;
private JButton OK;
private JButton cancel;
private JPanel contentPane;
public MyPanel(JPanel panel) {
contentPane = panel;
label1 = new JLabel ("Enter a number from 1 to n:");
text = new JTextField(1000);
OK = new JButton ("OK");
cancel = new JButton ("Cancel");
setPreferredSize (new Dimension (500, 250));
setLayout (null);
text.setBounds (145, 50, 60, 25);
OK.setBounds (450, 30, 150, 50);
cancel.setBounds (250, 30, 150, 50);
OK.setSize(315, 25);
OK.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.next(contentPane);
}
});
add (text);
add (label1);
add (OK);
add (cancel);
}
}
class MyPanel2 extends JPanel {
private JFrame frame;
private JLabel label;
JLabel label1;
public MyPanel2()
{
frame = new JFrame("Sieve of Eratosthenes");
label = new JLabel("The Prime numbers from 2 to " + num + " are");
num1 = num;
boolean[] bool = new boolean[num1];
for (int i = 0; i < bool.length; i++)
{
bool[i] = true;
}
for (int i = 2; i < Math.sqrt(num1); i++)
{
if(bool[i] == true)
{
for(int j = (i*i); j < num1; j = j+i)
{
bool[j] = false;
}
}
}
for (int i = 2; i< bool.length; i++)
{
if(bool[i]==true)
{
label1 = new JLabel(" " + label[i]);
}
}
}
}
Thanks for your help!
Your code had many compilation errors.
Oracle has a helpful tutorial, Creating a GUI With JFC/Swing. Skip the Netbeans section. Review all the other sections.
I reworked your two JPanels. When creating a Swing application, you first create the GUI. After the GUI is created, you fill in the values to be displayed.
I created the following GUI. Here's the input JPanel.
Here's the Sieve JPanel.
I used Swing layout managers to create the two JPanels. Using null layouts and absolute positioning leads to many problems.
I created the sieve JPanel, then populated it with values. You can see how I did it in the source code.
Here's the complete runnable code. I made the classes inner classes.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Eratosthenes {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Eratosthenes().displayGUI();
}
});
}
private CardLayout cardLayout;
private JFrame frame;
private JPanel contentPane;
private InputPanel inputPanel;
private SievePanel sievePanel;
private void displayGUI() {
frame = new JFrame("Input");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
cardLayout = new CardLayout();
contentPane.setLayout(cardLayout);
inputPanel = new InputPanel();
sievePanel = new SievePanel();
contentPane.add(inputPanel.getPanel(), "Input");
contentPane.add(sievePanel.getPanel(), "Sieve");
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public void cancelAction() {
frame.dispose();
System.exit(0);
}
public class InputPanel {
private JPanel panel;
private JTextField textField;
public InputPanel() {
this.panel = createMainPanel();
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new BorderLayout());
JPanel entryPanel = new JPanel(new FlowLayout());
entryPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JLabel label = new JLabel("Enter a number from 1 to n:");
entryPanel.add(label);
textField = new JTextField(10);
entryPanel.add(textField);
panel.add(entryPanel, BorderLayout.BEFORE_FIRST_LINE);
JPanel buttonPanel = new JPanel(new FlowLayout());
entryPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JButton okButton = new JButton("OK");
buttonPanel.add(okButton);
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int inputNumber = valueOf(textField.getText().trim());
if (inputNumber < 2) {
return;
}
sievePanel.updatePrimeLabel(inputNumber);
sievePanel.updatePrimeNumbers(inputNumber);
cardLayout.show(contentPane, "Sieve");
}
private int valueOf(String number) {
try {
return Integer.valueOf(number);
} catch (NumberFormatException e) {
return -1;
}
}
});
JButton cancelButton = new JButton("Cancel");
buttonPanel.add(cancelButton);
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cancelAction();
}
});
okButton.setPreferredSize(cancelButton.getPreferredSize());
panel.add(buttonPanel, BorderLayout.AFTER_LAST_LINE);
return panel;
}
public JPanel getPanel() {
return panel;
}
}
public class SievePanel {
private JLabel primeLabel;
private JList<Integer> primeNumbersList;
private JPanel panel;
public SievePanel() {
this.panel = createMainPanel();
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
Font titlefont = panel.getFont().deriveFont(Font.BOLD, 24f);
JPanel textPanel = new JPanel(new BorderLayout());
JLabel titleLabel = new JLabel("Sieve of Eratosthenes");
titleLabel.setFont(titlefont);
titleLabel.setHorizontalAlignment(JLabel.CENTER);
textPanel.add(titleLabel, BorderLayout.BEFORE_FIRST_LINE);
primeLabel = new JLabel(" ");
primeLabel.setHorizontalAlignment(JLabel.CENTER);
textPanel.add(primeLabel, BorderLayout.AFTER_LAST_LINE);
panel.add(textPanel, BorderLayout.BEFORE_FIRST_LINE);
primeNumbersList = new JList<>();
JScrollPane scrollPane = new JScrollPane(primeNumbersList);
panel.add(scrollPane, BorderLayout.CENTER);
JButton button = new JButton("Return");
panel.add(button, BorderLayout.AFTER_LAST_LINE);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
cardLayout.show(contentPane, "Input");
}
});
return panel;
}
public void updatePrimeLabel(int inputNumber) {
primeLabel.setText("The prime numbers from 2 to " +
inputNumber + " are:");
}
public void updatePrimeNumbers(int inputNumber) {
DefaultListModel<Integer> primeNumbers =
new DefaultListModel<>();
boolean[] bool = new boolean[inputNumber];
for (int i = 0; i < bool.length; i++) {
bool[i] = true;
}
for (int i = 2; i < Math.sqrt(inputNumber); i++) {
if (bool[i] == true) {
for (int j = (i * i); j < inputNumber; j = j + i) {
bool[j] = false;
}
}
}
for (int i = 2; i < bool.length; i++) {
if (bool[i] == true) {
primeNumbers.addElement(i);
}
}
primeNumbersList.setModel(primeNumbers);
}
public JPanel getPanel() {
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 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","");
I want to create a grid of buttons. Between the buttons there should not be a space, so that the buttons touch the next buttons.
import javax.swing.*;
import java.awt.*;
import javax.swing.border.*;
public class Bild extends JFrame {
public static class createButton extends JPanel {
public createButton() {
JButton b = new JButton();
Border border = new LineBorder(Color.BLACK, 1);
b.setBorder(border);
b.setBackground(Color.WHITE);
b.setPreferredSize (new Dimension(10,10));
this.add(b);
}
}
public Bild() {
GridLayout layout = new GridLayout(10,10,0,0);
this.setLayout(layout);
for (int i = 0; i < 100; i++) {
this.add(new createButton());
}
}
}
import javax.swing.*;
import java.awt.*;
public class Main{
public static void main (String[] args) {
JFrame frame = new Bild();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setVisible(true);
}
}
with the grid layout I tried to get a 10x10 grid of buttons. But although I created the GridLayout with the parameters 10,10,0,0 there is a space between the buttons.
Where is my mistake?
It's because createButton is actually a JPanel, which has a FlowLayout as it's layout manager by default. Make createButton a method that returns a JButton and the button will span across the whole space within the cell. (You can remove the setPreferredSize()). If you want the buttons to remain 10x10 pixels and be centered within the frame: Set the layout manager of the main panel to a GridBagLayout and add a JPanel with the GridLayout to it. Maybe also override getPreferredSize() of the buttons rather than calling setPreferredSize().
Buttons spanning across whole screen:
class Bild extends JFrame {
public JButton createButton() {
JButton b = new JButton();
Border border = new LineBorder(Color.BLACK, 1);
b.setBorder(border);
b.setBackground(Color.WHITE);
return b;
}
public Bild() {
setLayout(new GridLayout(10, 10));
for (int i = 0; i < 100; i++) {
add(createButton());
}
}
}
Buttons remaining 10x10:
class Bild extends JFrame {
public JButton createButton() {
JButton b = new JButton() {
#Override
public Dimension getPreferredSize() {
return new Dimension(10, 10);
}
};
Border border = new LineBorder(Color.BLACK, 1);
b.setBorder(border);
b.setBackground(Color.WHITE);
return b;
}
public Bild() {
JPanel panel = new JPanel(new GridLayout(10, 10));
for (int i = 0; i < 100; i++) {
panel.add(createButton());
}
setLayout(new GridBagLayout());
add(panel);
}
}