JDialog GridBagLayout Not Producing the Look I Want - java

I am trying to create a JDialog using GridBagLayout but I cannot get things looking the way I want. Am I perhaps using the wrong layout model? My code is:
import java.awt.Dialog;
import java.awt.Dialog;
import java.awt.GridBagLayout;
import java.text.NumberFormat;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class alertDialog {
JDialog dialog=null;
private GridBagLayout layout=new GridBagLayout();
private NumberFormat tempFormat = NumberFormat.getIntegerInstance();
public alertDialog(String type_,TimelineRecord timeLine_) {
dialog=new JDialog();
dialog.setTitle("Alert");
dialog.setSize(600, 200);
dialog.setLayout(layout);
dialog.setModalityType(Dialog.ModalityType.MODELESS);
dialog.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
Monitor mon=timeLine_.monitor;
int row=1;
JLabel msg=new JLabel();
if (type_.equals("Temperature")) {
msg.setText(mon.getName()+" temperature has been reached");
}
else {
msg.setText(type_);
}
JButton dismiss=new JButton("Dismiss");
dismiss.addActionListener(new delayButton(timeLine_,dialog));
JButton delay5=new JButton("Delay 5 Minutes");
delay5.addActionListener(new delayButton(5,timeLine_,dialog));
JButton delay10=new JButton("Delay 10 Minutes");
delay10.addActionListener(new delayButton(10,timeLine_,dialog));
JButton delay15=new JButton("Delay 15 Minutes");
delay15.addActionListener(new delayButton(15,timeLine_,dialog));
dialog.add(msg,makeGbc(0,row++));
dialog.add(dismiss,makeGbc(1,row++));
if (mon!=null) {
JLabel currentTemp=new JLabel("Current Temperature");
JLabel newTarget=new JLabel("New Target");
JFormattedTextField temp=new JFormattedTextField(tempFormat);
temp.setText(Double.toString(mon.current));
JFormattedTextField target=new JFormattedTextField(tempFormat);
target.setText(Double.toString(mon.target));
dialog.add(currentTemp,makeGbc(0,row));
dialog.add(temp,makeGbc(1,row));
dialog.add(newTarget,makeGbc(2,row));
dialog.add(target,makeGbc(3,row++));
}
dialog.add(delay5,makeGbc(0,row));
dialog.add(delay10,makeGbc(1,row));
dialog.add(delay15,makeGbc(2,row));
dialog.setVisible(true);
}
public static void main(String[] args) {
TimelineRecord timeline=new TimelineRecord();
new alertDialog("tod",timeline);
}
}
Here is the TimeLineRecord:
import java.util.Timer;
public class TimelineRecord {
// text of event to take place (Saved to XML)
public String eventText;
// time of day for alarm (Saved to XML)
public String tod;
// target temp for alarm (Saved to XML)
public double targetTemp;
// pit temp to change to (Saved to XML)
public double pitTemp;
// meat type
public String meat;
// weight of meat
public double weight;
// Average cook time for this probe in minutes (Saved to XML)
public long avgCookTime;
// total cook time in minutes
public long totalCookTime;
// associated monitor instance (ID saved to XML)
public Monitor monitor=null;
// associated pit probe instance (ID saved to XML)
public Monitor pit=null;
// timer for alarm instance
public Timer timer=null;
// actual time of event
public String actualTod;
// actual temp at event
public double actualTemp;
// actual pit temp at event
public double actualPitTemp;
// Method to set variables
public void setObject(String obj_,String value_) {
switch(obj_) {
case "eventText": eventText=value_;
break;
case "tod": tod=value_;
break;
case "targetTemp": if (!value_.equals("")) {
targetTemp=Double.parseDouble(value_);
}
break;
case "pitTemp": if (!value_.equals("")) {
pitTemp=Double.parseDouble(value_);
}
break;
case "meat": meat=value_;
break;
case "weight": if (!value_.equals("")) {
weight=Double.parseDouble(value_);
}
break;
}
}
}
The Listener:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JDialog;
public class delayButton implements ActionListener {
private int delay=0;
private TimelineRecord timeLine=null;
private JDialog dialog=null;
public delayButton(int minutes_,TimelineRecord timeLine_,JDialog dialog_) {
delay=minutes_;
timeLine=timeLine_;
dialog=dialog_;
}
public delayButton(TimelineRecord timeLine_,JDialog dialog_) {
timeLine=timeLine_;
dialog=dialog_;
}
#Override
public void actionPerformed(ActionEvent arg0) {
if (delay==0) {
System.out.println("Got dismiss for "+timeLine.monitor.getName());
}
else {
System.out.println("Got "+Integer.toString(delay)+" minute delay for "+timeLine.monitor.getName());
}
dialog.dispose();
}
}
And the GBC generator:
public static GridBagConstraints makeGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
Insets WEST_INSETS=new Insets(5,0,5,5);
Insets EAST_INSETS=new Insets(5,5,5,0);
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.anchor = (x == 0) ? GridBagConstraints.WEST : GridBagConstraints.EAST;
gbc.fill = (x == 0) ? GridBagConstraints.BOTH
: GridBagConstraints.HORIZONTAL;
gbc.insets = (x == 0) ? WEST_INSETS : EAST_INSETS;
gbc.weightx = (x == 0) ? 0.1 : 1.0;
gbc.weighty = 1.0;
return gbc;
}
The first line can be any length so I want it to be centered based on length. The button on the second line should be centered. Oddly, the height of the first button in the last line is different from the other buttons. They should all be the same.

