Need help resetting JComboBox - java

So I am trying to make a Fahrenheit to Celsius (or vice versa) conversion program. So it sort of works but I have a drop down menu which I take the value from to check which conversion equation I need. My program isn't quiet finished I only have one equation but It doesn't go back to normal once I've pressed convert. Does anyone know how I can refresh so it goes back to the first option?
package tools;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
public class TempConvert extends JFrame {
private JTextField Value;
private JComboBox Options;
private JLabel FVal;
private JButton Convert;
private static String[] OptionsList = {"","Celsius", "Farinheit"};
String TempVal;
int GetVal;
double C2F;
float F2C;
int GetUnit;
public TempConvert(){
super("Tempurature Converter");
setLayout(new FlowLayout());
FVal = new JLabel();
Convert = new JButton();
Options = new JComboBox(OptionsList);
Value = new JTextField("Insert Temperature here:");
Value.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e) {
TempVal = Value.getText();
GetVal = Integer.parseInt(TempVal);
}
}
);
Options.addItemListener(
new ItemListener(){
public void itemStateChanged(ItemEvent event){
if (event.getStateChange()==ItemEvent.SELECTED)
System.out.print(Options.getSelectedIndex());
GetUnit = Options.getSelectedIndex();
}
}
);
Convert.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e) {
if (GetUnit==1){
double Calc= (GetVal * 1.8);
C2F = (Calc+32);
System.out.println(C2F);
FVal.setText(C2F + " Fahrenheit");
Convert.revalidate();
Convert.repaint();
}
}
}
);
add(Options);
add(Value);
add (Convert);
add(FVal);
}
}

Related

Varaible in If statement in ActionListener

I'm making an app, with multiple classes, and in one class i have some code to assign a random number from 1 - 6 to a variable. In another class i have a JLabel showing this variable. And in another class i have a JButton, with a ActionListener, within this is an IF Statement, with the variable with the random number in.
The variable is in Class1.
package Dice;
public class DiceRoll {
public int DICEONE;
public int DICETWO;
private int max = 6;
private int min = 1;
public void DiceRollMethod() {
DICEONE = (int) (Math.floor(Math.random() * (max - min + 1)) + min);
DICETWO = (int) (Math.floor(Math.random() * (max - min + 1)) + min);
System.out.println(DICEONE);
System.out.println(DICETWO);
}
}
The variable is 'DICEONE'
The JLabel is in Class2 (which rolls the dice).
package Dice;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class DiceButton extends JPanel{
private static final long serialVersionUID = 1L;
DiceRoll roll = new DiceRoll();
JButton btnRoll;
public JLabel DB1, DB2;
public DiceButton() {
DB1 = new JLabel("Dice 1: " + roll.DICEONE);
DB2 = new JLabel("Dice 2: " + roll.DICETWO);
DB1.setVisible(true);
DB2.setVisible(true);
btnRoll = new JButton("Roll Dice");
btnRoll.setVisible(true);
btnRoll.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
roll.DiceRollMethod();
DB1.setText("Dice 1: " + roll.DICEONE);
DB2.setText("Dice 2: " + roll.DICETWO);
}
});
add(DB1);
add(DB2);
add(btnRoll);
}
}
When the button is clicked, the random number is assigned to the variable and then displayed.
Finally the variable is used in the ActionListener in Class3 (this is the bit i have a problem with).
package Tiles;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.Border;
import Dice.DiceButton;
import Dice.DiceRoll;
public class SpaceOne extends JPanel{
private static final long serialVersionUID = 1L;
DiceRoll roll = new DiceRoll();
DiceButton dButton = new DiceButton();
JButton btn1;
JLabel lbl1;
Font lblFont = new Font("Helvetica", Font.BOLD, 90);
Border lblBorder = BorderFactory.createLineBorder(Color.BLACK, 3);
public SpaceOne() {
setSize(50,100);
setLayout(new GridLayout(1,2));
lbl1 = new JLabel("1");
lbl1.setVisible(true);
lbl1.setFont(lblFont);
lbl1.setBorder(lblBorder);
lbl1.setLocation(1, 1);
btn1 = new JButton("1");
btn1.setVisible(true);
btn1.setLocation(1, 2);
btn1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(roll.DICEONE == 1) {
lbl1.setText(".");
System.out.println("DICEONE");
}else if(roll.DICETWO == 1) {
lbl1.setText(".");
System.out.println("DICETWO");
}
}
});
add(btn1);
add(lbl1);
}
}
The idea is that when the button is clicked, it will check if the variable is equal to a number, and if it is, to change the JLabel text.
But when I click the button nothing changes. The button to roll the dice works fine.

Swing worker freezes the application

