Eclipse Java 8 Error: Label cannot be resolved - java

I am trying to program an 'Inch-to-Centimeter Calculator'. I've got a problem with the method umrechnen(). The label lblCenti cannot be resolved. My Code is equal to the Solutioncode. I am grateful for every answer or tip I get.
I don't know what I should add to my Description, but StackOverflow forces me to write more, so I'm writing this.
package gui;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.text.DecimalFormat;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class ZollZentimeter extends JFrame {
private JPanel contentPane;
private JTextField tfInch;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ZollZentimeter frame = new ZollZentimeter();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ZollZentimeter() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 359, 157);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnCalculate = new JButton("Umrechnen");
btnCalculate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
umrechnen();
}
});
btnCalculate.setBounds(12, 77, 116, 25);
contentPane.add(btnCalculate);
JButton btnEnde = new JButton("Ende");
btnEnde.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnEnde.setBounds(214, 77, 116, 25);
contentPane.add(btnEnde);
JLabel lblZoll = new JLabel("Zoll");
lblZoll.setBounds(12, 13, 56, 16);
contentPane.add(lblZoll);
tfInch = new JTextField();
tfInch.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_ENTER){
umrechnen();
}
}
});
JLabel lblCenti = new JLabel("");
lblCenti.setBounds(214, 42, 116, 22);
contentPane.add(lblCenti);
tfInch.setBounds(12, 42, 116, 22);
contentPane.add(tfInch);
tfInch.setColumns(10);
}
private void umrechnen(){
DecimalFormat f=new DecimalFormat("#0.00");
double z, cm;
z=Double.parseDouble(tfInch.getText());
cm=z*2.54;
lblCenti.setText(f.format(cm+" cm"));
tfInch.requestFocus();
tfInch.selectAll();
}
}

JLabel lblCenti = new JLabel("");
"lblCenti" is defined as a local variable so it can only be accessible in the method/constructor where you define it.
It you want to access the label in another method you need to define it as an instance variable, the same way you do with the "tfInch" variable.

Related

Invoke a serie of actions when Enter key is pressed

I have one Swing project and I have an action listener on JTextField for Tab key as follows.
There is a JOptionPane.showMessageDialog() inside the action listener. And when Tab is pressed option pane will show an Information message.
My problem is that, when I press Enter on OK button of Information Message dialog, a serie of action is invoked viz Tab action of JTextField and Enter action of btnNewButton.
If I use mouse click on OK button of Error Message dialog, every thing is fine and no problem.
Can I solve this using key bindings instead of key listener?
Please suggest a solution
import java.awt.EventQueue;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Collections;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class Test extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JButton btnNewButton;
private JDialog dialog;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test frame = new Test();
frame.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
setLocationRelativeTo(null);
contentPane.setLayout(null);
textField = new JTextField();
textField.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
Collections.emptySet());
textField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_TAB) {
JOptionPane.showMessageDialog(dialog, " Please Press ENTER Key", "information",
JOptionPane.INFORMATION_MESSAGE);
btnNewButton.grabFocus();
}
}
});
textField.setBounds(73, 28, 178, 28);
contentPane.add(textField);
textField.setColumns(10);
btnNewButton = new JButton("New button");
btnNewButton.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
JOptionPane.showMessageDialog(dialog, " That Invoked New Button Also", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
});
btnNewButton.setBounds(223, 137, 117, 25);
contentPane.add(btnNewButton);
JLabel lblNewLabel = new JLabel("Please Press TAB Key");
lblNewLabel.setBounds(83, 55, 183, 15);
contentPane.add(lblNewLabel);
dialog = new JDialog();
dialog.setAlwaysOnTop(true);
}
}
The problem is that you are overriding method keyReleased(). The JOptionPane is closing before the keyReleased() method is called and since you make btnNewButton the focused component after the JOptionPane is closed, the keyReleased() method is invoked – which displays the other JOptionPane.
Simply rename the method to keyPressed().
Also, you don't need the dialog member. The first parameter to JOptionPane#showMessageDialog should be the JFrame.
Here is your code with my corrections.
import java.awt.EventQueue;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Collections;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class Test extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JButton btnNewButton;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test frame = new Test();
frame.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
setLocationRelativeTo(null);
contentPane.setLayout(null);
textField = new JTextField();
textField.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
Collections.emptySet());
textField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_TAB) {
JOptionPane.showMessageDialog(Test.this, " Please Press ENTER Key", "information",
JOptionPane.INFORMATION_MESSAGE);
btnNewButton.grabFocus();
}
}
});
textField.setBounds(73, 28, 178, 28);
contentPane.add(textField);
textField.setColumns(10);
btnNewButton = new JButton("New button");
btnNewButton.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
JOptionPane.showMessageDialog(Test.this, " That Invoked New Button Also", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
});
btnNewButton.setBounds(223, 137, 117, 25);
contentPane.add(btnNewButton);
JLabel lblNewLabel = new JLabel("Please Press TAB Key");
lblNewLabel.setBounds(83, 55, 183, 15);
contentPane.add(lblNewLabel);
}
}
Note that (at least in JDK 15) there is no need to explicitly set the default close operation for JFrame since the default is EXIT_ON_CLOSE