try this
import javax.swing.*;
import java.awt.*;
public class AlertDialog extends JDialog {
public AlertDialog(Frame owner) {
super(owner);
createGUI();
}
public AlertDialog(Dialog owner) {
super(owner);
createGUI();
}
private void createGUI() {
JLabel label = new JLabel("My Label");
JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
topPanel.add(label);
JButton button = new JButton("Button");
JPanel centerPanel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
centerPanel.add(button, c);
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
JButton button3 = new JButton("Button 3");
JPanel bottomPanel = new JPanel(new GridLayout(0, 3));
bottomPanel.add(button1);
bottomPanel.add(button2);
bottomPanel.add(button3);
setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
setLayout(new BorderLayout());
add(topPanel, BorderLayout.PAGE_START);
add(centerPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
pack();
setLocationRelativeTo(getParent());
}
}
and version with one panel
import javax.swing.*;
import java.awt.*;
public class AlertDialog extends JDialog {
public AlertDialog(Frame owner) {
super(owner);
createGUI();
}
public AlertDialog(Dialog owner) {
super(owner);
createGUI();
}
private void createGUI() {
JLabel label = new JLabel("My Label");
JButton button = new JButton("Button");
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
JButton button3 = new JButton("Button 3");
setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 3;
add(label, c);
c.gridy++;
c.weightx = 1.0;
c.weighty = 1.0;
add(button, c);
c.gridy++;
c.gridwidth = 1;
c.weighty = 0.0;
c.fill = GridBagConstraints.HORIZONTAL;
add(button1, c);
c.gridx++;
add(button2, c);
c.gridx++;
add(button3, c);
pack();
setLocationRelativeTo(getParent());
}
}
in your code this resize first button on last row (x = 0)
gbc.fill = (x == 0) ? GridBagConstraints.BOTH
: GridBagConstraints.HORIZONTAL

Related

Add Action Listener to RadioPanel

I am currently trying to implement an action listener to my JCheckBox so that when it is selected, it will open a JFileChooser for the user to pick a file they want the GUI to use. For starters how would I get the console to print out "Box clicked!" when a user checks the box?
It has been a while since I've programmed in Swing so any advice helps!
public class RadioPanel extends JPanel implements ActionListener
{
private static final long serialVersionUID = -1890379016551779953L;
private JCheckBox box;
private JLabel label;
public RadioPanel(String message)
{
this.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.WEST;
c.gridx = 0;
c.gridy = 0;
box = new JCheckBox();
this.add(box,c);
c.gridx = 1;
c.gridy = 0;
label = new JLabel(message);
this.add(label, c);
}
I think it's because the code does not have an event listener.
See my code below.
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class RadioPanel extends JPanel implements ActionListener {
private static final long serialVersionUID = -1890379016551779953L;
private JCheckBox box;
private JLabel label;
public RadioPanel(String message) {
this.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.WEST;
c.gridx = 0;
c.gridy = 0;
box = new JCheckBox();
// here
box.addActionListener(event -> {
JCheckBox checkBox = (JCheckBox) event.getSource();
if (checkBox.isSelected()) {
System.out.println("Box clicked!");
}
});
this.add(box, c);
c.gridx = 1;
c.gridy = 0;
label = new JLabel(message);
this.add(label, c);
}
#Override
public void actionPerformed(ActionEvent e) {
}
}
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
AbstractButton abstractButton = (AbstractButton) actionEvent.getSource();
boolean selected = abstractButton.getModel().isSelected();
System.out.println("Is selected :" + selected);
}
};
box.addActionListener(actionListener);

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

