Java - Enable Combo boxes depending on radio button - java

I'm trying to make taxi booking application. Now, if I (for example) want to schedule by mobile application, then I want to enable combobox with drivers name and if someone schedule via phone call, then I want to enable combobox with dispatchers names. How? I tryied something in initActions(), but, obvious it's not working...
public class OrderWindow extends JFrame {
private JLabel lblCustomerName;
private JTextField txtCustomerName;
private JLabel lblDateOrder;
private JPanel pnlDateOrder;
private JLabel lblDepartureAdress;
private JTextField txtADepartureAdress`
private JComboBox cbDriver;
private JRadioButton rbMobileApp;
private JRadioButton rbPhoneCall;
private ButtonGroup bgOrder;
public OrderWindow(){
setTitle("Scheduling");
setSize(400, 400);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
initGUI();
initActions();
}
private void initActions() {
rbMobileApp.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource()==rbMobileApp) {
setEnabled(rbMobilnaAplikacija.isSelected());
}
}
});
}
private void initGUI() {
MigLayout mig = new MigLayout("wrap 2", "[][]", "[]10[][]10[]");
setLayout(mig);
lblCustomerName = new JLabel("Name and Lastname");
txtCustomerName = new JTextField(20);
lblDepartureAdress = new JLabel("Adress");
txtDepartureAdress = new JTextField(20);
rbMobileApp = new JRadioButton("Application");
rbPhoneCall = new JRadioButton("Call");
bgPorudzbina = new ButtonGroup();
add(lblCustomerName);
add(txtCustomerName);
add(lblDepartureAdress);
add(txtDepartureAdress);
add(rbMobileApp);
add(rbPhoneCall);
bgOrder = new ButtonGroup();
bgOrder.add(rbMobileApp);
bgOrder.add(rbPhoneCall);
}
}

If you have just 2 JRadioButtons and 2 JComboBoxes, then the solution is simple: Give the JRadioButtons an ItemListener that checks if the radio is selected, and if so, select the corresponding JComboBox.
e.g.,
radioBtn.addItemListener(evt -> {
combo.setEnabled(evt.getStateChange() == ItemEvent.SELECTED);
});
If you have a bunch of JRadioButton / JComboBox combinations, then you need a more robust way to connect the two, and that can be achieved by either using a Map such as a HashMap, or by putting both objects into their own class, for example something like:
import java.awt.event.ItemEvent;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JRadioButton;
public class RadioCombo<T> {
private JRadioButton radioBtn;
private JComboBox<T> combo;
public RadioCombo(String text, DefaultComboBoxModel<T> model) {
radioBtn = new JRadioButton(text);
combo = new JComboBox<>(model);
combo.setEnabled(false);
radioBtn.addItemListener(evt -> {
combo.setEnabled(evt.getStateChange() == ItemEvent.SELECTED);
});
}
public JRadioButton getRadioBtn() {
return radioBtn;
}
public JComboBox<T> getCombo() {
return combo;
}
}
Then you could use it like so:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
#SuppressWarnings("serial")
public class TestRadioCombo extends JPanel {
private static final String[] DATA = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
private static final String[] INNER_DATA = {"One", "Two", "Three", "Four", "Five"};
private static final int GAP = 3;
public TestRadioCombo() {
ButtonGroup buttonGroup = new ButtonGroup();
setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
setLayout(new GridBagLayout());
for (String datum : DATA) {
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>();
for (String innerDatum : INNER_DATA) {
String item = datum + " - " + innerDatum;
model.addElement(item);
}
RadioCombo<String> radioCombo = new RadioCombo<>(datum, model);
buttonGroup.add(radioCombo.getRadioBtn());
addRadioCombo(radioCombo);
}
}
private void addRadioCombo(RadioCombo<String> radioCombo) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = GridBagConstraints.RELATIVE;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(GAP, GAP, GAP, 2 * GAP);
gbc.weightx = 1.0;
gbc.weighty = 1.0;
add(radioCombo.getRadioBtn(), gbc);
gbc.gridx = 1;
gbc.anchor = GridBagConstraints.EAST;
gbc.insets = new Insets(GAP, GAP, GAP, GAP);
add(radioCombo.getCombo(), gbc);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new TestRadioCombo());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
Another option is to have a bunch of JRadioButtons and only one JComboBox, and then in your radio button item listener, swap the JComboBox's model depending on which JRadioButton was selected.

Related

More efficient way to add a vertical row of letters to a gameboard GUI

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

Java, GridBagLayout. How add components right to other component

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.

How to make a new JButton instance in a existing button group everytime a Jbutton is pressed(clicked)

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

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","");

JTextField Everything looks ok in Eclipse but won't compile

Can someone please tell me what's wrong with this code?
I need it to pop up a frame and fill the frame with certain field a namer field and an intake field and also display a button at the bottom of the grid.
Any help would be welcomed, Thanks!!
import java.awt.*;
import javax.swing.*;
public class FrameDemo
//To create the gui and show it.
{
public static void createAndShowGUI()
{
//create and set up the window.
JFrame frame = new JFrame("RungeKutta");
GridLayout first = new GridLayout(1,14);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create, name and Populate TextField
JTextField PL = new JTextField("Pendulum Length", 20);
//Set TextField to Uneditable. Each will have Empty Field Below For Variables
PL.setEditable(false);
//Set Textfield for user entered dat
JTextField PLv = new JTextField();
//Allow handler for user input on Empty Textfield?
JTextField AD = new JTextField("Angular Displacement", 20);
AD.setEditable(false);
JTextField ADv = new JTextField();
JTextField AV = new JTextField("Angular Velocity", 20);
AV.setEditable(false);
JTextField Avv = new JTextField();
JTextField TS= new JTextField("Time Steps", 20);
TS.setEditable(false);
JTextField TSv = new JTextField();
JTextField MT = new JTextField("Max Time", 20);
MT.setEditable(false);
JTextField MTv = new JTextField();
JTextField V = new JTextField("Viscosity (0-1)", 20);
V.setEditable(false);
JTextField Vv = new JTextField();
//Create Button to Restart
JButton BNewGraph = new JButton("Draw New Graph"); //Button to restart entire drawing process
JLabel emptyLabel = new JLabel("");
emptyLabel.setPreferredSize(new Dimension(600,500));
frame.getContentPane().add(PL, first);
frame.getContentPane().add(PLv, first);
frame.getContentPane().add(AD, first);
frame.getContentPane().add(ADv, first);
frame.getContentPane().add(AV, first);
frame.getContentPane().add(Avv, first);
frame.getContentPane().add(TS, first);
frame.getContentPane().add(TSv, first);
frame.getContentPane().add(MT, first);
frame.getContentPane().add(MTv, first);
frame.getContentPane().add(V, first);
frame.getContentPane().add(Vv, first);
frame.getContentPane().add(BNewGraph, first);
//display the window
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args)
{
//add job to event scheduler
//create and show GUI
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
This is not how you use GridLayout:
frame.getContentPane().add(PL, first);
Instead you'd set the container's layout using the layout manager:
frame.getContentPane().setLayout(first);
and then add components to the container:
frame.getContentPane().add(PL);
frame.getContentPane().add(PLv);
frame.getContentPane().add(AD);
frame.getContentPane().add(ADv);
frame.getContentPane().add(AV);
frame.getContentPane().add(Avv);
frame.getContentPane().add(TS);
frame.getContentPane().add(TSv);
frame.getContentPane().add(MT);
frame.getContentPane().add(MTv);
// and so on for all the components.
You will want to read the tutorial on how to use GridLayout which you can find here: GridLayout Tutorial.
As an aside, note that this:
frame.getContentPane().add(PL);
can be shortened to this:
frame.add(PL);
Also you will want to study and learn Java naming conventions: class names begin with an upper case letter and all method and variables with lower case letters. Also avoid variable names like pl or plv, or ad or adv, and instead use names that are a little bit longer and have meaning, names that make your code self-commenting. So instead of AD, consider angularDisplacementField for the JTextfield's name.
Myself, I'd use a GridBagLayout and do something like:
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.swing.*;
public class GuiDemo extends JPanel {
// or better -- use an enum for this
public static final String[] FIELD_LABELS = {
"Pendulum Length", "Angular Displacement", "Angular Velocity",
"Time Steps", "Max Time", "Viscocity (0-1)"
};
private static final int TEXT_FIELD_COLUMNS = 10;
private static final int GAP = 3;
private static final Insets RIGHT_GAP_INSETS = new Insets(GAP, GAP, GAP, 3 * GAP);
private static final Insets BALANCED_INSETS = new Insets(GAP, GAP, GAP, GAP);
private Map<String, JTextField> labelFieldMap = new HashMap<>();
public GuiDemo() {
JPanel labelFieldPanel = new JPanel(new GridBagLayout());
int row = 0;
// to make sure that no focusAccelerator is re-used
Set<Character> focusAccelSet = new HashSet<>();
for (String fieldLabelLText : FIELD_LABELS) {
JLabel fieldLabel = new JLabel(fieldLabelLText);
JTextField textField = new JTextField(TEXT_FIELD_COLUMNS);
labelFieldPanel.add(fieldLabel, getGbc(row, 0));
labelFieldPanel.add(textField, getGbc(row, 1));
labelFieldMap.put(fieldLabelLText, textField);
for (char c : fieldLabelLText.toCharArray()) {
if (!focusAccelSet.contains(c)) {
textField.setFocusAccelerator(c);
fieldLabel.setDisplayedMnemonic(c);
focusAccelSet.add(c);
break;
}
}
row++;
}
JButton button = new JButton(new DrawGraphAction("Draw New Graph"));
labelFieldPanel.add(button, getGbc(row, 0, 2, 1));
setLayout(new BorderLayout(GAP, GAP));
add(labelFieldPanel, BorderLayout.CENTER);
}
private class DrawGraphAction extends AbstractAction {
public DrawGraphAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO calculation method
}
}
public static GridBagConstraints getGbc(int row, int column) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = column;
gbc.gridy = row;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
if (column == 0) {
gbc.anchor = GridBagConstraints.LINE_START;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = RIGHT_GAP_INSETS;
} else {
gbc.anchor = GridBagConstraints.LINE_END;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = BALANCED_INSETS;
}
return gbc;
}
public static GridBagConstraints getGbc(int row, int column, int width, int height) {
GridBagConstraints gbc = getGbc(row, column);
gbc.gridwidth = width;
gbc.gridheight = height;
gbc.insets = BALANCED_INSETS;
gbc.fill = GridBagConstraints.BOTH;
return gbc;
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Gui Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new GuiDemo());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Categories