How do I periodically update a label in a java swing/jFrame window?

I am currently trying to write a simple program that will display musical notes at a given interval in BPM. I have most of the code written, but I can't figure out how to get the labels containing the note and sharp/flat to update every interval given. This is my code so far. The NoteGenerator object is of my own creation and is just used to generate a random note/sharp/flat and keep track of tempo. I have already tested the NoteGenerator class and it works exactly how I expect it to. Thanks in advance!
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JSpinner;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.SpinnerNumberModel;
import javax.swing.Timer;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class NotePractice extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
NotePractice frame = new NotePractice();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public NotePractice() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
NoteGenerator noteGen = new NoteGenerator();
JSpinner spinner = new JSpinner();
spinner.setModel(new SpinnerNumberModel(new Integer(100), new Integer(20), null, new Integer(5)));
spinner.setBounds(211, 196, 60, 20);
contentPane.add(spinner);
JLabel lblBpm = new JLabel("BPM");
lblBpm.setFont(new Font("Arial", Font.BOLD, 12));
lblBpm.setBounds(175, 198, 26, 14);
contentPane.add(lblBpm);
JLabel lblNote = new JLabel(noteGen.getNote());
lblNote.setFont(new Font("Arial", Font.BOLD, 99));
lblNote.setBounds(175, 60, 82, 104);
contentPane.add(lblNote);
JLabel lblStep = new JLabel(noteGen.getStep());
lblStep.setFont(new Font("Arial", Font.BOLD, 70));
lblStep.setBounds(258, 93, 60, 58);
contentPane.add(lblStep);
JButton btnUpdateTempo = new JButton("Update Tempo");
btnUpdateTempo.setFont(new Font("Arial", Font.PLAIN, 11));
btnUpdateTempo.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
noteGen.setBPM(spinner.getComponentCount());
Timer t = new Timer(noteGen.getBPM(), new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
lblNote.setText(noteGen.getNote());
lblStep.setText(noteGen.getStep());
contentPane.updateUI();
}
});
}
});
btnUpdateTempo.setBounds(168, 227, 103, 23);
contentPane.add(btnUpdateTempo);
}
}

Get centering to work from jmenuitem action listener