Replace panels with another

How can I replace a JPanel or JFrame & its contents with another one by a simple button click in the same container ?
here a simple example that you can follow please show code at lest so we can follow your problem this a snap of code from unknowing source (old one)
package layout;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class CardLayoutExample extends JFrame{
JPanel totelPanel,btnPan,showPan;
JButton btn1,btn2;
public static void main(String[] args) {
CardLayoutExample ex = new CardLayoutExample();
ex.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ex.pack();
ex.setLocationRelativeTo(null);
ex.setTitle("BookClube library system");
ex.setVisible(true);
}
public CardLayoutExample(){
btn1 = new JButton("menu button");
btn2 = new JButton("back button");
CardLayout c1 = new CardLayout();
btnPan = new JPanel();
btnPan.add(btn1);
showPan = new JPanel();
showPan.add(btn2);
totelPanel = new JPanel(c1);
totelPanel.add(btn1,"1");
totelPanel.add(btn2,"2");
c1.show(totelPanel,"1");
JPanel fullLayout = new JPanel(new BorderLayout());
fullLayout.add(totelPanel,BorderLayout.NORTH);
add(fullLayout);
btn1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
c1.show(totelPanel,"2");
}
});
btn2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
c1.show(totelPanel,"1");
}
});
}
}
The trick would be to use CardLayout or modify panel visibility.
Please look at the following example that modifies panel visibility.
public class PanelExample {
private JPanel _myPanel1,_myPanel2;
public void init() {
JFrame frame = new JFrame("Testing");
JPanel mainPanel = new JPanel(new GridBagLayout());
_myPanel1 = new JPanel();
_myPanel1.add(new JLabel("Panel 1"));
_myPanel1.setVisible(true);
_myPanel2 = new JPanel();
_myPanel2.add(new JLabel("Panel 2"));
_myPanel2.setVisible(false);
JButton button = new JButton("Switch to Panel2");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(_myPanel1.isVisible()) {
_myPanel1.setVisible(false);
_myPanel2.setVisible(true);
button.setText("Switch to Panel1");
} else {
_myPanel1.setVisible(true);
_myPanel2.setVisible(false);
button.setText("Switch to Panel2");
}
}
});
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.PAGE_START;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
gbc.weighty = 0;
mainPanel.add(button,gbc);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.CENTER;
gbc.fill = GridBagConstraints.BOTH;
gbc.gridwidth = 2;
gbc.gridheight = 2;
gbc.weightx = 1;
gbc.weighty = 1;
mainPanel.add(_myPanel1,gbc);
mainPanel.add(_myPanel2,gbc);
frame.add(mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
PanelExample exmp = new PanelExample();
exmp.init();
}
}

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

