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.
Related
I'm quite new to Java Programming and I found this code on the internet. It works fine there is no problem. I downloaded the png's of every fruit and I want to see them when I click on them instead of seeing their names. For example, if I click only apple, I want to see the png of apple. But if I use shift and multiple select grape and banana, I want to see their pngs at the right. (If it is possible of course)
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.HeadlessException;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class Ğ extends JFrame
{
//Sample 02: Create a Label
JLabel label = new JLabel();
public Ğ(String title) throws HeadlessException
{
super(title);
//Sample 01: Set Size and Position
setBounds(100, 100, 200, 200);
Container ControlHost = getContentPane();
ControlHost.setLayout(new GridLayout(1,1));
//Sample 03: Create List of Fruit Items
String[] Fruits = new String[10];
Fruits[0] = "Apple";
Fruits[1] = "Mango";
Fruits[2] = "Banana";
Fruits[3] = "Grapes";
Fruits[4] = "Cherry";
Fruits[5] = "Lemon";
Fruits[6] = "Orange";
Fruits[7] = "Strawberry";
Fruits[8] = "Watermelon";
Fruits[9] = "Ananas";
//Sample 04: Create JList to Show Fruit Name
JList ListFruits = new JList(Fruits);
ListFruits.setVisibleRowCount(10);
//Sample 05: Hand-Over the JList to ScrollPane & Display
JScrollPane jcp = new JScrollPane(ListFruits);
ControlHost.add(jcp);
ControlHost.add(label);
ListFruits.setSelectionMode(
ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
//Sample 06: Handle the JList Event
ListFruits.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
String strFruits = "";
List<String> SelectedFruits = ListFruits.getSelectedValuesList();
for(String Fruit: SelectedFruits)
strFruits = strFruits + Fruit + ",";
strFruits = strFruits.substring(0, strFruits.length()-1);
label.setText(strFruits);
}
});
}
}
And this is the main class of course
import javax.swing.JFrame;
public class Fruits {
public static void main(String[] args) {
// TODO Auto-generated method stub
Ğ frame = new Ğ ("Fruits");
frame.setVisible(true);
}
}
I need to make my rocket move accordingly to the correct asnwer, if he(she) get it right, it will move(from the planet (left) to the (right) planet, else, it will do nothing, i have a counter for the right question, but i don't know what to do next.
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
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 java.util.Enumeration;
import java.util.HashMap;
import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class Jogo0 extends JFrame implements ActionListener{
my variables
JPanel QUIZ;
JRadioButton opcao1;//choice1
JRadioButton opcao2;//choice2
JRadioButton opcao3;//choice3
ButtonGroup escolha;//buttongroup
JLabel questao; //question
JButton proximo; //next button
String [] [] alternativa; //alternatives
String [] [] correta; //correct answer
int acerto; //my counter
int posifogx = 0;
int posifogy = 300;
the images to the code, rocket, background, planets
ImageIcon imagfogut = new v ImageIcon(getClass().getResource("Foguetao2.gif"));
ImageIcon imagespac = new ImageIcon(getClass().getResource("Background.jpg"));
ImageIcon imageplantale = new ImageIcon(getClass().getResource("giphy.gif"));
ImageIcon imageterra = new ImageIcon(getClass().getResource("terra.gif"));
JLabel fog = new JLabel (imagfogut);
JLabel background = new JLabel (imagespac);
JLabel planetale = new JLabel (imageplantale);
JLabel terra = new JLabel (imageterra);
my method jogo, that will run the whole game
public Jogo0 (){
Janela(); //window
Imagens(); //img
QuizMetodo(); //my quizmethod
}
public void Imagens (){ //imgs
background.setBounds(0, 0, 1920, 1080);
fog.setBounds(posifogx, posifogy, 300, 200);
planetale.setBounds(-150, 300, 259, 259);
terra.setBounds(1000, 0, 379, 379);
}
public void Janela()//window {
setTitle("Game");
setLocation(0,0);
setVisible(true);
setSize(1920,1080);
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(fog);
add(planetale);
add(terra);
add(background);
}
public void foguetex(int moverfoguetex) { //position of the rocket
this.posifogx = moverfoguetex;
moverfoguetex = moverfoguetex + 100;
}
public void foguetey(int moverfoguetey) {
this.posifogy = moverfoguetey;
moverfoguetey = moverfoguetey + 100;
}
public synchronized void QuizMetodo(){
questoes();
Container cont=getContentPane();
cont.setLayout(null);
cont.setBackground(Color.GRAY);
escolha=new ButtonGroup();
opcao1=new JRadioButton("Opção1",true);
opcao2=new JRadioButton("Opção2",false);
opcao3=new JRadioButton("Opção3",false);
escolha.add(opcao1);
escolha.add(opcao2);
escolha.add(opcao3);
questao= new JLabel("Salve seu planeta!");
questao.setForeground(Color.WHITE);
questao.setFont(new Font("tahoma", Font.BOLD, 14));
proximo=new JButton("Proximo");
proximo.setForeground(Color.BLACK);
proximo.addActionListener(aa);
opcao1.addActionListener(aa);
opcao2.addActionListener(aa);
opcao3.addActionListener(aa);
QUIZ=new JPanel();
QUIZ.setBackground(Color.DARK_GRAY);
QUIZ.setLocation(250,530);
QUIZ.setSize(800,150);
QUIZ.setLayout(new GridLayout(6,2));
QUIZ.add(questao);
QUIZ.add(opcao1);
QUIZ.add(opcao2);
QUIZ.add(opcao3);
QUIZ.add(proximo);
cont.add(QUIZ);
setVisible(true);
acerto = 0;
i = acerto;
lerqr(acerto);
}
public String getSelection(){
String selectedChoice=null;
Enumeration<AbstractButton> buttons=escolha.getElements();
while(buttons.hasMoreElements())
{
JRadioButton temp=(JRadioButton)buttons.nextElement();
if(temp.isSelected())
{
selectedChoice=temp.getText();
}
}
return(selectedChoice);
}
ActionListener aa = new ActionListener(){ //**I DONT KNOW WHAT TO DO HERE**
public void actionPerformed(ActionEvent e) {
}
};
public void questoes() { //questions
alternativa = new String [10][4];
alternativa[0][0] ="Qual é o composição química da água?";
alternativa[0][1] = "(2) Hidrogênio e (1) Carbono";
alternativa[0][2] = "(1) Hidroênio e (2) Oxigênio";
alternativa[0][3] = "(2) Hidrogênio e (1) Oxigênio";
alternativa[1][0] = "Pra que serve o Protocolo de Kyoto?";
alternativa[1][1] = "Defesa dos animais";
alternativa[1][2] = "Proteção contra emissão de gases";
alternativa[1][3] = "Codigo da reciclagem";
correta = new String [10] [2];
correta[0][0] = "Qual é o composição química da água?";
correta[0][1] = "(2) Hidrogênio e (1) Oxigênio";
correta [1][0] = "Pra que serve o Protocolo de Kyoto?";
correta [1][1] = "Proteção contra emissão de gases";
}
public void lerqr(int id){
questao.setText(" "+alternativa[id][0]);
opcao1.setText(alternativa[id][1]);
opcao2.setText(alternativa[id][2]);
opcao3.setText(alternativa[id][3]);
opcao1.setSelected(true);
}
public static void main(String[] args) { //my main method
new Jogo0();
}
I don't exactly know if you need the methods foguetex(); and foguetey(); in the way you implemented them but the last line in both methods doesn't seem to affect the program in any way.
To make the rocket move and calculate the movement you could simply modify the foguetex(); method like this (or write a method with a different name if you also need foguetex(); for something else in the code):
public void foguetex(int moverfoguetex) { // position of the rocket
this.posifogx = moverfoguetex + 100;
}
This will cause the value posifogx to get updated to the new x-value where the rocket should be (you can also modify foguetey(); if needed). After doing this you want to update the position of your JLabel displaying the rocket.
Therefore you reassign the bounds of the JLabel in the ActionListener similar to this (you possibly want to adapt it to the ActionListener you wrote yourself):
proximo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
foguetex(posifogx); //calculating new x-position
fog.setBounds(posifogx, posifogy, 300, 200); //updating the label's position
}
});
Hope this helps you.
So I'm having trouble trying to change the background color of the keys pressed and I'm not entirely sure on how to go about it?
It works as a keyboard, the only issue I have is the method to change the background color when any key is typed
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.AbstractAction;
public abstract class OnScreenKeyboard extends JFrame implements KeyListener
{
String firstRow[] = {"~","1","2","3","4","5","6","7","8","9","0","-","+","Back\nSpace"};
String secondRow[] = {"Tab","Q","W","E","R","T","Y","U","I","O","P","[","]","|"};
String thirdRow[] = {"Caps\nLock","A","S","D","F","G","H","J","K","L",";","'","Enter"};
String fourthRow[] = {"Shift","Z","X","C","V","B","N","M",",",".","?","Space"};
JButton first[] = new JButton[14];
JButton second[] = new JButton[14];
JButton third[] = new JButton[13];
JButton fourth[] = new JButton[12];
Panel keys = new Panel();
Panel text = new Panel();
TextArea textArea = new TextArea();
String strText = "";
private JLabel label1;
private JLabel label2;
private JTextField textField;
public OnScreenKeyboard()
{
super("Typing Application");
label1 = new JLabel("Type some text using your keyboard. The keys you press will be "
+ "highlighed and the text will be displayed");
add(label1);
label2 = new JLabel("Note: clicking the buttons with your mouse will not perform any action");
add(label2);
textField = new JTextField(80);
textField.setEditable(true);
TextFieldHandler handler = new TextFieldHandler();
this.setLayout(new BorderLayout(1,1));
keys.setLayout(new GridLayout(4,14));
text.setLayout(new BorderLayout(1,1));
text.add(textArea);
for(int i=0; i<14; i++)
{
first[i] = new JButton(firstRow[i]);
first[i].setBackground(Color.white);
keys.add(first[i]);
first[i].addKeyListener(this);
}
for(int i=0; i<14; i++)
{
second[i] = new JButton(secondRow[i]);
second[i].setBackground(Color.white);
keys.add(second[i]);
second[i].addKeyListener(this);
}
for(int i=0; i<13; i++)
{
third[i] = new JButton(thirdRow[i]);
third[i].setBackground(Color.white);
keys.add(third[i]);
third[i].addKeyListener(this);
}
for(int i=0; i<12; i++)
{
fourth[i] = new JButton(fourthRow[i]);
fourth[i].setBackground(Color.white);
keys.add(fourth[i]);
fourth[i].addKeyListener(this);
}
add(text, BorderLayout.NORTH);
add(keys,BorderLayout.CENTER);
}
private class TextAreaHandler implements ActionListener
{
public void actionPerformed( ActionEvent event )
{
String string = ""; // declare string to display
if ( event.getSource() == textField )
string = String.format( "%s",
event.getActionCommand() );
}
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() instanceof JButton) {
System.out.println((((JButton) event.getSource()).getActionCommand()));
((JButton) event.getSource()).setBackground(Color.BLUE);
((JButton) event.getSource()).setContentAreaFilled(false);
((JButton) event.getSource()).setOpaque(true);
}
}
#Override
public void keyTyped( KeyEvent event )
{
int keyCode = event.getKeyCode();
strText = String.format( "%s", event.getKeyCode() );
}
private class TextFieldHandler implements ActionListener
{
public void actionPerformed( ActionEvent event )
{
String string = ""; // declare string to display
// user pressed Enter in JTextField textField1
if ( event.getSource() == textField )
string = String.format("%s", event.getActionCommand());
}
}
}
It takes no Java knowledge to know that you don't need 4x14 buttons, and lables and textfilelds to demonstrate a change of background color in one JButton.
Doesn't this MCVE demonstrate it ?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
public class OnScreenKeyboard extends JFrame{
public OnScreenKeyboard()
{
super();
JButton button = new JButton("T");
add(button,BorderLayout.CENTER);
pack();//"size to fit the preferred size and layouts of its subcomponents"
setVisible(true);//make Jframe show
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() instanceof JButton) {
System.out.println((((JButton) event.getSource()).getActionCommand()));
((JButton) event.getSource()).setBackground(Color.BLUE);
((JButton) event.getSource()).setContentAreaFilled(false);
((JButton) event.getSource()).setOpaque(true);
}
}
//a main is needed to make your code runnable (google MCVE)
public static void main(String[] args) {
new OnScreenKeyboard();
}
}
When it is short and concise, it also help you debug the problem.
Hint: You wrote an ActionListener but you never use it.
If you need more help don't hesitate to ask.
I have a class that reads a object file and imports it in an ArrayList. Then I made a Jlist to show some of the information of each objectfrom that ArrayList. So when they select an element of the Jlist, it will show the entire corresponding index object from the ArrayList. I want to add a "Delete" button to remove the selected Jlist element and the corresponding index object from the ArrayList. And then update the Jlist showing that element is deleted.
This is my class:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.ListModel;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.JScrollPane;
import javax.swing.JList;
import java.awt.TextArea;
import javax.swing.JTable;
import javax.swing.JTextPane;
import javax.swing.JTextArea;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class LogBook2 extends JFrame {
private static ArrayList<Log> logList = new ArrayList<Log>();
private static String logs;
private JPanel contentPane;
private JScrollPane scrollPane;
private JList list;
private JScrollPane scrollPane_1;
private String tpContent;
private int diveNumber;
private int diveDate;
private String diveMonth;
private int diveYear;
private String location;
private String diveSite;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
LogBook frame = new LogBook();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public LogBook2() {
//===============================================================================
//Importing form the Object file to ArrayList "logList"
File fileOfLogs=new File("logList.txt");
if(fileOfLogs.exists()){
try{
ObjectInputStream myStream = new ObjectInputStream(new FileInputStream("logList.txt"));
logList = (ArrayList<Log>) myStream.readObject();
myStream.close();
}
catch(Exception e){
setVisible(false);
JOptionPane.showMessageDialog(null, " 00000 There was a problem while reading dive records.\n "
+ "Please contact SEASFiRE Tech Team.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
else if(!fileOfLogs.exists()){
JOptionPane.showMessageDialog(null, " 11111 There was a problem while reading dive records.\n "
+ "Please contact SEASFiRE Tech Team.", "Error", JOptionPane.ERROR_MESSAGE);
}
//===============================================================================
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 888, 680);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JScrollPane scrollPane_2 = new JScrollPane();
scrollPane_2.setBounds(10, 88, 297, 542);
contentPane.add(scrollPane_2);
JList list_1 = new JList();
scrollPane_2.setViewportView(list_1);
list_1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//===============================================================================
//getting some information of each object and making a Jlist element with it.
DefaultListModel model=new DefaultListModel();
for( int i=0;i<logList.size();i++){
model.addElement(""+logList.get(i).getDiveNumber()+"__"+logList.get(i).getDiveDate()+"/"+logList.get(i).getDiveMonth()+"/"+logList.get(i).getDiveYear()
+"__"+logList.get(i).getLocation()+"_"+logList.get(i).getDiveSite());
}
list_1.setModel(model);
//===============================================================================
JLabel lblAddNewLog = new JLabel("Log Book");
lblAddNewLog.setHorizontalAlignment(SwingConstants.CENTER);
lblAddNewLog.setFont(new Font("Myanmar Text", Font.BOLD, 40));
lblAddNewLog.setBounds(0, 16, 862, 61);
contentPane.add(lblAddNewLog);
scrollPane = new JScrollPane();
scrollPane.setBounds(317, 88, 322, 542);
contentPane.add(scrollPane);
JTextArea textArea = new JTextArea();
textArea.setEditable(false);
scrollPane.setViewportView(textArea);
JButton btnDelete = new JButton("Delete");
//===============================================================================
//trying to make the "Delete" button. Not working...
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
model.remove(list_1.getSelectedIndex());
list_1.remove(list_1.getSelectedIndex());
textArea.setText("");
list_1.clearSelection();
}
});
btnDelete.setBounds(649, 561, 115, 29);
contentPane.add(btnDelete);
//========================================================================
//========================================================================
//the action for when an element is selected.
list_1.addListSelectionListener(
new ListSelectionListener(){
public void valueChanged(ListSelectionEvent event){
textArea.setText("");
textArea.append("Dive Number: "+logList.get(list_1.getSelectedIndex()).getDiveNumber()+"\t\tDive Date: "+
logList.get(list_1.getSelectedIndex()).getDiveDate()+"/"+logList.get(list_1.getSelectedIndex()).getDiveMonth()+
"/"+logList.get(list_1.getSelectedIndex()).getDiveYear()+"\n\nLocation: "+logList.get(list_1.getSelectedIndex()).getLocation()+
"\n\nDive Site: "+logList.get(list_1.getSelectedIndex()).getDiveSite()+"\n\nDive Type: "+logList.get(list_1.getSelectedIndex()).getDiveType()+
"\t\tCondition: "+logList.get(list_1.getSelectedIndex()).getCondition()+"\n\nVisibility: "+logList.get(list_1.getSelectedIndex()).getVisibility()+
"m\t\tSuit Type: "+logList.get(list_1.getSelectedIndex()).getSuitType()+"\n\nWeights: "+logList.get(list_1.getSelectedIndex()).getWeight()+
"m\t\tAltitude: "+logList.get(list_1.getSelectedIndex()).getAltitude()+"m\n\nTime In: "+logList.get(list_1.getSelectedIndex()).getHourIn()+
":"+logList.get(list_1.getSelectedIndex()).getMinIn()+"\t\tDuration: "+logList.get(list_1.getSelectedIndex()).getDuration()+
"min\n\nMax Depth: "+logList.get(list_1.getSelectedIndex()).getMaxDepth()+"m\t\tSafety Stop: "+logList.get(list_1.getSelectedIndex()).getSafetyStop()+
"\n\nAir in: "+logList.get(list_1.getSelectedIndex()).getAirIn()+"bar\t\tAir Out: "+logList.get(list_1.getSelectedIndex()).getAirOut()+
"bar\n\n02 Perc: "+logList.get(list_1.getSelectedIndex()).getOxgPerc()+"%\t\tDive Buddy: "+logList.get(list_1.getSelectedIndex()).getDiveBuddy()+
"\n\nNote: "+logList.get(list_1.getSelectedIndex()).getNote());
}
}
);
//========================================================================
}
}
Don't keep a separate ArrayList to hold the data.
Instead all the data should be stored in the ListModel
DefaultListModel<Log> model = new DefaultListModel<Log>();
model.addElement(...);
JList<Log> list = new JList<Log>( model );
Then you create a custom renderer for the JList to display whatever data from the Log class that you want:
list.setCellRenderer( new DefaultListCellRenderer()
{
public Component getListCellRendererComponent(
JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
{
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
Log log = (Log)value;
setText( log.get...() ):
return this;
}
});
Now you only have data in one place so when you want to delete a row you just delete the row from the DefaultListModel.
If you want to know how to delete an entry from the ListModel then take a look at the section from the Swing tutorial on How to Use Lists. The "Fire" button will delete the selected row. The tutorial will also explain more about using a custom renderer.
add a toString() method to your Log class.
public void toString(){
return "" + getDiveNumber()+"__"+getDiveDate()+"/"+getDiveMonth()+"/"+getDiveYear() +"__"+getLocation()+"_"+getDiveSite();
}
then add listmodel log instances
model.addElement(logList.get(i));
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);
}
}