I'm having a problem with my About Frame class. I call it through an action listener in a JMenuItem. It comes up but it doesn't show it centered and the frame doesn't show the icon image as I request. I have the icon working in the mainframe so it's the image size isn't the problem. Does this have something to do with the private JPanel contentPane;?
Code in the JmenuItem:
aboutMItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
jAboutMN_actionPerformed(e);
About Frame code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.BoxLayout;
public class AboutFrame extends JFrame {
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AboutFrame frame = new AboutFrame();
frame.setIconImage(new ImageIcon("resources/Image.png").getImage());
frame.setVisible(true);
//frame.setLocationRelativeTo(null);
frame.setLocationRelativeTo(null);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public AboutFrame() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//AboutFrame.setLocationRelativeTo(null);
setTitle("About MyAPP");
setBounds(100, 100, 370, 250);
//contentPane.setLocationRelativeTo(null);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lbVerNum = new JLabel("MYAPP, Beta 1.2");
lbVerNum.setBounds(57, 11, 233, 19);
lbVerNum.setVerticalAlignment(SwingConstants.TOP);
lbVerNum.setFont(new Font("Tahoma", Font.BOLD, 15));
lbVerNum.setHorizontalAlignment(SwingConstants.CENTER);
contentPane.add(lbVerNum);
JLabel lbCopyright = new JLabel("Copyright 2015 ");
lbCopyright.setBounds(86, 41, 170, 16);
lbCopyright.setIcon(null);
lbCopyright.setFont(new Font("Tahoma", Font.PLAIN, 13));
lbCopyright.setVerticalAlignment(SwingConstants.TOP);
lbCopyright.setHorizontalAlignment(SwingConstants.CENTER);
contentPane.add(lbCopyright);
}
}

Focus on Keylistener

So what I've got is that I would love to try and make an little login applet. I'm using Java Windowsbuilder for it, to make it easyer for me. I hope the code isn't to messy, because I'm just a starter.
The problem I've got is that My JButton "login" only registers a keyevent when it's selected trought tab, or when you first click it. What I want is that I can use the button always just by pressing the "ENTER" key.
Hope you guys solve my problem :)
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import org.eclipse.wb.swing.FocusTraversalOnArray;
import java.awt.Component;
import java.awt.event.KeyAdapter;
public class nummer1 extends JFrame{
private JPanel contentPane;
public static nummer1 theFrame;
private JTextField textFieldUsername;
private JTextField textFieldPass;
private nummer1 me;
private JLabel lblCheck;
private String password = "test", username = "test";
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
nummer1 frame = new nummer1();
nummer1.theFrame = frame;
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void Check(){
String Pass = textFieldPass.getText();
String Username = textFieldUsername.getText();
System.out.println(Pass);
if (Pass.equals(password) && Username.equals(username)){
lblCheck.setText("Correct Login");
}else{
lblCheck.setText("Invalid username or password");
}
}
/**
* Create the frame.
*/
public nummer1() {
me = this;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 356, 129);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblUsername = new JLabel("Username:");
lblUsername.setBounds(10, 11, 61, 14);
contentPane.add(lblUsername);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setBounds(10, 36, 61, 14);
contentPane.add(lblPassword);
textFieldUsername = new JTextField();
textFieldUsername.setBounds(81, 8, 107, 20);
contentPane.add(textFieldUsername);
textFieldUsername.setColumns(10);
me.textFieldUsername = textFieldUsername;
textFieldPass = new JTextField();
textFieldPass.setBounds(81, 33, 107, 20);
contentPane.add(textFieldPass);
textFieldPass.setColumns(10);
me.textFieldPass = textFieldPass;
JButton btnLogin = new JButton("Login");
contentPane.requestFocusInWindow();
btnLogin.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER){
me.Check();
System.out.println("hi");
}
}
});
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
me.Check();
}
});
btnLogin.setBounds(198, 7, 89, 23);
contentPane.add(btnLogin);
JLabel lblCheck = new JLabel("");
lblCheck.setHorizontalAlignment(SwingConstants.TRAILING);
lblCheck.setBounds(10, 65, 264, 14);
contentPane.add(lblCheck);
me.lblCheck = lblCheck;
contentPane.setFocusTraversalPolicy(new FocusTraversalOnArray(new
Component[]{lblUsername, lblPassword, textFieldUsername, textFieldPass, btnLogin, lblCheck}));
}
}
Thanks Emil!
What I want is that I can use the button always just by pressing the "ENTER" key
Sounds like you want to make the "login" button the default button for the dialog.
See Enter Key and Button for the problem and solution.
When using panels KeyListeners won't work unless the panel is focusable. What you can do is make a KeyBinding to the ENTER key using the InputMap and ActionMap for your panel.
public class Sample extends JPanel{
//Code
Sample() {
//More code
this.getInputMap().put(KeyStroke.getKeyStroke((char)KeyEvent.VK_ENTER), "Enter" );
this.getActionMap().put("Enter", new EnterAction());
}
private class EnterAction extends AbstractAction(){
#Override
public void ActionPerformed(ActionEvent e){
//Acion
}
}
}

