I have a Swing Form (Java). In this form I have field, for example Name1. I initialize it so:
private JTextField Name1;
In this code i'm adding JTextField Name1 into my Form:
tabbedPane.addTab("T6", null, panel, "T6");
panel.setLayout(null);
Name1.setBounds(73, 11, 674, 20);
panel.add(Name1);
Additionaly I have Button1 on my form. The event in this button is changing the value of Name1. Its work normaly.
Moreover I have a Button 2 that hiding the Tab with Name1:
tabbedPane.remove(1);
tabbedPane.repaint();
tabbedPane.revalidate();
frame.repaint();
frame.revalidate();
(And, of course, I turn on my tabpane again after this)
After all that, by the pressing the Button 4 I want to change the vlue of Name1 to some text.
But it doesn't work!!!!!! SetTex doesnt work. The field is empty.
So, if I change the Name1 declaration from
private JTextField Name1;
to
static JTextField Name1;
Yes, it works. BUT! Then I can't change the value of Name1 by using
Name1.Settext("Example");
What i have to do to make Name1 available after Button 4 pressed and changable ????
The all code is:
public class GUI {
public JTextField Name_textField;
public static void main(String[] args) {
DB_Initialize();
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI window = new GUI();
window.frame.setVisible(true);
window.frame.setResizable(false);
FirstConnect FC = window.new FirstConnect();
ConnectStatus = true;
FC.FirstEntry();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public GUI() {
CurrentEnty_textField = new JTextField();
Name_textField = new JTextField();
EntriesCountlbl = new JLabel("New label");
initialize();
EntriesCountlbl.setText(Integer.toString(EC1));
if (LoginStatus == true) {
System.out.println("LoginStatus == true");
AdminPartOn();
btnNewButton.setEnabled(false);
} else {
btnNewButton_3.setEnabled(false);
tabbedPane.setEnabledAt(1, false);
// UnableForm();
AdminPartOff();
}
}
public static void DB_Initialize() {
conn3 = con3.DoConnect();
int ID;
ArrayList<String> list = new ArrayList<String>();
String l;
String p;
list = con3.LoginFileRead();
if (list.size() == 2) {
l = list.get(0);
p = list.get(1);
System.out.println("Логин из файла = " + l);
System.out.println("Пароль из файла = " + p);
ID = con3.CRMUserRequest(conn3, l, p);
AdminPanelData = con3.CRMUserFullData(conn3, l, p);
if (ID != 0) {
System.out.println("ID Юзера = " + ID);
LoginStatus = true;
}
}
EC1 = con3.CRMQuery_EntriesCount(conn3); // запрашиваем кол-во записей
StatusTableEntriesCount = con3.CRMQueryStatus_EntriesCount(conn3);
StatusTableFromCount = con3.CRMQueryFRom_EntriesCount(conn3);
System.out.println("Entries count(Из модуля GYU): " + EC1);
if (EC1 > 0) {
CurrentEntry = 1;
System.out.println("Все ОК, текущая запись - " + CurrentEntry);
} else {
System.out.println("Выскакивает обработчик ошибок");
}
con3.Ini();
con3.CRMQuery2(conn3, EC1 + 1);
StatusColumn = con3.CRMQueryStatus(conn3, StatusTableEntriesCount);
FromColumn = con3.CRMQueryFrom(conn3, StatusTableFromCount);
}
public class FirstConnect {
public void FirstEntry() {
int CurStatus = F.GetStatus(CurrentEntry - 1);
int CurFrom = F.GetFrom(CurrentEntry - 1);
if (LoginStatus != false) {
Name_textField.setText(F.GetName(CurrentEntry - 1));
} else {
Name_textField.setText("-");
}
}
}
private void initialize() {
frame = new JFrame();
panel = new JPanel();
frame.setBounds(100, 100, 816, 649);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setBounds(10, 250, 780, 361);
frame.getContentPane().add(tabbedPane);
JPanel panel_1 = new JPanel();
tabbedPane.addTab("\u0412\u0445\u043E\u0434", null, panel_1, null);
btnNewButton = new JButton("\u0412\u0445\u043E\u0434");
btnNewButton.setBounds(263, 285, 226, 37);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int ID;
ID = con3.CRMUserRequest(conn3, LoginField.getText(), PasswordField.getText());
if (ID == 0) {
} else {
MainTab();
FirstEntry3();
}
}
});
panel_1.setLayout(null);
panel_1.add(btnNewButton);
tabbedPane.addTab("\u041A\u043B\u0438\u0435\u043D\u0442", null, panel,
"\u041A\u043E\u043D\u0442\u0430\u043A\u0442\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435 \u043A\u043B\u0438\u0435\u043D\u0442\u0430");
panel.setLayout(null);
// Name_textField = new JTextField();
Name_textField.setBounds(73, 11, 674, 20);
panel.add(Name_textField);
Name_textField.setHorizontalAlignment(SwingConstants.CENTER);
Name_textField.setColumns(10);
NextEntryButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (NextEntryButton.isEnabled() != false) {
if (CurrentEntry < EC1) {
CurrentEntry = CurrentEntry + 1;
int CurStatus = F.GetStatus(CurrentEntry - 1);
int CurFrom = F.GetFrom(CurrentEntry - 1);
Name_textField.setText(F.GetName(CurrentEntry - 1));
} else {
}
}
}
});
}
public void MainTab() {
tabbedPane.addTab("1", null, panel,
"1");
tabbedPane.setEnabledAt(1, true);
panel.setLayout(null);
}
public void FirstEntry3() {
Name_textField.setText(F.GetName(CurrentEntry - 1));
}
}
Related
I have some custom JPanels that are used as buttons. This works well 90% of the time, however, sometimes the GUI doesn't respond to a mouse click - the mouseClicked event is not triggered and you have to click again (sometimes even more than once) to actually trigger it.
This behavior appears to be random, though I have the feeling that it occurs more frequently after having moved the frame to another monitor.
Here is the code:
public class EatingMouse extends JFrame implements MouseListener {
JPanel contentPane;
int contentPanelWidth, contentPanelHeight;
int mainTabMarginHeight, mainTabMarginWidth;
int subTabMarginHeight, subTabMarginWidth;
Color fontColor = Color.WHITE;
Color tabBackgroundColor = Color.BLACK;
Color tabBackgroundHighlightColor = Color.GRAY;
Color tabBackgroundSelectedColor = Color.LIGHT_GRAY;
TabPanel firstMainTab;
TabPanel secondMainTab;
ArrayList<TabPanel> firstSubTabs;
ArrayList<TabPanel> secondSubTabs;
ArrayList<TabPanel> currentSubTabs;
int clickCounter;
public EatingMouse() {
super("Why do you eat mouse clicks?");
JLayeredPane layeredPane = new JLayeredPane();
firstMainTab = new TabPanel("First Tab", 18);
firstMainTab.addMouseListener(this);
layeredPane.add(firstMainTab, new Integer(100));
secondMainTab = new TabPanel("Second Tab", 18);
secondMainTab.addMouseListener(this);
layeredPane.add(secondMainTab, new Integer(100));
firstSubTabs = new ArrayList<>();
secondSubTabs = new ArrayList<>();
currentSubTabs = new ArrayList<>();
TabPanel tp = new TabPanel("First First Subtab", 14);
tp.addMouseListener(this);
layeredPane.add(tp, new Integer(100));
firstSubTabs.add(tp);
tp = new TabPanel("Second First Subtab", 14);
tp.addMouseListener(this);
layeredPane.add(tp, new Integer(100));
firstSubTabs.add(tp);
tp = new TabPanel("First Second Subtab", 14);
tp.addMouseListener(this);
layeredPane.add(tp, new Integer(100));
secondSubTabs.add(tp);
tp = new TabPanel("Second Second Subtab", 14);
tp.addMouseListener(this);
layeredPane.add(tp, new Integer(100));
secondSubTabs.add(tp);
contentPane = new JPanel(new BorderLayout());
setContentPane(contentPane);
contentPane.add(layeredPane);
mainTabMarginWidth = 40;
mainTabMarginHeight = 8;
subTabMarginWidth = 20;
subTabMarginHeight = 10;
selectTabs(0, 1);
clickCounter = 0;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(new Dimension(800, 600));
setVisible(true);
}
public void selectTabs(int mainTab, int subTab) {
boolean hasChanged = false;
if((mainTab == 0) && !firstMainTab.isSelected) {
hasChanged = true;
firstMainTab.setSelected(true);
secondMainTab.setSelected(false);
for(TabPanel tp : currentSubTabs) {
tp.setSelected(false);
tp.setVisible(false);
}
currentSubTabs = firstSubTabs;
for(TabPanel tp : currentSubTabs) {
tp.setVisible(true);
}
currentSubTabs.get(subTab).setSelected(true);
}
else if((mainTab == 1) && !secondMainTab.isSelected) {
hasChanged = true;
firstMainTab.setSelected(false);
secondMainTab.setSelected(true);
for(TabPanel tp : currentSubTabs) {
tp.setSelected(false);
tp.setVisible(false);
}
currentSubTabs = secondSubTabs;
for(TabPanel tp : currentSubTabs) {
tp.setVisible(true);
}
currentSubTabs.get(subTab).setSelected(true);
}
else if((mainTab == 0) && firstMainTab.isSelected) {
hasChanged = true;
for(TabPanel tp : currentSubTabs) {
if(tp != currentSubTabs.get(subTab)) { tp.setSelected(false); }
else { tp.setSelected(true); }
}
}
else if((mainTab == 1) && secondMainTab.isSelected) {
hasChanged = true;
for(TabPanel tp : currentSubTabs) {
if(tp != currentSubTabs.get(subTab)) { tp.setSelected(false); }
else { tp.setSelected(true); }
}
}
if(hasChanged) {
revalidate();
repaint();
}
}
#Override
public void paint(Graphics graphics) {
super.paint(graphics);
contentPanelWidth = getContentPane().getWidth();
contentPanelHeight = getContentPane().getHeight();
int xOffset = 100;
int yOffset = 100;
FontMetrics mainTabMetrics = graphics.getFontMetrics(firstMainTab.label.getFont());
firstMainTab.setBounds(xOffset, yOffset, (mainTabMetrics.stringWidth(firstMainTab.text) + mainTabMarginWidth), (mainTabMetrics.getHeight() + mainTabMarginHeight));
xOffset += firstMainTab.getBounds().width;
secondMainTab.setBounds(xOffset, yOffset, (mainTabMetrics.stringWidth(secondMainTab.text) + mainTabMarginWidth), (mainTabMetrics.getHeight() + mainTabMarginHeight));
FontMetrics subTabMetrics = graphics.getFontMetrics(currentSubTabs.get(0).label.getFont());
xOffset = 100;
yOffset += firstMainTab.getBounds().height;
for(TabPanel tp : currentSubTabs) {
tp.setBounds(xOffset, yOffset, (subTabMetrics.stringWidth(tp.text) + subTabMarginWidth), (subTabMetrics.getHeight() + subTabMarginHeight));
tp.revalidate();
tp.repaint();
xOffset += tp.getBounds().width;
}
}
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("click " + clickCounter++);
Object source = e.getSource();
if(source == firstMainTab && !firstMainTab.isSelected) {
secondMainTab.setSelected(false);
if(currentSubTabs.get(1).isSelected) { selectTabs(0, 1); }
else { selectTabs(0, 0); }
}
else if(source == secondMainTab && !secondMainTab.isSelected) {
if(currentSubTabs.get(1).isSelected) { selectTabs(1, 1); }
else { selectTabs(1, 0); }
}
}
#Override
public void mouseEntered(MouseEvent e) {
Object source = e.getSource();
if(source == firstMainTab && !firstMainTab.isSelected) { firstMainTab.setBackground(tabBackgroundHighlightColor); }
else if(source == secondMainTab && !secondMainTab.isSelected) { secondMainTab.setBackground(tabBackgroundHighlightColor); }
else if(currentSubTabs.contains(source) && !((TabPanel) source).isSelected) {
((TabPanel)source).setBackground(tabBackgroundHighlightColor);
}
}
#Override
public void mouseExited(MouseEvent e) {
Object source = e.getSource();
if(source == firstMainTab && !firstMainTab.isSelected) { firstMainTab.setBackground(tabBackgroundColor); }
else if(source == secondMainTab && !secondMainTab.isSelected) { secondMainTab.setBackground(tabBackgroundColor); }
else if(currentSubTabs.contains(source) && !((TabPanel) source).isSelected) {
((TabPanel)source).setBackground(tabBackgroundColor);
}
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
public class TabPanel extends JPanel {
JLabel label;
String text;
boolean isSelected;
public TabPanel(String labelText, int fontSize) {
super();
text = labelText;
isSelected = false;
setLayout(new GridBagLayout());
setBackground(tabBackgroundColor);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.PAGE_START;
gbc.fill = GridBagConstraints.BOTH;
gbc.weighty = 0.1;
gbc.weightx = 0.1;
gbc.insets = new Insets(0,0,0,0);
label = new JLabel("<html><div style=\"text-align:center\"> " + text + "</div></html>", SwingConstants.CENTER);
label.setAlignmentX(JLabel.CENTER_ALIGNMENT);
label.setForeground(fontColor);
label.setFont(new Font("Arial", Font.BOLD, fontSize));
add(label, gbc);
}
public void setSelected(boolean selected) {
isSelected = selected;
if(selected) { setBackground(tabBackgroundSelectedColor); }
else { setBackground(tabBackgroundColor); }
}
public boolean isSelected() { return isSelected; }
#Override
public String toString() {
return text + " - " + label.getFont().getSize();
}
}
public static void main(String[] args) {
new EatingMouse();
}
}
Please note that I have chosen JPanels as buttons because I want to heavily customize them later, which I didn't get to work with extending JButton.
Thank you for your time reading this and of course I would appreciate any leads on why this is happening and what I can do to improve this code.
I am trying to add a class for each course in the drop down menu on the right corner of the image, as shown in the code in the action Performed there is one class but the same class opens for all the courses so how can i make each one of them open a different class?
this part is confusing me im not sure if i need to do anything with it or not
for (String crse : course) {
courseList.addItem(crse);
}
courseList.setFont(fnt);
courseList.setMaximumSize(courseList.getPreferredSize());
courseList.addActionListener(this);
courseList.setActionCommand("Course");
menuBar.add(courseList);
the list of courses in the left corner works perfectly fine with me but my only problem is instead of the list on the left i want the list on the right to work and it has something to do with crse
public class CourseWork extends JFrame implements ActionListener, KeyListener {
CommonCode cc = new CommonCode();
JPanel pnl = new JPanel(new BorderLayout());
JTextArea txtNewNote = new JTextArea();
JTextArea txtDisplayNotes = new JTextArea();
JTextField search = new JTextField();
ArrayList<String> note = new ArrayList<>();
ArrayList<String> course = new ArrayList<>();
JComboBox courseList = new JComboBox();
String crse = "";
AllNotes allNotes = new AllNotes();
public static void main(String[] args) {
// This is required for the coursework.
//JOptionPane.showMessageDialog(null, "Racha Chaouby");
CourseWork prg = new CourseWork();
}
// Using MVC
public CourseWork() {
model();
view();
controller();
}
#Override
public void actionPerformed(ActionEvent ae) {
if ("Close".equals(ae.getActionCommand())) {
}
if ("Course".equals(ae.getActionCommand())) {
crse = courseList.getSelectedItem().toString();
COMP1752 cw = new COMP1752();
}
if ("Exit".equals(ae.getActionCommand())) {
System.exit(0);
}
if ("NewNote".equals(ae.getActionCommand())) {
addNote(txtNewNote.getText());
txtNewNote.setText("");
}
if ("SearchKeyword".equals(ae.getActionCommand())) {
String lyst = allNotes.searchAllNotesByKeyword("", 0, search.getText());
txtDisplayNotes.setText(lyst);
}
if ("Coursework".equals(ae.getActionCommand())) {
CWDetails cw = new CWDetails();
}
if ("Course1752".equals(ae.getActionCommand())) {
COMP1752 cw = new COMP1752();
}
if ("Course1753".equals(ae.getActionCommand())) {
COMP1753 cw = new COMP1753();
}
if ("Cours1110".equals(ae.getActionCommand())) {
MATH1110 cw = new MATH1110();
}
}
#Override
public void keyTyped(KeyEvent e) {
System.out.println("keyTyped not coded yet.");
}
#Override
public void keyPressed(KeyEvent e) {
System.out.println("keyPressed not coded yet.");
}
#Override
public void keyReleased(KeyEvent e) {
System.out.println("keyReleased not coded yet.");
}
private void model() {
course.add("COMP1752");
course.add("COMP1753");
course.add("MATH1110");
crse = course.get(0);
//Note nt = new Note();
//nt.noteID = 1;
//t.dayte = getDateAndTime();
//nt.course = crse;
//nt.note = "Arrays are of fixed length and are inflexible.";
//allNotes.allNotes.add(nt);
//nt = new Note();
//nt.noteID = 2;
//nt.dayte = getDateAndTime();
//nt.course = crse;
//nt.note = "ArraysList can be added to and items can be deleted.";
//allNotes.allNotes.add(nt);
}
private void view() {
Font fnt = new Font("Georgia", Font.PLAIN, 24);
JMenuBar menuBar = new JMenuBar();
JMenu kurs = new JMenu();
kurs = new JMenu("Courses");
kurs.setToolTipText("Course tasks");
kurs.setFont(fnt);
kurs.add(makeMenuItem("COMP1752", "Course1752", "Coursework requirments.", fnt));
kurs.add(makeMenuItem("COMP1753", "Course1753", "Coursework requirments.", fnt));
kurs.add(makeMenuItem("MATH1110", "Course1110", "Coursework requirments.", fnt));
menuBar.add(kurs);
JMenu note = new JMenu();
note = new JMenu("Note");
note.setToolTipText("Note tasks");
note.setFont(fnt);
note.add(makeMenuItem("New", "NewNote", "Create a new note.", fnt));
note.addSeparator();
note.add(makeMenuItem("Close", "Close", "Clear the current note.", fnt));
menuBar.add(note);
menuBar.add(makeMenuItem("Exit", "Exit", "Close this program", fnt));
// This will add each course to the combobox
for (String crse : course) {
courseList.addItem(crse);
}
courseList.setFont(fnt);
courseList.setMaximumSize(courseList.getPreferredSize());
courseList.addActionListener(this);
courseList.setActionCommand("Course");
menuBar.add(courseList);
this.setJMenuBar(menuBar);
JToolBar toolBar = new JToolBar();
// Setting up the ButtonBar
JButton button = null;
button = makeButton("Document", "Coursework",
"Open the coursework window.",
"Coursework");
toolBar.add(button);
button = makeButton("Create", "NewNote",
"Create a new note.",
"New");
toolBar.add(button);
button = makeButton("closed door", "Close",
"Close this note.",
"Close");
toolBar.add(button);
toolBar.addSeparator();
button = makeButton("exit button", "Exit",
"Exit from this program.",
"Exit");
toolBar.add(button);
toolBar.addSeparator();
// This forces anything after it to the right.
toolBar.add(Box.createHorizontalGlue());
search.setMaximumSize(new Dimension(6900, 30));
search.setFont(fnt);
toolBar.add(search);
toolBar.addSeparator();
button = makeButton("search", "SearchKeyword",
"Search for this text.",
"Search");
toolBar.add(button);
add(toolBar, BorderLayout.NORTH);
JPanel pnlWest = new JPanel();
pnlWest.setLayout(new BoxLayout(pnlWest, BoxLayout.Y_AXIS));
pnlWest.setBorder(BorderFactory.createLineBorder(Color.black));
txtNewNote.setFont(fnt);
pnlWest.add(txtNewNote);
JButton btnAddNote = new JButton("Add note");
btnAddNote.setActionCommand("NewNote");
btnAddNote.addActionListener(this);
pnlWest.add(btnAddNote);
add(pnlWest, BorderLayout.WEST);
JPanel cen = new JPanel();
cen.setLayout(new BoxLayout(cen, BoxLayout.Y_AXIS));
cen.setBorder(BorderFactory.createLineBorder(Color.black));
txtDisplayNotes.setFont(fnt);
cen.add(txtDisplayNotes);
add(cen, BorderLayout.CENTER);
setExtendedState(JFrame.MAXIMIZED_BOTH);
setTitle("Coursework");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true); // Needed to ensure that the items can be seen.
}
private void controller() {
addAllNotes();
}
protected JMenuItem makeMenuItem(
String txt,
String actionCommand,
String toolTipText,
Font fnt) {
JMenuItem mnuItem = new JMenuItem();
mnuItem.setText(txt);
mnuItem.setActionCommand(actionCommand);
mnuItem.setToolTipText(toolTipText);
mnuItem.setFont(fnt);
mnuItem.addActionListener(this);
return mnuItem;
}
protected JButton makeButton(
String imageName,
String actionCommand,
String toolTipText,
String altText) {
//Create and initialize the button.
JButton button = new JButton();
button.setToolTipText(toolTipText);
button.setActionCommand(actionCommand);
button.addActionListener(this);
//Look for the image.
String imgLocation = System.getProperty("user.dir")
+ "\\icons\\"
+ imageName
+ ".png";
File fyle = new File(imgLocation);
if (fyle.exists() && !fyle.isDirectory()) {
// image found
Icon img;
img = new ImageIcon(imgLocation);
button.setIcon(img);
} else {
// image NOT found
button.setText(altText);
System.err.println("Resource not found: " + imgLocation);
}
return button;
}
private void addNote(String text) {
allNotes.addNote(allNotes.getMaxID(), crse, text);
addAllNotes();
}
private void addAllNotes() {
String txtNotes = "";
for (Note n : allNotes.getAllNotes()) {
txtNotes += n.getNote() + "\n";
}
txtDisplayNotes.setText(txtNotes);
}
public String getDateAndTime() {
String UK_DATE_FORMAT_NOW = "dd-MM-yyyy HH:mm:ss";
String ukDateAndTime;
Calendar cal = Calendar.getInstance();
SimpleDateFormat uksdf = new SimpleDateFormat(UK_DATE_FORMAT_NOW);
ukDateAndTime = uksdf.format(cal.getTime());
return ukDateAndTime;
}
}
code snippet
this is the AllNotes class:
public class AllNotes extends CommonCode {
private ArrayList<Note> allNotes = new ArrayList<>();
private String crse = "";
private int maxID = 0;
AllNotes() {
readAllNotes();
}
public final int getMaxID() {
maxID++;
return maxID;
}
private void readAllNotes() {
ArrayList<String> readNotes = new ArrayList<>();
readNotes = readTextFile(appDir + fileSeparator + "Notes.txt");
System.out.println(readNotes.get(0));
if (!"File not found".equals(readNotes.get(0))) {
allNotes.clear();
for (String str : readNotes) {
String[] tmp = str.split("\t");
int nid = Integer.parseInt(tmp[0]);
Note n = new Note(nid, tmp[1], tmp[2], tmp[3]);
allNotes.add(n);
if (nid > maxID) {
maxID = nid;
}
}
}
maxID++;
}
public void addNote(int maxID, String course, String note) {
Note myNote = new Note(maxID, course, note);
allNotes.add(myNote);
writeAllNotes();
}
public ArrayList<Note> getAllNotes() {
return allNotes;
}
private void writeAllNotes() {
String path = appDir + fileSeparator +"Notes.txt";
ArrayList<String> writeNote = new ArrayList<>();
for (Note n : allNotes) {
String tmp = n.getNoteID() + "\t";
tmp += n.getCourse() + "\t";
tmp += n.getDayte() + "\t";
tmp += n.getNote();
writeNote.add(tmp);
}
try {
writeTextFile(path, writeNote);
} catch (IOException ex) {
System.out.println("Problem! " + path);
}
}
public String searchAllNotesByKeyword(String noteList, int i, String s) {
if (i == allNotes.size()) {
return noteList;
}
if (allNotes.get(i).getNote().contains(s)) {
noteList += allNotes.get(i).getNote() + "\n";
}
return searchAllNotesByKeyword(noteList, i + 1, s);
}
}
When you init your drop down of courses, set the action command to be the same value that you record in your file, this will make everything consistent when looking up notes from the file. so this way
kurs.add(makeMenuItem("Course 1752", "COMP1752", "Coursework requirments.", fnt));
kurs.add(makeMenuItem("Course 1753", "COMP1753", "Coursework requirments.", fnt));
kurs.add(makeMenuItem("Course 1110", "MATH1110", "Coursework requirments.", fnt));
Then change actionPerformed to store the selected value form the drop down to the crse attribute, and call addAllNotes() to refresh the notes list
#Override
public void actionPerformed(ActionEvent ae) {
System.out.println("actionPerformed: " + ae.getActionCommand());
if ("Close".equals(ae.getActionCommand())) {
} else if ("Course".equals(ae.getActionCommand())) {
// set the value of the selected element into the crse attribute
crse = courseList.getSelectedItem().toString();
// Refresh the text area
addAllNotes();
} else if ("Exit".equals(ae.getActionCommand())) {
System.exit(0);
} else if ("NewNote".equals(ae.getActionCommand())) {
addNote(txtNewNote.getText());
txtNewNote.setText("");
} else if ("SearchKeyword".equals(ae.getActionCommand())) {
String lyst = allNotes.searchAllNotesByKeyword("", 0, search.getText());
txtDisplayNotes.setText(lyst);
} else if ("Coursework".equals(ae.getActionCommand())) {
CWDetails cw = new CWDetails();
}
System.out.println("selectedCourse: " + crse);
}
in AllNotes, create a new method to return the notes for a specific course.
public ArrayList<Note> getAllNotesForCourse(String course) {
ArrayList<Note> notes = new ArrayList<>();
for(Note note : allNotes) {
if(course.equalsIgnoreCase(note.getCourse())) {
notes.add(note);
}
}
return notes;
}
then in the addAllNotes method, call getAllNotesForCourse, passing the selected course. This will update txtDisplayNotes with the notes from the selected course
private void addAllNotes() {
String txtNotes = "";
for (Note n : allNotes.getAllNotesForCourse(crse)) {
txtNotes += n.getNote() + "\n";
}
txtDisplayNotes.setText(txtNotes);
}
I think this is all I modified and it works for me.
I've been trying to get a running total price of all the elements within my Jlist as they are being added however just can't seem to get it to work. I've tried to provide the classes necessary to be able to reproduce my problem for greater clarity on what I'm trying to do. Thank you.
-Main GUI
public class PaymentSystemGUI extends javax.swing.JFrame {
private JLabel priceLabel;
private JLabel totalLabel;
private JTextField totalField;
private JButton scanBtn;
private JList checkoutList;
private JScrollPane jScrollCheckout;
private JLabel jLabel1;
private JButton removeBtn;
private JButton addBtn;
private JTextField priceField;
private JTextField barcodeField;
private JLabel barcodeLabel;
private JTextField itemNameField;
private JLabel jItemName;
private JLabel editorLabel;
private JScrollPane checkScrollPane;
private JScrollPane jScrollPane1;
private JMenuItem exitButton;
private JMenu StartButton;
private JMenuBar MainMenBar;
private DefaultListModel Inventory = new DefaultListModel();
private DefaultListModel checkoutBasket = new DefaultListModel();
private JList productList;
private InventoryList stockInst;
private JFileChooser chooser;
private File saveFile;
private boolean changesMade;
/**
* Auto-generated main method to display this JFrame
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
PaymentSystemGUI inst = new PaymentSystemGUI();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}
public PaymentSystemGUI() {
super();
initGUI();
stockInst = new InventoryList();
productList.setModel(stockInst);
checkoutList.setModel(checkoutBasket);
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setLayout(null);
getContentPane().setBackground(new java.awt.Color(245, 245, 245));
this.setEnabled(true);
{
MainMenBar = new JMenuBar();
setJMenuBar(MainMenBar);
{
StartButton = new JMenu();
MainMenBar.add(StartButton);
StartButton.setText("File");
{
exitButton = new JMenuItem();
StartButton.add(exitButton);
exitButton.setText("Exit");
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.exit(0);
}
}
);
}
}
{
jScrollPane1 = new JScrollPane();
getContentPane().add(jScrollPane1);
jScrollPane1.setBounds(31, 84, 275, 323);
jScrollPane1.setAlignmentY(0.4f);
{
ListModel stockListModel = new DefaultComboBoxModel(
new String[] { "Item One", "Item Two" });
productList = new JList();
jScrollPane1.setViewportView(productList);
BorderLayout stockListLayout = new BorderLayout();
productList.setLayout(stockListLayout);
productList.setBounds(25, 92, 269, 330);
productList.setAlignmentX(0.4f);
productList.setModel(stockListModel);
}
}
{
editorLabel = new JLabel();
getContentPane().add(editorLabel);
editorLabel.setText("INVENTORY");
editorLabel.setBounds(121, 56, 88, 16);
}
{
jItemName = new JLabel();
getContentPane().add(jItemName);
jItemName.setText("Item Name");
jItemName.setBounds(31, 432, 61, 16);
}
{
itemNameField = new JTextField();
getContentPane().add(itemNameField);
itemNameField.setBounds(127, 426, 130, 28);
}
{
barcodeLabel = new JLabel();
getContentPane().add(barcodeLabel);
barcodeLabel.setText("Barcode Number");
barcodeLabel.setBounds(27, 476, 94, 16);
}
{
barcodeField = new JTextField();
getContentPane().add(barcodeField);
barcodeField.setBounds(127, 470, 130, 28);
}
{
priceLabel = new JLabel();
getContentPane().add(priceLabel);
priceLabel.setText("Price of Item");
priceLabel.setBounds(33, 521, 68, 16);
}
{
priceField = new JTextField();
getContentPane().add(priceField);
priceField.setBounds(127, 515, 130, 28);
}
{
addBtn = new JButton();
getContentPane().add(addBtn);
addBtn.setText("Add");
addBtn.setBounds(53, 560, 83, 28);
}
addBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evta) {
addButtonPressed();
}
});
{
removeBtn = new JButton();
getContentPane().add(removeBtn);
removeBtn.setText("Remove");
removeBtn.setBounds(148, 560, 83, 28);
removeBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
removeButtonPressed();
}
});
}
{
jLabel1 = new JLabel();
getContentPane().add(jLabel1);
jLabel1.setText("CHECKOUT");
jLabel1.setBounds(480, 79, 68, 16);
}
{
jScrollCheckout = new JScrollPane();
getContentPane().add(jScrollCheckout);
jScrollCheckout.setBounds(395, 107, 248, 323);
{
ListModel checkoutListModel =
new DefaultComboBoxModel(
new String[] { "Item One", "Item Two" });
checkoutList = new JList();
jScrollCheckout.setViewportView(checkoutList);
checkoutList.setModel(checkoutListModel);
}
}
{
scanBtn = new JButton();
getContentPane().add(scanBtn);
scanBtn.setText("Scan Item into Checkout");
scanBtn.setBounds(59, 613, 161, 28);
scanBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
checkoutBasket.addElement(productList.getSelectedValue());
double totalAddedValue = 0.00;
double oldCheckoutValue = 0.00;
//Iterate to get the price of the new items.
for (int i = 1; i < productList.getModel().getSize(); i++) {
InventItem item = (InventItem) productList.getModel().getElementAt(i);
totalAddedValue += Double.parseDouble(item.getPrice());
}
//Set total price value as an addition to cart total field.
//cartTotalField must be accessible here.
String checkoutField = totalField.getText();
//Check that cartTextField already contains a value.
if(checkoutField != null && !checkoutField.isEmpty())
{
oldCheckoutValue = Double.parseDouble(checkoutField);
}
totalField.setText(String.valueOf(oldCheckoutValue + totalAddedValue));
checkoutBasket.addElement(productList);
}
});
}
{
totalField = new JTextField();
getContentPane().add(totalField);
totalField.setBounds(503, 442, 115, 28);
totalField.setEditable(false);
}
{
totalLabel = new JLabel();
getContentPane().add(totalLabel);
totalLabel.setText("Total Cost of Items");
totalLabel.setBounds(367, 448, 124, 16);
}
pack();
this.setSize(818, 730);
}
} catch (Exception e) {
// add your error handling code here
e.printStackTrace();
}
}
private void loadMenuItemAction() {
try {
FileInputStream in = new FileInputStream("itemdata.dat");
ObjectInputStream oIn = new ObjectInputStream(in);
stockInst = (InventoryList)oIn.readObject();
productList.setModel(stockInst);
oIn.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Failed to read file");
System.out.println("Error : " + e);
}
}
private void clearAllTextFields() {
barcodeField.setText("");
itemNameField.setText("");
priceField.setText("");
}
private void removeButtonPressed() {
int selectedIndex = productList.getSelectedIndex();
if (selectedIndex == -1) {
JOptionPane.showMessageDialog(this, "Select An Item to Remove");
} else {
InventItem toGo = (InventItem)stockInst.getElementAt(selectedIndex);
if (JOptionPane.showConfirmDialog(this, "Do you really want to remove the item from the cart ? : " + toGo,
"Delete Confirmation", JOptionPane.YES_NO_OPTION)
== JOptionPane.YES_OPTION) {
stockInst.removeItem(toGo.getID());
clearAllTextFields();
productList.clearSelection();
}
}
}
private void addButtonPressed() {
String newbarcode = barcodeField.getText();
String newitemName = itemNameField.getText();
String newprice = priceField.getText();
if (newbarcode.equals("") || newitemName.equals("") || newprice.equals("")) {
JOptionPane.showMessageDialog(this, "Please Enter Full Details");
} else {
stockInst.addInventItem(newbarcode, newitemName, newprice);
InventItem newBasket = stockInst.findItemByName(newbarcode);
productList.setSelectedValue(newBasket, true);
clearAllTextFields();
}
}
}
-InventoryList
import javax.swing.DefaultListModel;
public class InventoryList extends DefaultListModel {
public InventoryList(){
super();
}
public void addInventItem(String idNo, String itemName, String total){
super.addElement(new InventItem(idNo, itemName, total));
}
public InventItem findItemByName(String name){
InventItem temp;
int indexLocation = -1;
for (int i = 0; i < super.size(); i++) {
temp = (InventItem)super.elementAt(i);
if (temp.getItemName().equals(name)){
indexLocation = i;
break;
}
}
if (indexLocation == -1) {
return null;
} else {
return (InventItem)super.elementAt(indexLocation);
}
}
public InventItem findItemByBarcode(String id){
InventItem temp;
int indexLocation = -1;
for (int i = 0; i < super.size(); i++) {
temp = (InventItem)super.elementAt(i);
if (temp.getID().equals(id)){
indexLocation = i;
break;
}
}
if (indexLocation == -1) {
return null;
} else {
return (InventItem)super.elementAt(indexLocation);
}
}
public void removeItem(String id){
InventItem empToGo = this.findItemByBarcode(id);
super.removeElement(empToGo);
}
}
InventoryItem
import java.io.Serializable;
public class InventItem implements Serializable {
private String idnum;
private String itemName;
private String cost;
public InventItem() {
}
public InventItem (String barno, String in, String price) {
idnum = barno;
itemName = in;
cost = price;
}
public String getID(){
return idnum;
}
public String getItemName(){
return itemName;
}
public void setitemName(String itemName){
this.itemName = itemName;
}
public String getPrice(){
return cost;
}
public String toString(){
return idnum + ": " + itemName + ", £ " + cost;
}
}
I'm a beginner and don't quite know how to change my code to add a single element from the list.
Read the List API and you will find methods like:
size()
get(...)
So you create a loop that loops from 0 to the number of elements. Inside the loop you get the element from the List and add it to the model of the checkoutBasket JList.
Here is the basics of an MCVE to get you started. All you need to do is add the code for the actionPerformed() method to copy the selected item(s):
import java.awt.*;
import java.awt.event.*;
import java.util.List;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.table.*;
public class SSCCE extends JPanel
{
JList<String> left;
JList<String> right;
JLabel total;
public SSCCE()
{
setLayout( new BorderLayout() );
// change this to store Integer objects
String[] data = { "one", "two", "three", "four", "five", "four", "six", "seven" };
left = new JList<String>(data);
add(new JScrollPane(left), BorderLayout.WEST);
right = new JList<String>( new DefaultListModel<String>() );
add(new JScrollPane(right), BorderLayout.EAST);
JButton button = new JButton( "Copy" );
add(button, BorderLayout.CENTER);
button.addActionListener( new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
DefaultListModel<String> model = (DefaultListModel<String>)right.getModel();
List<String> selected = left.getSelectedValuesList();
for (String item: selected)
model.addElement( item );
// add code here to loop through right list and total the Integer items
total.setText("Selected total is ?");
}
});
total = new JLabel("Selected total is 0");
add(total, BorderLayout.SOUTH);
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new SSCCE() );
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
If you have a problem then delete your original code and post the MCVE showing what you have tried based on the information in this answer. Don't create a new posting.
Edit:
My original answer talked about copying the data from the DefaultListModel. However, your code is using the JList.getSelectedValuesList() method to get a List of selected items. Each of these items needs to be copied from the List to the ListModel of the JList. I updated my answer to reflect this part of your code. I even wrote the code to show you how to copy the items from the list.
So now your next step is to calculate the a total of the items in the "right" JLIst (ie, your checkout basked). In order to do this, you need to change the data in the "left" list to be "Integer" Objects. So now when you copy the Integer objects yo9u can then iterate through the JList and calculate a total value. If you have problems, then any code you post should be based on this MVCE and NOT your real program.
I am having trouble with one part of my code. I have been working for so long on this and I am exhausted and missing something easy. I need to have a text box to enter a new title for the JFrame, a button that says "Set New Name" and an "Exit Button.
Can someone look at this code and give me some info so I can go to bed.
Thank you
//Good One
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.text.*;
import java.util.*;
import javax.swing.*;
public class Pool {
public static void main(String[] args) {
new poolCalc();
}
}
class poolCalc extends JFrame {
private static final long serialVersionUID = 1L;
public static final double MILLIMETER = 1;
public static final double METER = 1000 * MILLIMETER;
public static final double INCH = 25.4 * MILLIMETER;
public static final double FOOT = 304.8 * MILLIMETER;
public static final double YARD = 914.4 * MILLIMETER;
private static final DecimalFormat df = new DecimalFormat("#,##0.###");
private JTabbedPane tabs;
private JPanel generalPanel;
private JPanel optionsPanel;
private JPanel customerPanel;
private JPanel contractorPanel;
private JPanel poolPanel;
private JPanel hotTubPanel;
private JPanel tempCalPanel;
private JPanel lengthCalPanel;
public poolCalc() {
super("The Pool Calculator");
setSize(340, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(true);
initializeComponents();
setLocationRelativeTo(null);
setVisible(true);
}
private void initializeComponents() {
Container pane = getContentPane();
tabs = new JTabbedPane();
generalTab();
optionsTab();
customerTab();
contractorTab();
poolsTab();
hotTubsTab();
tempCalTab();
lengthCalTab();
tabs.add("General", generalPanel);
tabs.add("Options", optionsPanel);
tabs.add("Customers", customerPanel);
tabs.add("Contractors", contractorPanel);
tabs.add("Pools", poolPanel);
tabs.add("Hot Tubs", hotTubPanel);
tabs.add("Temp Calc", tempCalPanel);
tabs.add("Length Calc", lengthCalPanel);
pane.add(tabs);
}
private JButton createExitButton() {
JButton exitButton = new JButton("Exit");
exitButton.setMnemonic('x');
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
return exitButton;
}
private void generalTab() {
generalPanel = new JPanel(new FlowLayout());
String currentTime = SimpleDateFormat.getInstance().format(
Calendar.getInstance().getTime());
generalPanel.add(new JLabel("Today's Date: " + currentTime));
generalPanel.add(createExitButton());
}
private JTextField createTitleField(String text, int length) {
JTextField tf = new JTextField(length);
tf.setEditable(false);
tf.setFocusable(false);
tf.setText(text);
return tf;
}
// FIX
private void optionsTab() {
optionsPanel = new JPanel(new FlowLayout());
//optionsPanel.setLayout(null);
JLabel labelOptions = new JLabel("Change Company Name:");
labelOptions.setBounds(120, 10, 150, 20);
optionsPanel.add(labelOptions);
final JTextField newTitle = new JTextField("Some Title");
newTitle.setBounds(80, 40, 225, 20);
optionsPanel.add(newTitle);
final JTextField myTitle = new JTextField("My Title...");
myTitle.setBounds(80, 40, 225, 20);
myTitle.add(labelOptions);
JButton newName = new JButton("Set New Name");
newName.setBounds(60, 80, 150, 20);
//newName.addActionListener(this);
optionsPanel.add(newName);
optionsPanel.add(createExitButton());
}
private void customerTab() {
customerPanel = createContactPanel("Customer", "customer.txt");
}
private void contractorTab() {
contractorPanel = createContactPanel("Contractor", "contractor.txt");
}
private void poolsTab() {
poolPanel = new JPanel(new FlowLayout());
final JRadioButton roundPool = new JRadioButton("Round Pool");
final JRadioButton ovalPool = new JRadioButton("Oval Pool");
final JRadioButton rectangularPool = new JRadioButton("Rectangle Pool");
roundPool.setSelected(true);
ButtonGroup group = new ButtonGroup();
group.add(roundPool);
group.add(rectangularPool);
poolPanel.add(roundPool);
poolPanel.add(rectangularPool);
poolPanel.add(new JLabel("Enter the pool's length (ft): "));
final JTextField lengthField = new JTextField(10);
poolPanel.add(lengthField);
final JLabel widthLabel = new JLabel("Enter the pool's width (ft): ");
widthLabel.setEnabled(false);
poolPanel.add(widthLabel);
final JTextField widthField = new JTextField(10);
widthField.setEnabled(false);
poolPanel.add(widthField);
poolPanel.add(new JLabel("Enter the pool's depth (ft): "));
final JTextField depthField = new JTextField(10);
poolPanel.add(depthField);
JButton calculateVolume = new JButton("Calculate Volume");
calculateVolume.setMnemonic('C');
poolPanel.add(calculateVolume);
poolPanel.add(createExitButton());
poolPanel.add(new JLabel("The pool's volume is (ft^3): "));
final JTextField volumeField = new JTextField(10);
volumeField.setEditable(false);
poolPanel.add(volumeField);
final JTextArea messageArea = createMessageArea(2, 20, "");
poolPanel.add(messageArea);
calculateVolume.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (roundPool.isSelected()) {
widthField.setText(lengthField.getText());
}
ValidationResult result = validateFields(new JTextField[] {
lengthField, widthField, depthField });
String errors = "";
if (result.filled != 3) {
errors += "Please fill out all fields! ";
}
if (result.valid != 3 && result.filled != result.valid) {
errors += "Please enter valid numbers!";
}
if (errors != "") {
messageArea.setText(errors);
messageArea.setVisible(true);
}
else {
messageArea.setVisible(false);
double length = Double.parseDouble(lengthField.getText());
double width = Double.parseDouble(widthField.getText());
double depth = Double.parseDouble(depthField.getText());
double volume;
if (roundPool.isSelected()) {
volume = Math.PI * Math.pow(length / 2.0, 2) * depth;
}
if (rectangularPool.isSelected()) {
volume = length * width * depth * 5.9;
}
else {
volume = length * width * depth * 7.5;
}
volumeField.setText(df.format(volume));
}
}
});
ActionListener poolsListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == roundPool) {
widthLabel.setEnabled(false);
widthField.setEnabled(false);
widthField.setText(lengthField.getText());
}
else if (e.getSource() == rectangularPool) {
widthLabel.setEnabled(true);
widthField.setEnabled(true);
messageArea.setVisible(false);
}
}
};
roundPool.addActionListener(poolsListener);
ovalPool.addActionListener(poolsListener);
rectangularPool.addActionListener(poolsListener);
}
private void hotTubsTab() {
hotTubPanel = new JPanel(new FlowLayout());
final JRadioButton roundTub = new JRadioButton("Round Tub");
final JRadioButton ovalTub = new JRadioButton("Oval Tub");
roundTub.setSelected(true);
ButtonGroup group = new ButtonGroup();
group.add(roundTub);
group.add(ovalTub);
hotTubPanel.add(roundTub);
hotTubPanel.add(ovalTub);
hotTubPanel.add(new JLabel("Enter the tub's length (ft): "));
final JTextField lengthField = new JTextField(10);
hotTubPanel.add(lengthField);
final JLabel widthLabel = new JLabel("Enter the tub's width (ft): ");
widthLabel.setEnabled(false);
hotTubPanel.add(widthLabel);
final JTextField widthField = new JTextField(10);
widthField.setEnabled(false);
hotTubPanel.add(widthField);
hotTubPanel.add(new JLabel("Enter the tub's depth (ft): "));
final JTextField depthField = new JTextField(10);
hotTubPanel.add(depthField);
JButton calculateVolume = new JButton("Calculate Volume");
calculateVolume.setMnemonic('C');
hotTubPanel.add(calculateVolume);
hotTubPanel.add(createExitButton());
hotTubPanel.add(new JLabel("The tub's volume is (ft^3): "));
final JTextField volumeField = new JTextField(10);
volumeField.setEditable(false);
hotTubPanel.add(volumeField);
final JTextArea messageArea = createMessageArea(1, 25,
"Width will be set to the same value as length");
hotTubPanel.add(messageArea);
calculateVolume.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (roundTub.isSelected()) {
widthField.setText(lengthField.getText());
}
ValidationResult result = validateFields(new JTextField[] {
lengthField, widthField, depthField });
String errors = "";
if (result.filled != 3) {
errors += "Please fill out all fields! ";
}
if (result.valid != 3 && result.filled != result.valid) {
errors += "Please enter valid numbers!";
}
if (errors != "") {
messageArea.setText(errors);
messageArea.setVisible(true);
}
else {
messageArea.setVisible(false);
double length = Double.parseDouble(lengthField.getText());
double width = Double.parseDouble(widthField.getText());
double depth = Double.parseDouble(depthField.getText());
double volume;
if (roundTub.isSelected()) {
volume = Math.PI * Math.pow(length / 2.0,2) * depth;
}
if (ovalTub.isSelected()) {
volume = Math.PI * ((length * width)*2) * depth;
}
else {
volume = length * width * depth * 7.5;
}
volumeField.setText(df.format(volume));
}
}
});
ActionListener tubsListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == roundTub) {
widthLabel.setEnabled(false);
widthField.setEnabled(false);
widthField.setText(lengthField.getText());
}
else if (e.getSource() == ovalTub) {
widthLabel.setEnabled(true);
widthField.setEnabled(true);
messageArea.setVisible(false);}
}
};
roundTub.addActionListener(tubsListener);
ovalTub.addActionListener(tubsListener);}
private void tempCalTab() {
tempCalPanel = new JPanel(new FlowLayout());
tempCalPanel.add(new JLabel("Enter temperature: "));
final JTextField temperatureField = new JTextField(10);
tempCalPanel.add(temperatureField);
final JComboBox optionComboBox = new JComboBox(
new String[] { "C", "F" });
tempCalPanel.add(optionComboBox);
tempCalPanel.add(new JLabel("Result: "));
final JTextField resultField = new JTextField(18);
resultField.setEditable(false);
tempCalPanel.add(resultField);
final JLabel oppositeLabel = new JLabel("F");
tempCalPanel.add(oppositeLabel);
JButton convertButton = new JButton("Convert");
convertButton.setMnemonic('C');
tempCalPanel.add(convertButton);
tempCalPanel.add(createExitButton());
final JTextArea messageArea = createMessageArea(1, 20,
"System Messages");
tempCalPanel.add(messageArea);
optionComboBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
if ("F".equals(e.getItem())) {
oppositeLabel.setText("C");}
else {
oppositeLabel.setText("F");}}}
});
convertButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ValidationResult result = validateFields(new JTextField[] { temperatureField });
String errors = "";
if (result.filled != 1 || result.valid != 1) {
errors += "Value set to zero";}
if (errors != "") {
messageArea.setText(errors);
messageArea.setVisible(true);
temperatureField.setText("0");}
else {
messageArea.setVisible(false);}
double temperature = Double.parseDouble(temperatureField
.getText());
double resultValue = 0;
if (oppositeLabel.getText().equals("C")) {
resultValue = (temperature - 32.0) / 9.0 * 5.0;}
else if (oppositeLabel.getText().equals("F")) {
resultValue = ((temperature * 9.0) / 5.0) + 32.0;}
resultField.setText(df.format(resultValue));}
});
}
private void lengthCalTab() {
lengthCalPanel = new JPanel(new FlowLayout());
lengthCalPanel.add(createTitleField("Millimeters", 6));
lengthCalPanel.add(createTitleField("Meters", 4));
lengthCalPanel.add(createTitleField("Yards", 4));
lengthCalPanel.add(createTitleField("Feet", 3));
lengthCalPanel.add(createTitleField("Inches", 6));
final JTextField millimetersField = new JTextField(6);
final JTextField metersField = new JTextField(4);
final JTextField yardsField = new JTextField(4);
final JTextField feetField = new JTextField(3);
final JTextField inchesField = new JTextField(6);
lengthCalPanel.add(millimetersField);
lengthCalPanel.add(metersField);
lengthCalPanel.add(yardsField);
lengthCalPanel.add(feetField);
lengthCalPanel.add(inchesField);
JButton convertButton = new JButton("Convert");
convertButton.setMnemonic('C');
convertButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double millimeters = convertToDouble(millimetersField.getText());
double meters = convertToDouble(metersField.getText());
double yards = convertToDouble(yardsField.getText());
double feet = convertToDouble(feetField.getText());
double inches = convertToDouble(inchesField.getText());
double value = 0;
if (millimeters != 0) {
value = millimeters * MILLIMETER;}
else if (meters != 0) {
value = meters * METER;}
else if (yards != 0) {
value = yards * YARD;}
else if (feet != 0) {
value = feet * FOOT;}
else if (inches != 0) {
value = inches * INCH;}
millimeters = value / MILLIMETER;
meters = value / METER;
yards = value / YARD;
feet = value / FOOT;
inches = value / INCH;
millimetersField.setText(df.format(millimeters));
metersField.setText(df.format(meters));
yardsField.setText(df.format(yards));
feetField.setText(df.format(feet));
inchesField.setText(df.format(inches));}
private double convertToDouble(String s) {
try {
return Double.parseDouble(s);}
catch (Exception e) {
return 0;}}
});
JButton clearButton = new JButton("Clear");
clearButton.setMnemonic('l');
clearButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
millimetersField.setText(null);
metersField.setText(null);
yardsField.setText(null);
feetField.setText(null);
inchesField.setText(null);}
});
lengthCalPanel.add(convertButton);
lengthCalPanel.add(clearButton);
lengthCalPanel.add(createExitButton());}
private String loadDataFromFile(String fileName) {
String data = "";
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
while (reader.ready()) {
data += reader.readLine() + "\n";}
reader.close();}
catch (IOException e){
}
return data;}
private JPanel createContactPanel(final String contactName,
final String fileName) {
JPanel pane = new JPanel(new FlowLayout());
final JTextArea customerDisplay = new JTextArea(8, 25);
customerDisplay.setLineWrap(true);
customerDisplay.setEditable(false);
pane.add(new JScrollPane(customerDisplay));
pane.add(createExitButton());
JButton addCustomerButton = new JButton("Add " + contactName);
addCustomerButton.setMnemonic('A');
pane.add(addCustomerButton);
JButton refreshButton = new JButton("Refresh");
refreshButton.setMnemonic('R');
pane.add(refreshButton);
final JTextArea messageArea = createMessageArea(2, 25, "");
messageArea.setBackground(Color.white);
pane.add(messageArea);
addCustomerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new EditContact(contactName, fileName);}
});
refreshButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = loadDataFromFile(fileName);
if (data != "") {
customerDisplay.setText(data);
customerDisplay.setEnabled(true);
messageArea.setText("File " + fileName
+ " can be read from!");
}
else {
customerDisplay.setText("Click Add "
+ contactName
+ " button to add "
+ contactName.toLowerCase()
+ ". And click Refresh button to update this pane.");
customerDisplay.setEnabled(false);
messageArea.setText("File " + fileName + " is not "
+ "there yet! It will be created "
+ "when you add " + contactName.toLowerCase()
+ "s!");
}
}
});
refreshButton.doClick();
return pane;
}
private JTextArea createMessageArea(int rows, int cols, String text) {
final JTextArea messageArea = new JTextArea(rows, cols);
messageArea.setBorder(BorderFactory.createEmptyBorder());
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setFont(new Font("System", Font.PLAIN, 12));
messageArea.setText(text);
messageArea.setBackground(null);
messageArea.setForeground(Color.GRAY);
messageArea.setEnabled(true);
messageArea.setFocusable(false);
return messageArea;
}
private class ValidationResult {
int filled;
int valid;
}
private ValidationResult validateFields(JTextField[] fields) {
ValidationResult result = new ValidationResult();
for (int i = 0; i < fields.length; i++) {
JTextField field = fields[i];
if ((field.getText() != null) && (field.getText().length() > 0)) {
result.filled++;
}
try {
Double.parseDouble(field.getText());
field.setBackground(Color.white);
result.valid++;
}
catch (Exception e) {
field.setBackground(Color.orange);
}
}
return result;
}
private class EditContact extends JDialog {
private static final long serialVersionUID = 1L;
private final String contactName;
private final String fileName;
private File file;
private JTextField nameField;
private JTextField addressField;
private JTextField cityField;
private JComboBox stateComboBox;
private JTextField zipField;
private JTextField phoneField;
private JTextArea messageArea;
public EditContact(String contactName, String fileName) {
super(poolCalc.this, contactName + "s");
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setModalityType(ModalityType.APPLICATION_MODAL);
setSize(418, 300);
this.contactName = contactName;
this.fileName = fileName;
initializeComponents();
if (openFile()) {
displayMessage(null);
}
else {
displayMessage("File " + fileName + " does not exist yet! "
+ "Will be created when you add a "
+ contactName.toLowerCase() + "!");
}
setLocationRelativeTo(null);
setVisible(true);
}
private void displayMessage(String message) {
if (message != null) {
messageArea.setVisible(true);
messageArea.setText(message);
}
else {
messageArea.setVisible(false);
}
}
private boolean openFile() {
file = new File(fileName);
return file.exists();
}
private boolean deleteFile() {
return file.exists() && file.delete();
}
private boolean saveToFile() {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(file,
true));
writer.write("Name: " + nameField.getText() + "\n");
writer.write("Address: " + addressField.getText() + "\n");
writer.write("City: " + cityField.getText() + "\n");
writer.write("State: "
+ stateComboBox.getSelectedItem().toString() + "\n");
writer.write("ZIP: " + zipField.getText() + "\n");
writer.write("Phone: " + phoneField.getText() + "\n");
writer.write("\n");
writer.close();
return true;
}
catch (IOException e) {
return false;
}
}
private void initializeComponents() {
Container pane = getContentPane();
pane.setLayout(new FlowLayout());
pane.add(new JLabel(contactName + " Name "));
nameField = new JTextField(25);
pane.add(nameField);
pane.add(new JLabel("Address "));
addressField = new JTextField(28);
pane.add(addressField);
pane.add(new JLabel("City "));
cityField = new JTextField(32);
pane.add(cityField);
pane.add(new JLabel("State "));
stateComboBox = new JComboBox(new String[] { "AL", "AK", "AZ",
"AR", "CA", "CO", "CT", "DE", "FL", "GA", "HI", "ID", "IL",
"IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN",
"MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC",
"ND", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX",
"UT", "VT", "VA", "WA", "WV", "WI", "WY" });
pane.add(stateComboBox);
pane.add(new JLabel("ZIP "));
zipField = new JTextField(5);
pane.add(zipField);
pane.add(new JLabel("Phone "));
phoneField = new JTextField(10);
pane.add(phoneField);
JButton addContactButton = new JButton("Add " + this.contactName);
addContactButton.setMnemonic('A');
addContactButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (saveToFile()) {
displayMessage(contactName + " added");
}
else {
displayMessage("File saving error!");
}
}
});
pane.add(addContactButton);
JButton closeButton = new JButton("Close");
closeButton.setMnemonic('C');
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
pane.add(closeButton);
JButton deleteFileButton = new JButton("Delete File");
deleteFileButton.setMnemonic('D');
deleteFileButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (deleteFile()) {
displayMessage("File " + fileName + " deleted!");
}
}
});
pane.add(deleteFileButton);
messageArea = createMessageArea(2, 30, "");
messageArea.setBackground(Color.white);
pane.add(messageArea);
}
}
}
Let's start with this (which I assume is where you create the details)...
private void optionsTab() {
optionsPanel = new JPanel(new FlowLayout());
//optionsPanel.setLayout(null);
JLabel labelOptions = new JLabel("Change Company Name:");
labelOptions.setBounds(120, 10, 150, 20);
optionsPanel.add(labelOptions);
final JTextField newTitle = new JTextField("Some Title");
newTitle.setBounds(80, 40, 225, 20);
optionsPanel.add(newTitle);
final JTextField myTitle = new JTextField("My Title...");
myTitle.setBounds(80, 40, 225, 20);
myTitle.add(labelOptions);
JButton newName = new JButton("Set New Name");
newName.setBounds(60, 80, 150, 20);
//newName.addActionListener(this);
optionsPanel.add(newName);
optionsPanel.add(createExitButton());
}
The newTitle field is a local variable, so once the method exists, you will not be able to access the field (easily)...
You seem to have tried adding a actionListener to the newName button, which isn't a bad idea, but because you can't actually access the newTitle field, isn't going to help...
The use of setBounds is not only ill advised, but probably won't result in the results you are expecting, because the optionsPane is under the control a layout manager...
And while I was digging around, I noticed this if (errors != "") {...This is not how String comparison is done in Java. This is comparing the memory references of both Strings which will never be true, instead you should if (!"".equals(errors)) {...
But back to the problem at hand...
You are really close to having a solution. You could make the newTitle field a class instance variable, which would allow you to access the field within other parts of your program, but because you've made it final, there's something else you can try...
You can use an anonymous inner class instead...
newName.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setTitle(newTitle.getText());
}
});
Which should get a good nights sleep :D
It is a little unclear what you want, but if I understand you right you want the JButton newName to set the title of the JFrame to the text in some textbox?
In that case you would write
setTitle(someTextbox.getText());
inside the function of the button.
First, you need to create a JTextField that has public access. Then, create a JButton that implements ActionListener. After that you must implement the abstract method actionPerformed() in the JButton Subclass. Then in the run method say JFrame.setTitle(JTextfield.getText()).
Subclass Method:
public class main extends JFrame{
// Construct and setVisible()
}
class textfield extends JTextField{
// create field then add to JFrame
}
class button extends JButton implements ActionListener{
// create button
public void actionPerformed(ActionEvent e){
main.setTitle(textfield.getText());
}
Instance Method:
public class main implements ActionListener{
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JTextField field = new JTextField();
JButton button = new JButtone();
button.addActionListener(this);
panel.add(field);
panel.add(button);
frame.add(panel);
public void actionPerformed(ActionEvent e){
frame.setTitle(field.getText);
}
}
Try This
private void optionsTab() {
optionsPanel = new JPanel(new FlowLayout());
// optionsPanel.setLayout(null);
JLabel labelOptions = new JLabel("Change Company Name:");
labelOptions.setBounds(120, 10, 150, 20);
optionsPanel.add(labelOptions);
final JTextField newTitle = new JTextField("Some Title");
newTitle.setBounds(80, 40, 225, 20);
optionsPanel.add(newTitle);
final JTextField myTitle = new JTextField("My Title...");
myTitle.setBounds(80, 40, 225, 20);
myTitle.add(labelOptions);
JButton newName = new JButton("Set New Name");
newName.setBounds(60, 80, 150, 20);
newName.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setTitle(newTitle.getText());
}
});
// newName.addActionListener(this);
optionsPanel.add(newName);
optionsPanel.add(createExitButton());
}
I have a problem.
I have an element that would JPanel.
In this JPanel would be four JButtons and image.
This image is 'green LED lights' that would change depending on which JButton would be pressed.
It works very well.
But also I want the JComboBox to change this paramter.
And here's the problem.
Although the parameter (from 1 to 4) is changing,(this shows JLabel near LEDs),
but the picture (LED lights) do not want to change it to the right one.
screenshot
The program is divided into 3 classes.
MyFrame.class This main class.
public class MyFrame extends JFrame {
int ctrlTriggers = 1;
private JLabel label = new JLabel();
private Triggers triggers;
private String[] typeTrig = {"1", "2", "3", "4"};
public MyFrame() {
JFrame frame = new JFrame("JComboBox Problem");
frame.setBounds(50, 0, 800, 240);
frame.setLayout(new BorderLayout());
int tvalue = 1;
String tstr = Integer.toString(tvalue);
JPanel panelTrig = new JPanel(new BorderLayout());
label = new JLabel(tstr, 4);
panelTrig.add(label);
final JLabel et = label;
triggers = new Triggers(typeTrig, "trigger " + Integer.toString(1));
triggers.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
Triggers tr = (Triggers) e.getSource();
int vol;
vol = (int) tr.getValue();
et.setText(Integer.toString(vol));
}
});
panelTrig.add(triggers, BorderLayout.LINE_START);
// JCOMBOBOX
JPanel pCombo = new JPanel();
pCombo.setLayout(new FlowLayout());
Presets combo = new Presets();
combo.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
Presets presetcombo = (Presets) e.getSource();
int tval;
tval = (int) presetcombo.getValue(ctrlTriggers);
label.setText(Integer.toString(tval));
triggers.setValue(tval);
}
});
pCombo.add(combo, BorderLayout.CENTER);
frame.add(pCombo, BorderLayout.CENTER);
frame.add(panelTrig, BorderLayout.LINE_START);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
frame.show();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MyFrame();
}
});
}
}
Triggers.class This class is JPanel where is 4 JButton and 'LED like image'
public class Triggers extends JPanel
implements ActionListener, ItemListener {
public Triggers(String s[], String name) {
JPanel panel = new JPanel(new BorderLayout());
this.value = Integer.parseInt(s[selected]);
for (int i = 0; i < s.length; i++) {
ImageIcon cup = new ImageIcon();
button[i] = new JButton(z[i], cup);
button[i].setPreferredSize(new Dimension(70, 25));
Font font = button[i].getFont();
button[i].setFont(new Font(font.getFontName(), font.getStyle(), 10));
button[i].setActionCommand(s[i]);
if (i == selected) {
button[i].setSelected(true);
} else {
button[i].setSelected(false);
}
}
ButtonGroup group = new ButtonGroup();
for (int i = 0; i < s.length; i++) {
group.add(button[i]);
button[i].addActionListener(this);
button[i].addItemListener(this);
}
diody = new JLabel(createImageIcon("/resources/diody/"
+ this.value
+ ".png"));
diody.setPreferredSize(new Dimension(20, 100));
JPanel triggs = new JPanel(new FlowLayout());
triggs.setPreferredSize(new Dimension(80, 120));
for (int i = 0; i < s.length; i++) {
triggs.add(button[i]);
}
panel.add(triggs, BorderLayout.LINE_START);
panel.add(diody, BorderLayout.LINE_END);
add(panel);
}
public void actionPerformed(ActionEvent e) {
cmd = e.getActionCommand();
diody.setIcon(createImageIcon("/resources/diody/"
+ cmd
+ ".png"));
if (cmd.equals("1")) {
setValue(1);
} else if (cmd.equals("2")) {
setValue(2);
} else if (cmd.equals("3")) {
setValue(3);
} else if (cmd.equals("4")) {
setValue(4);
}
}
public static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = Triggers.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
public int setController() {
return value;
}
public void setValue(int k) {
this.value = k;
cmd = Integer.toString(this.value);
repaint();
fireChangeEvent();
}
public int getValue() {
return this.value;
}
public void setSel(int k) {
selected = k;
repaint();
fireChangeEvent();
}
public void itemStateChanged(ItemEvent ie) {
String s = (String) ie.getItem();
}
public void addChangeListener(ChangeListener cl) {
listenerList.add(ChangeListener.class, cl);
}
public void removeChangeListener(ChangeListener cl) {
listenerList.remove(ChangeListener.class, cl);
}
protected void fireChangeEvent() {
Object[] listeners = listenerList.getListenerList();
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == ChangeListener.class) {
if (changeEvent == null) {
changeEvent = new ChangeEvent(this);
}
((ChangeListener) listeners[i + 1]).stateChanged(changeEvent);
}
}
}
private ChangeEvent changeEvent = null;
private EventListenerList listenerList = new EventListenerList();
private JLabel diody;
private int x = 1;
private int y = 4;
private JButton button[] = new JButton[y];
double border = 4;
double vborder = 1;
int controller[] = new int[4];
String z[] = {"1", "2", "3", "4"};
private int selected;
private int value;
private String cmd;
}
class Presets Here is JCombobox.
public class Presets extends JPanel
implements ActionListener {
private int value;
private int[] ctrlIdx = new int[27];
private int controller;
private ChangeEvent changeEvent = null;
private EventListenerList listenerList = new EventListenerList();
private JLabel label;
private String[][] presets = {
{"0", "3"},
{"1", "2"},
{"2", "3"},
{"3", "1"},
{"4", "4"},
{"5", "2"},};
String[] ctrlName = {"preset 1 (value 3)", "preset 2 (value 2)", "preset 3 (value 3)", "preset 4 (value 1)", "preset 5 (value 4)", "preset 5 (value 2)"};
public Presets() {
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.setPreferredSize(new Dimension(600, 30));
JComboBox combolist = new JComboBox(ctrlName);
combolist.setSelectedIndex(2);
combolist.addActionListener(this);
combolist.setPreferredSize(new Dimension(300, 30));
label = new JLabel();
label.setFont(label.getFont().deriveFont(Font.ITALIC));
label.setHorizontalAlignment(JLabel.CENTER);
int indeks = combolist.getSelectedIndex();
updateLabel(ctrlName[combolist.getSelectedIndex()], indeks);
label.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
label.setPreferredSize(new Dimension(300, 30));
panel.add(combolist, "East");
add(panel);
setPreferredSize(new Dimension(600, 40));
}
public void setSelectedItem(int a) {
}
public void setValue(int c, int v) {
controller = c;
value = v;
ctrlIdx[controller] = value;
repaint();
fireChangeEvent();
}
public int getController() {
return controller;
}
public int getValue(int c) {
int w = (int) ctrlIdx[c];
return (int) w;
}
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox) e.getSource();
String pres = (String) cb.getSelectedItem();
int indeks = cb.getSelectedIndex();
updateLabel(pres, indeks);
for (int i = 0; i < ctrlName.length; i++) {
for (int j = 0; j < 2; j++) {
setValue(j, Integer.parseInt(presets[indeks][j]));
}
}
}
protected void updateLabel(String name, int ii) {
label.setToolTipText("A drawing of a " + name.toLowerCase());
}
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = Presets.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
public void addChangeListener(ChangeListener cl) {
listenerList.add(ChangeListener.class, cl);
}
public void removeChangeListener(ChangeListener cl) {
listenerList.remove(ChangeListener.class, cl);
}
protected void fireChangeEvent() {
Object[] listeners = listenerList.getListenerList();
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == ChangeListener.class) {
if (changeEvent == null) {
changeEvent = new ChangeEvent(this);
}
((ChangeListener) listeners[i + 1]).stateChanged(changeEvent);
}
}
}
}
Could someone help me, what am I doing wrong?
Your image is only begin loaded in the actionPerformed method of your Triggers class, which means when you call setValue in response to the stateChanged event thrown by the Presets class, no new image is begin loaded.
Move your image loading logic so it is either in the setValue method or triggered by the setValue method