JComboBox, ActionListener, How do I really use them?

Im currently learning java and stuck onto JComboBox.
I have a feel things that I am trying out and hitting the wall for the pass 4 hours.
I am trying to let a user select 1-10 from a ComboBox.
How do I get the value of the combobox?
The value of the combo box is equivalent to quantity.
So I have another value which is maybe $10.
If the user choose quantity 2.
I want to get the value of what the user choose, then take the value of $10 and times it by 2.
The result which is $20 will be displayed on the JTextField.
Please help :(
public class Panel extends JPanel {
public Panel(){
JPanel test = new JPanel(new GridBagLayout());
String[] quantities1 = {"0","1","2","3","4","5","6","7","8","9","10"};
JComboBox quantitiesCB = new JComboBox(quantities1);
quantitiesCB.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
JComboBox combo = (JComboBox)e.getSource();
String currentQuantity = (String)combo.getSelectedItem();
}
}
);
JTextField result = new JTextField();
setLayout(new GridBagLayout());
setPreferredSize(new Dimension(640,480));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 0.1;
gbc.weighty = 0.1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.NORTH;
add(quantitiesCB, gbc);
}
}
Just few changes:
public class Panel extends JPanel {
public Panel(){
JPanel test = new JPanel(new GridBagLayout());
String value = "10";
final JTextField result = new JTextField();
String[] quantities1 = {"0","1","2","3","4","5","6","7","8","9","10"};
JComboBox quantitiesCB = new JComboBox(quantities1);
quantitiesCB.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
JComboBox combo = (JComboBox)e.getSource();
String currentQuantity = (String)combo.getSelectedItem();
int value1 = Integer.valueOf(value);
int value2 = Integer.valueOf(currentQuantity);
String resultText = String.valueOf(value1*value2);
result.setText("$" + resultText);
}
}
);
setLayout(new GridBagLayout());
setPreferredSize(new Dimension(640,480));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 0.1;
gbc.weighty = 0.1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.NORTH;
add(quantitiesCB, gbc);
}
}
I am guessing that you are looking for a way to convert a String to an Integer. That can be done with Integer.valueOf.
Below is a very small/basic demo code that works (but I don't know exactly what you are looking for):
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Panel extends JPanel {
private JTextField result;
private JTextField amount;
public Panel() {
setLayout(new GridBagLayout());
String[] quantities1 = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
JLabel dollar = new JLabel("$");
amount = new JTextField(3);
JComboBox quantitiesCB = new JComboBox(quantities1);
quantitiesCB.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JComboBox combo = (JComboBox) e.getSource();
String currentQuantity = (String) combo.getSelectedItem();
int a;
int q;
try {
a = Integer.valueOf(amount.getText());
q = Integer.valueOf(currentQuantity);
result.setText("$" + String.valueOf(a * q));
} catch (NumberFormatException e1) {
e1.printStackTrace();
// Some invalid number
}
}
});
JLabel equal = new JLabel("=");
result = new JTextField(5);
JLabel quantity = new JLabel("Quantity:");
GridBagConstraints gbc = new GridBagConstraints();
add(dollar, gbc);
add(amount, gbc);
add(quantity, gbc);
add(quantitiesCB, gbc);
add(equal, gbc);
add(result, gbc);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Panel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
You need to make the fixed price and the JTextField final, in order to pass them to your event handler.
Besides, why do you use String for integers? You can just use:
final int FixedPrice = 10;
final JTextField result = new JTextField();
int[] quantities1 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
JComboBox quantitiesCB = new JComboBox(quantities1);
quantitiesCB.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
JComboBox combo = (JComboBox)e.getSource();
int currentQuantity = (Integer)combo.getSelectedItem();
result.setText("$" + String.valueOf(currentQuantity * FixedPrice));
}
}
);

Categories