Using Radio Buttons to set labels in Java

So for class I'm suppose to make a Celsius to Fahrenheit converter GUI. With that said, it's a pretty simple and easy program to create. I want to do more with it though. What I want to do is have one window that changes depending on which radio button is selected in a buttongroup. I want the selected radiobutton for "To Fahrenheit" or "To Celsius" to update the labels for the input and output. I have tried using an actionlistener for when one is selected, but it doesn't change the labels. Am I using the wrong listener? What's the correct way to do this?
Here's my code:
import java.awt.EventQueue;
import java.awt.Font;
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.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
public class Converter extends JFrame {
private JPanel contentPane;
private JTextField tfNumber;
private JLabel lblCelsius;
private JLabel lblFahrenheit;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Converter frame = new Converter();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Converter() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
setTitle("Celsius Converter");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 308, 145);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
tfNumber = new JTextField();
tfNumber.setText("0");
tfNumber.setBounds(10, 11, 123, 20);
contentPane.add(tfNumber);
tfNumber.setColumns(10);
lblCelsius = new JLabel("Celsius");
lblCelsius.setFont(new Font("Tahoma", Font.BOLD, 15));
lblCelsius.setBounds(143, 12, 127, 14);
contentPane.add(lblCelsius);
lblFahrenheit = new JLabel("Fahrenheit");
lblFahrenheit.setBounds(187, 46, 95, 14);
contentPane.add(lblFahrenheit);
final JLabel lblNum = new JLabel("32.0");
lblNum.setBounds(143, 46, 43, 14);
contentPane.add(lblNum);
final JRadioButton rdbtnF = new JRadioButton("to Fahrenheit");
rdbtnF.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(rdbtnF.isSelected()) {
lblCelsius.setText("Celsius");
lblFahrenheit.setText("Fahrenheit");
}
}
});
rdbtnF.setSelected(true);
rdbtnF.setBounds(10, 72, 109, 23);
contentPane.add(rdbtnF);
final JRadioButton rdbtnC = new JRadioButton("to Celsius");
rdbtnC.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(rdbtnF.isSelected()) {
lblCelsius.setText("Fahrenheit");
lblFahrenheit.setText("Celsius");
}
}
});
rdbtnC.setBounds(121, 72, 109, 23);
contentPane.add(rdbtnC);
ButtonGroup bg = new ButtonGroup();
bg.add(rdbtnF);
bg.add(rdbtnC);
JButton btnConvert = new JButton("Convert");
btnConvert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(rdbtnF.isSelected()) {
String num = String.valueOf(convertToF(tfNumber.getText()));
lblNum.setText(num);
}
if(rdbtnC.isSelected()) {
String num = String.valueOf(convertToC(tfNumber.getText()));
lblNum.setText(num);
}
}
});
btnConvert.setBounds(10, 42, 123, 23);
contentPane.add(btnConvert);
}
private double convertToF(String celsius) {
double c = Double.parseDouble(celsius);
double fahren = c * (9/5) + 32;
return fahren;
}
private double convertToC(String fahren) {
double f = Double.parseDouble(fahren);
double celsius = (f - 32) * 5 / 9;
return celsius;
}
}

Categories

Resources