Using Radio Buttons to set labels in Java - 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;
}
}

Related

How to link multiple frames in java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I created Login and Register frames separated which both connected to MySQL. If I just run the register frame, I can insert a new user to the database. However, If I run the login frame which includes the register frame inside and press register, the button that adds in the register frame does not work even the text fields are filled out.
//this is Login frame class
package YASAR;
import java.awt.BorderLayout;
import java.sql.*;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class GirisEkrani extends JFrame {
static JButton btnKullancEkle = new JButton("Kullan\u0131c\u0131 Ekle");
public static JPanel contentPane;
private static JTextField textField;
private static JComboBox comboBox = new JComboBox();
private static JButton btnBalan = new JButton("Ba\u011Flan");
private static JLabel lblParola = new JLabel("Parola :");
private static JLabel lblXaampeBalanlamad = new JLabel("Xaampe Ba\u011Flan\u0131lamad\u0131");
//private static KullaniciEkle ke=new KullaniciEkle();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
lblXaampeBalanlamad.setVisible(false);
try {
GirisEkrani frame = new GirisEkrani();
frame.setVisible(true);
try {
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/yasar","ozkan","******");
btnKullancEkle.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
KullaniciEkle ke=new KullaniciEkle();
ke.setVisible(true);
}
});
btnBalan.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
deneme abc=new deneme();
abc.setVisible(true);
}
});
con.close();
}
catch(SQLException e) {
textField.setEditable(false);
btnKullancEkle.setEnabled(false);
comboBox.setEnabled(false);
btnBalan.setEnabled(false);
lblParola.setVisible(false);
lblXaampeBalanlamad.setVisible(true);
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public GirisEkrani() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 286, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField = new JTextField();
textField.setBounds(74, 129, 124, 19);
contentPane.add(textField);
textField.setColumns(10);
comboBox.setBounds(74, 42, 124, 21);
contentPane.add(comboBox);
btnBalan.setBounds(74, 184, 124, 33);
contentPane.add(btnBalan);
btnKullancEkle.setBounds(74, 227, 124, 26);
contentPane.add(btnKullancEkle);
lblParola.setBounds(10, 132, 45, 13);
contentPane.add(lblParola);
lblXaampeBalanlamad.setBounds(74, 90, 162, 29);
contentPane.add(lblXaampeBalanlamad);
}
}
// And this is register frame class where I add user
package YASAR;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.sql.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;
public class KullaniciEkle extends JFrame {
public static JPanel contentPane;
public static JTextField textField;
public static JTextField textField_1;
public static JTextField textField_2;
public static JLabel lblIsim;
public static JLabel lblSoyisim;
public static JButton btnNewButton = new JButton("Ekle");
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
KullaniciEkle frame = new KullaniciEkle();
frame.setVisible(true);
try {
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/yasar","ozkan","******");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String input="INSERT INTO kullanicilar (TC,name,surname) VALUES(?,?,?)";
try {
PreparedStatement ps=con.prepareStatement(input);
ps.setInt(1, Integer.parseInt(textField.getText()));
ps.setString(2, textField_1.getText());
ps.setString(3, textField_2.getText());
//ps.execute();
if(ps.executeUpdate()>0) {
JOptionPane.showMessageDialog(null, "user added","user add",JOptionPane.OK_CANCEL_OPTION);
}
}catch(SQLException f) {
f.printStackTrace();
}
finally {System.out.println("pressed");}
frame.setVisible(false);
new GirisEkrani().setVisible(true);
}
});
}
catch(SQLException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public KullaniciEkle() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 285, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField = new JTextField();
textField.setBounds(87, 67, 96, 19);
contentPane.add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(87, 112, 96, 19);
contentPane.add(textField_1);
textField_1.setColumns(10);
textField_2 = new JTextField();
textField_2.setBounds(87, 160, 96, 19);
contentPane.add(textField_2);
textField_2.setColumns(10);
btnNewButton.setFont(new Font("Tahoma", Font.PLAIN, 10));
btnNewButton.setBounds(93, 232, 85, 21);
contentPane.add(btnNewButton);
JLabel lblTc = new JLabel("TC");
lblTc.setFont(new Font("Tahoma", Font.PLAIN, 10));
lblTc.setBounds(10, 70, 45, 13);
contentPane.add(lblTc);
lblIsim = new JLabel("\u0130sim");
lblIsim.setFont(new Font("Tahoma", Font.PLAIN, 10));
lblIsim.setBounds(10, 115, 45, 13);
contentPane.add(lblIsim);
lblSoyisim = new JLabel("Soyisim");
lblSoyisim.setFont(new Font("Tahoma", Font.PLAIN, 10));
lblSoyisim.setBounds(10, 163, 45, 13);
contentPane.add(lblSoyisim);
}
}
You need to put this code inside your Constructor.
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String input="INSERT INTO kullanicilar (TC,name,surname) VALUES(?,?,?)";
try {
PreparedStatement ps=con.prepareStatement(input);
ps.setInt(1, Integer.parseInt(textField.getText()));
ps.setString(2, textField_1.getText());
ps.setString(3, textField_2.getText());
//ps.execute();
if(ps.executeUpdate()>0) {
JOptionPane.showMessageDialog(null, "user added","user add",JOptionPane.OK_CANCEL_OPTION);
}
}catch(SQLException f) {
f.printStackTrace();
}
finally {System.out.println("pressed");}
frame.setVisible(false);
new GirisEkrani().setVisible(true);
}
});
Finally, it will look like this,
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.sql.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;
public class KullaniciEkle extends JFrame {
public static JPanel contentPane;
public static JTextField textField;
public static JTextField textField_1;
public static JTextField textField_2;
public static JLabel lblIsim;
public static JLabel lblSoyisim;
public static JButton btnNewButton = new JButton("Ekle");
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
KullaniciEkle frame = new KullaniciEkle();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public KullaniciEkle() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 285, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField = new JTextField();
textField.setBounds(87, 67, 96, 19);
contentPane.add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(87, 112, 96, 19);
contentPane.add(textField_1);
textField_1.setColumns(10);
textField_2 = new JTextField();
textField_2.setBounds(87, 160, 96, 19);
contentPane.add(textField_2);
textField_2.setColumns(10);
btnNewButton.setFont(new Font("Tahoma", Font.PLAIN, 10));
btnNewButton.setBounds(93, 232, 85, 21);
contentPane.add(btnNewButton);
JLabel lblTc = new JLabel("TC");
lblTc.setFont(new Font("Tahoma", Font.PLAIN, 10));
lblTc.setBounds(10, 70, 45, 13);
contentPane.add(lblTc);
lblIsim = new JLabel("\u0130sim");
lblIsim.setFont(new Font("Tahoma", Font.PLAIN, 10));
lblIsim.setBounds(10, 115, 45, 13);
contentPane.add(lblIsim);
lblSoyisim = new JLabel("Soyisim");
lblSoyisim.setFont(new Font("Tahoma", Font.PLAIN, 10));
lblSoyisim.setBounds(10, 163, 45, 13);
contentPane.add(lblSoyisim);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btnNewButtonActionPerformed(e);
}
});
}
private void btnNewButtonActionPerformed(ActionEvent evt) {
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/yasar", "ozkan", "******");
String input = "INSERT INTO kullanicilar (TC,name,surname) VALUES(?,?,?)";
try {
PreparedStatement ps = con.prepareStatement(input);
ps.setInt(1, Integer.parseInt(textField.getText()));
ps.setString(2, textField_1.getText());
ps.setString(3, textField_2.getText());
//ps.execute();
if (ps.executeUpdate() > 0) {
JOptionPane.showMessageDialog(null, "user added", "user add", JOptionPane.OK_CANCEL_OPTION);
}
} catch (SQLException f) {
f.printStackTrace();
} finally {
System.out.println("pressed");
}
//Instead of frame use this keyword
this.setVisible(false);
new GirisEkrani().setVisible(true);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
NOTE:- This is not the best practice to communicate with the database.

JAVA - can't get return from isSelected()

I have this part of code here, but whenever I launch the program I only get left brain. even though I check one or the other box.
chckbxMusic = new JCheckBox("Music");
chckbxMusic.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
chckbxMath.setSelected(false);
}
});
chckbxMusic.setBounds(46, 107, 85, 23);
Question_1.add(chckbxMusic);
chckbxMath = new JCheckBox("Math");
chckbxMath.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
chckbxMusic.setSelected(false);
}
});
chckbxMath.setBounds(243, 107, 128, 23);
Question_1.add(chckbxMath);
if(chckbxMusic.isSelected()) brain_right++;
else brain_left++;
Ok maybe the full code can help a bit more..
I rewrite it a little bit, but the result is always 0 for both variables??
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.CardLayout;
import javax.swing.JPanel;
import javax.swing.JCheckBox;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
public class PrgVeloce {
private JFrame frame;
private JPanel Question;
private JPanel Result;
public int brain_left;
public int brain_right;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PrgVeloce window = new PrgVeloce();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public PrgVeloce() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new CardLayout(0, 0));
Question = new JPanel();
frame.getContentPane().add(Question, "name_971195205673");
Question.setLayout(null);
final JCheckBox chckbxMath = new JCheckBox("Math");
chckbxMath.setBounds(39, 115, 128, 23);
Question.add(chckbxMath);
final JCheckBox chckbxMusic = new JCheckBox("Music");
chckbxMusic.setBounds(237, 115, 128, 23);
Question.add(chckbxMusic);
JButton btnNext = new JButton("Next");
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(chckbxMusic.isSelected())
{
brain_left = 10;
}
if(chckbxMath.isSelected())
{
brain_right = 10;
}
Question.setVisible(false);
Result.setVisible(true);
}
});
btnNext.setBounds(158, 210, 117, 29);
Question.add(btnNext);
Result = new JPanel();
frame.getContentPane().add(Result, "name_978670915264");
Result.setLayout(null);
JLabel lblEmisferoDx = new JLabel("Right brain:");
lblEmisferoDx.setBounds(90, 118, 110, 16);
Result.add(lblEmisferoDx);
JLabel lblNewLabel = new JLabel("Left Brain:");
lblNewLabel.setBounds(90, 157, 84, 16);
Result.add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel(brain_right + "%");
lblNewLabel_1.setBounds(218, 118, 61, 16);
Result.add(lblNewLabel_1);
JLabel lblNewLabel_2 = new JLabel(brain_left + "%");
lblNewLabel_2.setBounds(218, 157, 61, 16);
Result.add(lblNewLabel_2);
}
}