Below is a small program that utilises the Newton-Raphson method for finding out a square root to a high degree of accuracy.
Everything seems to work as expected except for the SwingWorker. When this is run the application freezes up and can't be used until the SwingWorker completes its task. However, I thought the purpose of a SwingWorker was to avoid this.
Can someone help me rectify the problem?
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.concurrent.ExecutionException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.text.DefaultCaret;
import net.miginfocom.swing.MigLayout;
#SuppressWarnings("serial")
public class SquareRoot extends JFrame {
private BigDecimal SQRT_DIG = new BigDecimal(150);
private SquareRoot() {
super("Square Rooter");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createLayout(this);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private void createLayout(JFrame addTo) {
JPanel rootPanel = new JPanel(new MigLayout("wrap", "grow", ""));
JLabel acc = new JLabel("Accuracy: " + SQRT_DIG);
JSlider accSlide = new JSlider(1, 1000000, 150);
JLabel numRoot = new JLabel("Number to Square Root");
JTextField num = new JTextField();
JButton root = new JButton("Root");
JLabel ansRoot = new JLabel("Answer");
JTextArea ans = new JTextArea();
JScrollPane ansHolder = new JScrollPane(ans);
accSlide.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent arg0) {
SQRT_DIG = new BigDecimal(accSlide.getValue());
acc.setText("Accuracy: " + SQRT_DIG);
}
});
rootPanel.add(acc);
rootPanel.add(accSlide, "grow");
root.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
ans.setText("Please Wait");
new SwingWorker<BigDecimal, Object>() {
#Override
protected BigDecimal doInBackground() throws Exception {
return bigSqrt(new BigDecimal(num.getText()));
}
#Override
protected void done() {
try {
ans.setText(get().toPlainString());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}.run();
}
});
rootPanel.add(numRoot);
rootPanel.add(num, "grow");
rootPanel.add(root, "right");
ans.setEditable(false);
((DefaultCaret) ans.getCaret()).setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
ansHolder.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
rootPanel.add(ansRoot);
rootPanel.add(ansHolder, "grow");
addTo.add(rootPanel);
}
private BigDecimal sqrtNewtonRaphson(BigDecimal c, BigDecimal xn, BigDecimal precision) {
BigDecimal fx = xn.pow(2).add(c.negate());
BigDecimal fpx = xn.multiply(new BigDecimal(2));
BigDecimal xn1 = fx.divide(fpx,2*SQRT_DIG.intValue(),RoundingMode.HALF_DOWN);
xn1 = xn.add(xn1.negate());
BigDecimal currentSquare = xn1.pow(2);
BigDecimal currentPrecision = currentSquare.subtract(c);
currentPrecision = currentPrecision.abs();
if (currentPrecision.compareTo(precision) <= -1)
return xn1;
return sqrtNewtonRaphson(c, xn1, precision);
}
private BigDecimal bigSqrt(BigDecimal c) {
return sqrtNewtonRaphson(c, new BigDecimal(1), new BigDecimal(1).divide(new BigDecimal(10).pow(SQRT_DIG.intValue())));
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new SquareRoot());
}
}
I believe your issue is due to you using the run() method to executer the SpringWorker. Using execute() instead will ensure the spring worker will be run in a worker thread.

Creating a java swing album

