im having a little trouble with this GUI. Im new to making GUI's so if its something basic im sorry for asking. I cant seem to find the answer to my problem anywhere on google.
The problem im having is when i click on any of the buttons i get an error when any one of the textfields are left empty. here is my code so far
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JOptionPane;
public class MainGUI extends JFrame implements ActionListener{
ArrayList<Object> list;
JTextField name, surname, age, height, weight;
JComboBox<String> sportList, gender;
JButton btnSave;
JButton btnExit;
JButton btnclrtxt;
/**
* #param args
*/
public MainGUI() {
super("Adding members");
this.setLayout(new BorderLayout());
JPanel panel = new JPanel(new FlowLayout());
name = new JTextField(10);
surname = new JTextField(10);
age = new JTextField(10);
height = new JTextField(5);
weight = new JTextField(10);
gender = new JComboBox<String>(new String[] { "Male", "Female" });
sportList = new JComboBox<String>(new String[] { "Football",
"HandBall", "BasketBall", "Rugby", "Hockey", "Tennis" });
panel.add(new JLabel("Name:"));
panel.add(name);
panel.add(new JLabel("Surname:"));
panel.add(surname);
panel.add(new JLabel("Age:"));
panel.add(age);
panel.add(new JLabel("Gender:"));
panel.add(gender);
panel.add(new JLabel("Height:"));
panel.add(height);
panel.add(new JLabel("Weight:"));
panel.add(weight);
panel.add(new JLabel("Sport Speciality:"));
panel.add(sportList);
btnSave = new JButton("Save member");
panel.add(btnSave);
btnSave.addActionListener(this);
btnclrtxt = new JButton("Clear text");
panel.add(btnclrtxt);
btnclrtxt.addActionListener(this);
btnExit = new JButton("Exit");
panel.add(btnExit);
btnExit.addActionListener(this);
this.pack();
this.add(panel);
this.setSize(400, 300);
this.setVisible(true);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new MainGUI();
}
public void actionPerformed(ActionEvent e) {
String namestr = name.getText().toLowerCase();
String surnameStr = surname.getText().toLowerCase();
int ageNum = Integer.parseInt(age.getText().toLowerCase());
double heightNum = Double.parseDouble(height.getText().toLowerCase());
double weightNum = Double.parseDouble(weight.getText().toLowerCase());
String sportsStr = sportList.getSelectedItem().toString();
String genderStr = gender.getSelectedItem().toString();
if(e.getSource()==btnSave) {
list = new ArrayList<Object>();
list.add("Name is "+namestr);
list.add("Surname is "+surnameStr);
list.add("Age is "+ageNum);
list.add("Height is "+heightNum);
list.add("Weight is "+weightNum);
list.add("Sport "+sportsStr);
list.add("Gender "+genderStr);
FileRead.writeFile(list);
System.out.println("Done!");
}
if(e.getSource()==btnExit) {
dispose();
System.exit(0);
}
if(e.getSource()==btnclrtxt) {
name.setText("");
surname.setText("");
age.setText("");
height.setText("");
weight.setText("");
}
}
}
wotking, but you don't test if JTextField.isEmpty, then parsing throws correct exception, instead of that to use
JFormattedTextField with NumberFormatter, then default valur is 0 (zero)
JSpinner with SpinnerNumberModel, then default valur is 0 (zero)
add DocumentFilter to plain JTextField with filtering non_numeric chars, but still required to test if JTextField.isEmpty()
I suspect this is because of these fields:
int ageNum = Integer.parseInt(age.getText().toLowerCase());
double heightNum = Double.parseDouble(height.getText().toLowerCase());
double weightNum = Double.parseDouble(weight.getText().toLowerCase());
The parsing will throw an exception if any of these fields is empty, or contains an incorrect value; make sure you check they contain a (valid) value. Use a JFormattedTextField, for example.
Related
I have to display a map containing two columns and the size is dynamic. I am currently displaying it in a panel, but the problem is I cannot start each row of the map in the new line, rather it depends on the frame size of the display. Here is the full code:
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
import java.awt.BorderLayout;
import java.awt.Image;
public class P05 {
private JLabel label;
private JLabel label1;
private JLabel label3;
private JTextField tf;
private JPanel panel;
public P05() {
JFrame frame = new JFrame("Search result and score");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
JPanel buttonPane = new JPanel();
label = new JLabel("Search Result: ");
label1 = new JLabel();
label3 = new JLabel("Score: ");
tf=new JTextField(10);
tf.setBounds(10,10, 150,20);
JButton button = new JButton("Search");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String text = tf.getText();
label1.setText("The input query is " + text);
panel.removeAll();
panel.add(label);
panel.add(label3);
int i = 0;
Map < String, Double> map = new HashMap < String, Double> ();
map.put("Jennifer Anniston", 31.0);
map.put("brad_pit", 29.0);
map.put("Angelina Jolie", 30.0);
map.put("badley", 21.0);
map.put("Leonardo Decaprio", 43.0);
map.put("Kate Winslet", 41.0);
map.put("Julia Roberts", 40.0);
map.put("Emma Watson", 34.0);
map.put("Mayim Bialik", 28.0);
map.put("Cobie Smulders", 28.0);
for(String item:map.keySet()) {
JTextField t1[] = new JTextField[12];
t1[i] = new JTextField(20);
t1[i].setText(item );
panel.add(t1[i]);
JTextField t2[] = new JTextField[12];
t2[i] = new JTextField(5);
t2[i].setText(Double.toString(map.get(item)));
panel.add(t2[i]);
i++;
}
panel.add(label1);
panel.revalidate();
}
});
buttonPane.add(tf);
buttonPane.add(button);
panel = new JPanel();
frame.add(buttonPane, BorderLayout.NORTH);
frame.add(panel);
frame.setVisible(true);
}
public static void main(String[] args) {
new P05();
}
The output looks like somewhat this:
The quick and dirty solution right now is for me to set the frame size of lower width and it will come in a new line, but in that case, if the text field contains a value with many characters it will not show the whole text. So need a solution to add a new line after each row.
I am simply making a user interface and all i want it to do after the button is pressed is display thanks... I am pretty new to this but from what i see there are no errors? I have tried playing around with the set visible and to no avail...Any help is great thanks
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JList;
public class GuiApp1 {
public static void main(String args[]) {
String title = (args.length == 0 ? "CheckBox Sample" : args[0]);
JFrame frame = new JFrame(title);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel panel = new JPanel(new GridLayout(0, 1));
Border border = BorderFactory.createTitledBorder("Pizza Toppings");
panel.setBorder(border);
JLabel label1 = new JLabel("Enter name below:");
panel.add(label1);
JTextField field = new JTextField(20);
panel.add(field);
JCheckBox check = new JCheckBox("Car0");
panel.add(check);
check = new JCheckBox("Car1");
panel.add(check);
check = new JCheckBox("Car2");
panel.add(check);
check = new JCheckBox("Car3");
panel.add(check);
check = new JCheckBox("Car4");
panel.add(check);
JButton button = new JButton("Submit");
final JPanel listPanel = new JPanel();
listPanel.setVisible(false);
JLabel listLbl = new JLabel("Vegetables:");
listPanel.add(listLbl);
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
listPanel.setVisible(!listPanel.isVisible());
panel.setVisible(!panel.isVisible());
}
});
Container contentPane = frame.getContentPane();
contentPane.add(panel, BorderLayout.CENTER);
contentPane.add(button, BorderLayout.SOUTH);
frame.setSize(300, 300);
frame.setResizable(true);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
}
The reason for the vegetables panel not appearing is simple: Xou never add ist to the contentPane.
For the code to function properly you need to add/remove the panels in the ActionListener of the button:
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
listPanel.setVisible(!listPanel.isVisible());
panel.setVisible(!panel.isVisible());
if (listPanel.isVisible()) {
contentPane.remove(panel); // Vegetables are visible, so remove the Cars
contentPane.add(listPanel, BorderLayout.CENTER); // And add the Vegetables
} else {
contentPane.remove(listPanel); // Vice versa
contentPane.add(panel, BorderLayout.CENTER);
}
}
});
Then, you need to move the ActionListener below the contentPane declaration and make it final.
Also you should consider putting the different checkboxes is different variables, so you can read the state of them. If you don't want to have so many variables hanging you could put them into an array.
JCheckBox[] checks = new JCheckbox[5];
checks[0] = new JCheckBox("Car0");
panel.add(checks[0]);
...
So I want to change the image showing every time i press the Roll button but whenever I try to do it I double instantiate the JFrame. I would like to use the ActionListener this way if it is posible.
Here is my code:
import javax.swing.JFrame;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class DiceFrame extends JFrame{
ImageIcon[] dice_images = new ImageIcon[7];
String score = "This is a test";
JPanel mainPanel;
JPanel scorePanel;
JPanel buttonPanel;
JLabel picLabel;
JTextArea scoreField;
JButton roll;
JButton save;
ActionListener action;
ActionListener output;
public DiceFrame(){
super();
mainPanel = new JPanel();
scorePanel = new JPanel();
buttonPanel = new JPanel();
roll = new JButton("Roll");
save = new JButton("Save");
picLabel = new JLabel();
scoreField = new JTextArea();
setSize(400,300);
setTitle("Dice Program");
loadImage();
getContentPane().add(mainPanel, BorderLayout.CENTER);
getContentPane().add(scorePanel, BorderLayout.EAST);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
mainPanel.add(picLabel);
picLabel.setIcon(dice_images[0]);
buttonPanel.add(roll);
buttonPanel.add(save);
scorePanel.add(scoreField);
scoreField.setText(score);
roll.addActionListener(action);
save.addActionListener(output);
}
private void loadImage()
{
dice_images [0] = new ImageIcon("res/dice_img/die_01_sm.gif");
dice_images [1] = new ImageIcon("res/dice_img/die_02_sm.gif");
dice_images [2] = new ImageIcon("res/dice_img/die_03_sm.gif");
dice_images [3] = new ImageIcon("res/dice_img/die_04_sm.gif");
dice_images [4] = new ImageIcon("res/dice_img/die_05_sm.gif");
dice_images [5] = new ImageIcon("res/dice_img/die_06_sm.gif");
dice_images [6] = new ImageIcon("res/dice_img/die_01_sm.gif");
}
public static void main(String [] args){
DiceFrame frame = new DiceFrame();
frame.setDefaultLookAndFeelDecorated(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class DiceActionListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e){}
}
class SaveActionListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e){}
}
I dont know what to put inside the actionPerformed method in order to not create another instance of the JFrame.
Do something like below code. Create a method that can change your image icon. Then call it from as part of your button click. Have a look at the comments.
import javax.swing.JFrame;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class DiceFrame extends JFrame {
ImageIcon[] dice_images = new ImageIcon[7];
String score = "This is a test";
JPanel mainPanel, scorePanel, buttonPanel;
JLabel picLabel;
JTextArea scoreField;
JButton roll, save;
public DiceFrame(){
super();
mainPanel = new JPanel();
scorePanel = new JPanel();
buttonPanel = new JPanel();
roll = new JButton("Roll");
save = new JButton("Save");
picLabel = new JLabel();
scoreField = new JTextArea();
setSize(400,300);
setTitle("Dice Program");
loadImage();
getContentPane().add(mainPanel, BorderLayout.CENTER);
getContentPane().add(scorePanel, BorderLayout.EAST);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
mainPanel.add(picLabel);
picLabel.setIcon(dice_images[0]);
buttonPanel.add(roll);
buttonPanel.add(save);
scorePanel.add(scoreField);
scoreField.setText(score);
save.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {
System.out.println("You clicked save");
}
});
roll.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {
//call your icon change method with the index you want to change it to
changeIcon(3);
}
});
}
private void loadImage() {
//use a loop insted of repeting the add, but becareful if i < 10 because your file names need to match :)
for(int i = 0; i < 7; i++) {
dice_images [i] = new ImageIcon("res/dice_img/die_0" + i + "_sm.gif");
}
}
public static void main(String [] args) {
DiceFrame frame = new DiceFrame();
frame.setDefaultLookAndFeelDecorated(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
//create a method to change your icon
public void changeIcon(int imageIndex) {
picLabel.setIcon(this.dice_images[imageIndex]);
}
}
I am trying to add text in a JTextArea.
But i need some of the text to be strike through and some to added as it is.
I have searched over the internet, but couldn't find any answer.
Any help on what to refer?
JTextArea allow you set font style, but you cannot set style to text partially. Please see the code below, you can use setFont method to specify font with strikethru style, but it applies to all text in the JTextArea:
JTextArea area = new JTextArea();
Font font = new Font("arial", Font.PLAIN, 12);
Map fontAttr = font.getAttributes();
fontAttr.put (TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
Font myFont = new Font(fontAttr);
area.setFont (myFont);
area.setText ("Hello");
Whereas, if you want some text are in strikethru and some not, then you have to use JTextPane with StyledDocument, but I do not recommend this because you need a lot of tweaking to display your content with specific style. Below code may give you the idea:
DefaultStyledDocument doc = new DefaultStyledDocument();
StyleContext sc = new StyleContext();
Style style = sc.addStyle("strikethru", null);
StyleConstants.setStrikeThrough (style,true);
doc.insertString (0, "Hello ", null);
doc.insertString (6, "strike through ", style);
JTextPane pane = new JTextPane(doc);
You can use below code. Here some of the strike text "#11#","#22#" and some to added text "#yicHFRx1nc#" ,"#icHFRx1nc#" which replace of strike text.
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class JTextAreaExample {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public JTextAreaExample() {
prepareGUI();
}
public static void main(String[] args) {
JTextAreaExample swingControlDemo = new JTextAreaExample();
swingControlDemo.showTextAreaDemo();
}
private void prepareGUI() {
mainFrame = new JFrame("JTextArea Example");
mainFrame.setSize(400, 400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent windowEvent) {
System.exit(0);
}
});
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("", JLabel.CENTER);
statusLabel.setSize(350, 100);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showTextAreaDemo() {
headerLabel.setText("JTextArea");
JLabel descriptionLabel = new JLabel("Description: ", JLabel.RIGHT);
final JTextArea descriptionTextArea = new JTextArea("Enter String ", 5, 20);
JScrollPane scrollPane = new JScrollPane(descriptionTextArea);
JButton showButton = new JButton("Show");
showButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String b = descriptionTextArea.getText().replace("#11#", "#yicHFRx1nc#")
.replace("#22#", "#icHFRx1nc#");
System.out.println("b=" + b);
statusLabel.setText(b);
}
});
controlPanel.add(descriptionLabel);
controlPanel.add(scrollPane);
controlPanel.add(showButton);
mainFrame.setVisible(true);
}
}
So I would consider myself to be a beginner programmer, but something as simple as getting a button to do something once clicked is fairly easy, right? I'll paste the code first then ask the question.
/*
* Created By Vili Milner
*/
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
public class MainView extends JFrame implements ActionListener {
private long cookieBalance = 0;
private String stringBalance = Long.toString(cookieBalance);
private JLabel balance = new JLabel(stringBalance);
public MainView(){
display();
}
public void display(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setTitle("Cookie Clicker");
setSize(300, 200);
GridLayout gridOneTwo = new GridLayout(1, 2);
GridLayout gridOneTen = new GridLayout(1, 10);
GridLayout gridOneThree = new GridLayout(1, 3);
Panel mainPanel = new Panel();
mainPanel.setLayout(gridOneTwo);
Panel upgradePanel = new Panel();
upgradePanel.setLayout(new BoxLayout(upgradePanel, BoxLayout.Y_AXIS));
JButton upgradeButtonOne = new JButton("UPGRADE 1");
JButton upgradeButtonTwo = new JButton("UPGRADE 2");
JButton upgradeButtonThree = new JButton("UPGRADE 3");
JButton upgradeButtonFour = new JButton("UPGRADE 4");
JButton upgradeButtonFive = new JButton("UPGRADE 5");
upgradePanel.add(upgradeButtonOne);
upgradePanel.add(upgradeButtonTwo);
upgradePanel.add(upgradeButtonThree);
upgradePanel.add(upgradeButtonFour);
upgradePanel.add(upgradeButtonFive);
mainPanel.add(upgradePanel);
Panel displayPanel = new Panel();
displayPanel.setLayout(new BoxLayout(displayPanel, BoxLayout.Y_AXIS));
displayPanel.add(balance);
mainPanel.add(displayPanel);
Panel cookiePanel = new Panel();
cookiePanel.setLayout(gridOneThree);
JButton cookieButton = new JButton("COOKIE");
cookieButton.setActionCommand("cookie");
cookieButton.addActionListener(this);
cookiePanel.add(cookieButton);
JLabel emptyLabelOne = new JLabel(" ");
JLabel emptyLabelTwo = new JLabel(" ");
displayPanel.add(cookiePanel);
displayPanel.add(emptyLabelOne);
displayPanel.add(emptyLabelTwo);
add(mainPanel);
}
#Override
public void actionPerformed(ActionEvent click) {
String action = click.getActionCommand();
if (action.equals("cookie")){
cookieBalance++;
}
}
}
Continuing, I can get the button to do anything except make the display label go up by 1. In other words, the button itself does work, but for some reason the label isn't changing. I believe this is a fairly simple mistake, I just can't seem to find it. So my question is: why is the label not changing once I increment the value?
Repeating what has been said in the comments, The JLabel balance is not being updated with the value, It simply reflects the value of what cookieBalance originally was.
Rather than simply incrementing the variable, you should call:
#Override
public void actionPerformed(ActionEvent click) {
String action = click.getActionCommand();
if (action.equals("cookie")){
balance.setText(String.valueOf(++cookieBalance));
}
}