Cannot interact with jFrame, only plays error note

I been coding on a autoclicker, I just finished but I can't click anything, I can be in the window open but I can't click any button or slider etc.
I am using jnativehook as api for checking mouse press outside.
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import javax.swing.JSlider;
import javax.swing.JTextField;
import java.awt.AWTException;
import java.awt.Color;
public class AutoClicker extends JFrame implements Runnable {
public static AutoClicker get = new AutoClicker();
private static final long serialVersionUID = 1L;
private JPanel contentPane;
public static boolean enabled = false;
// private MouseHandler mouse;
private JTextField textField;
private JTextField textField_1;
public boolean activated;
public boolean skipNext;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AutoClicker frame = new AutoClicker();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public AutoClicker() {
setTitle("Swezeds AutoClicker");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 403, 253);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
JButton btnStart = new JButton("Start");
btnStart.setBounds(88, 36, 89, 23);
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
enabled = true;
}
});
contentPane.setLayout(null);
contentPane.add(btnStart);
JButton btnStop = new JButton("Stop");
btnStop.setBounds(187, 36, 89, 23);
btnStop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
enabled = false;
}
});
contentPane.add(btnStop);
JLabel lblSwezedsAutoclicker = new JLabel("Swezeds AutoClicker");
lblSwezedsAutoclicker.setBounds(102, 11, 167, 14);
lblSwezedsAutoclicker.setFont(new Font("Impact", Font.PLAIN, 20));
contentPane.add(lblSwezedsAutoclicker);
JCheckBox chckbxClickingSound = new JCheckBox("Clicking Sound");
chckbxClickingSound.setBounds(6, 184, 118, 23);
contentPane.add(chckbxClickingSound);
JSlider slider = new JSlider();
slider.setValue(5);
slider.setMaximum(20);
slider.setBounds(88, 70, 188, 14);
contentPane.add(slider);
JSlider slider_1 = new JSlider();
slider_1.setMaximum(20);
slider_1.setValue(12);
slider_1.setBounds(88, 112, 188, 14);
contentPane.add(slider_1);
JLabel lblNewLabel = new JLabel("Max CPS");
lblNewLabel.setBounds(32, 112, 76, 14);
contentPane.add(lblNewLabel);
JLabel lblMinCps = new JLabel("Min CPS");
lblMinCps.setBounds(32, 70, 76, 14);
contentPane.add(lblMinCps);
textField = new JTextField(slider.getValue() + "");
textField.setEditable(false);
textField.setBackground(Color.LIGHT_GRAY);
textField.setBounds(276, 64, 31, 20);
contentPane.add(textField);
textField.setColumns(10);
textField_1 = new JTextField(slider_1.getValue() + "");
textField_1.setEditable(false);
textField_1.setBackground(Color.LIGHT_GRAY);
textField_1.setColumns(10);
textField_1.setBounds(276, 109, 31, 20);
contentPane.add(textField_1);
}
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public boolean isSkipNext() {
return skipNext;
}
public void setSkipNext(boolean skipNext) {
this.skipNext = skipNext;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
AutoClicker.enabled = enabled;
}
public boolean isActivated() {
return activated;
}
public void setActivated(boolean activated) {
this.activated = activated;
}
#Override
public void run() {
try {
for (;;) {
Thread.sleep(1L);
if ((isActivated()) && (isEnabled())) {
try {
Thread.sleep(1L);
Robot robot = new Robot();
while (true) {
try {
setSkipNext(true);
Thread.sleep(AutoClicker.randInt(100, 150));
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
} catch (InterruptedException ecksdee) {
}
}
} catch (AWTException ecksdee) {
}
}
}
} catch (Exception localException) {
}
try {
GlobalScreen.registerNativeHook();
this.mouse = new MouseHandler();
GlobalScreen.addNativeMouseListener(this.mouse);
} catch (NativeHookException exception) {
exception.printStackTrace();
}
}
}
You've overridden essentially functionality of the JFrame
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
AutoClicker.enabled = enabled;
}
This is changing the user interaction state, basically disabling the frame.
Suggestion, use a model to manage the state, separate the logic from the user interface and share the model between them.
I recommend against using JFrame as your primary component, you're not adding any new functionality to the class and it ties you into a single use case. Better to start with a JPanel, then you can add it to whatever container you like.
This:
public static AutoClicker get = new AutoClicker();
is not how a singleton should be done, besides, you create a whole other instance in the main method anyway, so now you run the risk of contaminating the state. Separating the model/view/controller will help solve part of the problem at least