I'd like to create a Java Swing Photo Album but I can't manage to find the right way to do it. I think it should be to create two ArrayList, one to stock the photo objects and another one to stock the buttons.
After that I should find a way to assign each images to the buttons and add them into the panel.
My question is : Do you think it is the right way to do it and if so, could you give me a hint? (For the last class at the bottom)
Here's my code at the moment :
Main :
import javax.swing.JFrame;
public class Main extends JFrame {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new AlbumFrame();
}
});
}
}
AlbumFrame :
import java.awt.BorderLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class AlbumFrame extends JFrame {
private JPanel MenuPanel;
private JPanel PhotoPanel;
public AlbumFrame(){
super("JPhone");
setLayout(new BorderLayout());
PhotoPanel = new PhotoPanel();
add(PhotoPanel,BorderLayout.CENTER);
MenuPanel = new MenuPanel();
add(MenuPanel,BorderLayout.SOUTH);
setSize(480,800);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
}
MenuPanel
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.filechooser.FileNameExtensionFilter;
public class MenuPanel extends JPanel implements ActionListener{
private static final long serialVersionUID = 1L;
private JButton backButton;
private JButton homeButton;
private JButton turnButton;
private JButton addButton;
final private JFileChooser fc;
public MenuPanel(){
fc = new JFileChooser();
backButton = new JButton(new ImageIcon(getClass().getResource("/Images/back.png")));
homeButton = new JButton(new ImageIcon(getClass().getResource("/Images/home.png")));
turnButton = new JButton(new ImageIcon(getClass().getResource("/Images/turn.png")));
addButton = new JButton(new ImageIcon(getClass().getResource("/Images/add.png")));
backButton.setPreferredSize(new Dimension(55,55));
homeButton.setPreferredSize(new Dimension(55,55));
turnButton.setPreferredSize(new Dimension(55,55));
addButton.setPreferredSize(new Dimension(55,55));
backButton.addActionListener(this);
homeButton.addActionListener(this);
turnButton.addActionListener(this);
addButton.addActionListener(this);
setLayout(new FlowLayout(FlowLayout.CENTER));
add(backButton);
add(homeButton);
add(turnButton);
add(addButton);
}
public void actionPerformed(ActionEvent e) {
JButton clicked = (JButton)e.getSource();
//Test for the moment
if(clicked == backButton){
System.out.println("back");
}else if(clicked == homeButton){
System.out.println("home");
}else if(clicked == turnButton){
System.out.println("turn");
}else if(clicked == addButton){
int returnVal = fc.showOpenDialog(MenuPanel.this);
if(returnVal == JFileChooser.APPROVE_OPTION){
File file = fc.getSelectedFile();
}
}
}
}
PhotoPanel
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.JPanel;
public class PhotoPanel extends JPanel implements ActionListener {
ArrayList<Photo> Album = new ArrayList<Photo>();
ArrayList<JButton> Buttons = new ArrayList<JButton>();
public PhotoPanel(){
setLayout(new FlowLayout(FlowLayout.CENTER));
}
public void actionPerformed(ActionEvent e) {
}
}
I would use separate class like PhotoCard to avoid lists:
class PhotoCard {
public PhotoCard(Photo photo) {
add(photo);
// also add buttons, listeners, etc.
}
}
that holds necessary data and initializes listeners.
And then class can be added to to your PhotoPanel:
PhotoPanel.add(new PhotoCard(...));

'Highgui cannot be resolved', JavaCV, Eclipse

I'm trying to set up face detection with JavaCV. I've got working code with cvLoadImage but when I try to load an image via Highgui.imread there's an error: 'Highgui cannot be resolved' and 'Highgui' has red wavy underlining. For some reason Eclipse cannot deal properly with imported com.googlecode.javacv.cpp.opencv_highgui or ...?
Problem here:
CvMat myImg = Highgui.imread(myFileName);
Full code:
import java.awt.EventQueue;
import java.awt.Insets;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import com.googlecode.javacv.cpp.opencv_core.CvMemStorage;
import com.googlecode.javacv.cpp.opencv_core.CvRect;
import com.googlecode.javacv.cpp.opencv_core.CvScalar;
import com.googlecode.javacv.cpp.opencv_core.CvSeq;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
import com.googlecode.javacv.cpp.opencv_objdetect.CvHaarClassifierCascade;
import static com.googlecode.javacv.cpp.opencv_core.*;
import static com.googlecode.javacv.cpp.opencv_highgui.*;
import static com.googlecode.javacv.cpp.opencv_objdetect.*;
import java.awt.Button;
import java.io.File;
import javax.swing.SwingConstants;
import javax.swing.JLabel;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import com.googlecode.javacv.cpp.opencv_core.CvMat;
import com.googlecode.javacv.cpp.opencv_highgui;
//import opencv_highgui;
public class Form1 {
static private final String newline = "\n";
JButton openButton, saveButton;
JTextArea log;
JFileChooser fc;
String myFileName = "";
//Load haar classifier XML file
public static final String XML_FILE =
"resources/!--master--haarcascade_frontalface_alt_tree.xml";
private JFrame frame;
//Detect for face using classifier XML file
public static void detect(IplImage src){
//Define classifier
CvHaarClassifierCascade cascade = new CvHaarClassifierCascade(cvLoad(XML_FILE));
CvMemStorage storage = CvMemStorage.create();
//Detect objects
CvSeq sign = cvHaarDetectObjects(
src,
cascade,
storage,
1.1,
3,
0);
cvClearMemStorage(storage);
int total_Faces = sign.total();
//Draw rectangles around detected objects
for(int i = 0; i < total_Faces; i++){
CvRect r = new CvRect(cvGetSeqElem(sign, i));
cvRectangle (
src,
cvPoint(r.x(), r.y()),
cvPoint(r.width() + r.x(), r.height() + r.y()),
CvScalar.RED,
2,
CV_AA,
0);
}
//Display result
cvShowImage("Result", src);
cvWaitKey(0);
}
/**
* Create the application.
*/
public Form1() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
JLabel Label1 = new JLabel(" ");
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 301, 222);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btnDetect = new JButton("Detect");
btnDetect.setVerticalAlignment(SwingConstants.TOP);
btnDetect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//IplImage img = cvLoadImage("resources/lena.jpg");
IplImage img = cvLoadImage(myFileName);
CvMat myImg = Highgui.imread(myFileName);
detect(img);
}
});
frame.getContentPane().add(btnDetect, BorderLayout.SOUTH);
Label1.setHorizontalAlignment(SwingConstants.CENTER);
frame.getContentPane().add(Label1, BorderLayout.CENTER);
JButton btnNewButton = new JButton("Open");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JFileChooser fileopen = new JFileChooser();
int ret = fileopen.showDialog(null, "Открыть файл");
if (ret == JFileChooser.APPROVE_OPTION) {
File file = fileopen.getSelectedFile();
myFileName = file.getAbsolutePath();
Label1.setText(myFileName);
}
}
});
frame.getContentPane().add(btnNewButton, BorderLayout.NORTH);
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Form1 window = new Form1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
//Load image
//IplImage img = cvLoadImage("resources/lena.jpg");
//detect(img);
}
}
External JARs: http://pasteboard.co/jwqNHC9.png
Full project in ZIP
I've also followed all steps from here: http://opencvlover.blogspot.in/2012/04/javacv-setup-with-eclipse-on-windows-7.html
Any help will be appreciated.
Mat m = Highgui.imread(myFileName); is from the builtin opencv java wrappers , not from javacv ( which is a independant, 3rd party wrapper ).
unfortunately, both concurrent apis are pretty incompatible, as javacv is wrapping the outdated c-api, and the opencv ones are wrapping the more modern c++ api.