Way to save jList data into a txt file?

I am looking for a way to save the users input from a jlist into a txt file. It's for a homework project. I have the program set up to take user input from a textfield, then it goes into the jlist once they hit the add button. The jlist has a defaultlistmodel on it, and I'm wondering if there is a way to create a save button and allow it to save the complete jlist into a .txt file.
Also, here is my code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.border.LineBorder;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JComboBox;
import javax.swing.JProgressBar;
import javax.swing.JLabel;
public class i extends JFrame {
private JPanel contentPane;
private JTextField jTextField;
DefaultListModel ListModel = new DefaultListModel();
ArrayList<String> arr = new ArrayList <String>();
String str;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
i frame = new i();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public i() {
super("List");
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);
jTextField = new JTextField();
jTextField.setBounds(15, 80, 168, 20);
contentPane.add(jTextField);
jTextField.setColumns(10);
final JList jList = new JList(ListModel);
jList.setBorder(new LineBorder(new Color(0, 0, 0)));
jList.setBounds(289, 54, 135, 197);
contentPane.add(jList);
JButton jButton = new JButton("Add");
jButton.setBounds(190, 79, 89, 23);
contentPane.add(jButton);
jButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String str=jTextField.getText();
ListModel.addElement(str);
jTextField.setText("");
arr.add(str);
System.out.println(arr);
}
});
JButton delete = new JButton("DELETE");
delete.setBounds(190, 162, 89, 23);
contentPane.add(delete);
delete.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent k){
ListModel.removeElement(jList.getSelectedValue());
}
});
JButton btnUp = new JButton("UP");
btnUp.setBounds(190, 125, 89, 23);
contentPane.add(btnUp);
btnUp.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int index = jList.getSelectedIndex();
if(index == -1){
JOptionPane.showMessageDialog(null, "Select something to move.");
} else if(index > 0) {
String temp = (String)ListModel.remove(index);
ListModel.add(index - 1, temp);
jList.setSelectedIndex(index -1);
}
}
});
JButton btnDown = new JButton("DOWN");
btnDown.setBounds(190, 196, 89, 23);
contentPane.add(btnDown);
btnDown.addActionListener( new ActionListener(){
public void actionPerformed( ActionEvent e ){
int index = jList.getSelectedIndex();
if( index == -1 )
JOptionPane.showMessageDialog(null, "Select something to move.");
else if( index < ListModel.size() - 1 ){
String temp = (String)ListModel.remove( index );
ListModel.add( index + 1, temp );
jList.setSelectedIndex( index + 1 );
}
}
});
JLabel lblItems = new JLabel("Items:");
lblItems.setBounds(290, 37, 46, 14);
contentPane.add(lblItems);
JButton btnPrint = new JButton("PRINT");
btnPrint.setBounds(190, 228, 89, 23);
contentPane.add(btnPrint);
btnPrint.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});
}
}
you need use File class to save your list in that
File file = new File("c:/test/myfile.txt");
now file's created and opened!
and for write some output to file
use Formatter Class:
public class CreateFile
{
private Formatter x;
void openFile()
{
try
{
x = new Formatter("c:/myfile.txt");
System.out.println("you created a file");
}
catch(Exception e)
{
System.err.println("error in opening file");
}
}
void addFile()
{
x.format("%s %s %s\n","20","Start","Today");
}
void closeFile()
{
x.close();
}
}
as you see,addFile method accept 3 String passed to write in the file
i passed "20" , "Start" , "Today"
you can use more/less than %s , and pass user input or a list in String to write in the file.
good luck

Eclipse Java 8 Error: Label cannot be resolved

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.

Categories

Resources