Update DefaultListModel with JList, using extends on subclass

trying to solve a problem and i cant get why it wont work. I'm sorry if I confuse you with my norwegian comments and variables.
First, here is my form.java file.
import java.awt.FlowLayout;
import java.awt.List;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
public class Form implements ActionListener {
String[] ansatt_type = {"Sjef","Mellomleder","Assistent"};
String totlønn;
// KOMPONENTER FOR GUI START
JList ansatte;
DefaultListModel model;
JLabel label1 = new JLabel ();
JComboBox ansatt_id = new JComboBox (ansatt_type);
JButton add_me = new JButton ();
JLabel lønn = new JLabel ();
// KOMPONENTER FOR GUI SLUTT
public Form () {
// LAGER RAMME START
JFrame ramme = new JFrame ();
ramme.setBounds(0,0,275,400);
ramme.setTitle("Ansatt kontroll");
ramme.setLayout(new FlowLayout ());
ramme.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// LEGGER TIL TEXT LABEL1
label1.setText("Liste over ansatte: ");
ramme.add(label1);
// LEGGER TIL DEFAULTLISTMODEL
model = new DefaultListModel();
ansatte = new JList(model);
ansatte.setBounds(0, 0, 200, 200);
model.addElement("KU");
ramme.add(ansatte);
// LEGGER TIL DROPDWON LIST;
ramme.add(ansatt_id);
// LEGGER TIL ANSATT KNAPP
add_me.setText("Legg til ny ansatt");
ramme.add(add_me);
add_me.addActionListener(this);
// LEGGER TIL SAMLEDE LØNNSKOSTNADER
totlønn = "Totale lønnskostnader er : eksempeltall";
lønn.setText(totlønn);
ramme.add(lønn);
ramme.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(null, "Du har valgt:
"+ansatt_id.getSelectedItem()+"!" +
" Du blir nå videreført og kan legge til en ny ansatt");
if(ansatt_id.getSelectedItem() == "Sjef"){
System.out.println("Valgt Sjef");
Sjef sj = new Sjef ();
model.addElement(sj);
}
if(ansatt_id.getSelectedItem() == "Mellomleder"){
System.out.println("Valgt Mellomleder");
}
if(ansatt_id.getSelectedItem() == "Assistent"){
System.out.println("Valgt Assistent");
}
}
}
I also have a class file called Ansatt.java who several class fiels extends from. I'l show you one.
First my Ansatt.java file ;
import javax.swing.JOptionPane;
public class Ansatt extends Form {
public String Navn;
public int Lønn;
public String Type;
public Ansatt () {
Navn = JOptionPane.showInputDialog(null, "Skriv inn navn på ny ansatt: ");
System.out.println("Ansatt lag til i liste");
}
public String toString(){
return Navn + " " + Type;
}
}
And the extended class Sjef.java
public class Sjef extends Ansatt {
public Sjef () {
super();
this.Lønn = 40000;
this.Type = "Sjef";
}
}
Everything works, except the ModelList wont update, I have a working example, who is almost identical but it just doesent work in this one!
Your problem is the String comparison in your ActionListener:
ansatt_id.getSelectedItem() == "Sjef"
will most likely not return true. You should use
"Sjef".equals( ansatt_id.getSelectedItem() )
Same for the other comparisons.

Categories

Resources