How to get JComboBox updated automatically? - java

I'm struggling with update my item in JComboBox. When I load item from a file, the combobox display properly, however when I tried to add or remove item from combobox item, the combobox doesn't update automatically, it still remain the same item instead. Here is my code
This is where I load the combobox item
ObjectInputStream input;
try {
// TODO add your handling code here:
JFileChooser openFileChooser = new JFileChooser();
openFileChooser.setCurrentDirectory(new File("."));
if (openFileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
input = new ObjectInputStream(new FileInputStream(openFileChooser.getSelectedFile()));
diary = (Diary)input.readObject();
jTextArea3.setText(diary.getUnitCollection().toString());
input.close();
//Load Unit Item
for (Unit u: diary.getUnitCollection()){
jComboBox8.addItem(u.getUnitName());
jComboBox1.addItem(u.getUnitName());
}
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
}
This is button to remove item
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
for (int i = 0; i < diary.getUnitCollection().size(); i++){
if (jComboBox8.getSelectedItem().equals(diary.getUnitCollection().get(i).getUnitName())){
diary.getUnitCollection().remove(diary.getUnitCollection().get(i));
jTextArea3.setText("The Unit " + jComboBox8.getSelectedItem()+ " has been removed successfully");
}
}
}
edit: just fix style (code block)

You need to add and remove content via a model, check out http://docs.oracle.com/javase/7/docs/api/javax/swing/DefaultComboBoxModel.html

Related

Java Swing JEditorPane insert bold tags around selection

I'm using Java Swing and I have a JEditorPane with content type "text/html"
Currently the only content I have in the editor pane is:
<html><p>This is a short sentence</p></html>
What I want is the user to be able to select any part of that sentence with their mouse. When they hit a button (boldButton_), it needs to bold the text inside their selection.
I'm not sure how to accomplish this. This is the code I have so far, which is the event handler on the bold button. The best I can do is insert some text wrapped in bold at the start of the paragraph that has selected text, but what i want is to insert bold tags around the selected text only, so the effect is to bold the selection like you would in any word processor.
Thanks in advance.
JEditorPane editArea_;
public void actionPerformed(ActionEvent e) {
// bold button
if (e.getSource() == boldButton_) {
HTMLDocument doc = (HTMLDocument) editArea_.getDocument();
HTMLEditorKit ekit = (HTMLEditorKit) editArea_.getEditorKit();
int selectStart = editArea_.getSelectionStart();
int selectEnd = editArea_.getSelectionEnd();
Element startElem = doc.getParagraphElement(selectStart);
Element endElem = doc.getParagraphElement(selectEnd);
// for now only bold if some text has been selected with the mouse
if (selectStart != selectEnd) {
// 1. text is selected
// toggle bold tags around the text
try {
doc.insertAfterStart(startElem, "<b>WTF</b>");
} catch (BadLocationException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
editArea_.requestFocusInWindow();
}
}
i'm not sure, but you can try this code.
// toggle bold tags around the text
String txt = doc.getSelectedText();
if (selectStart != selectEnd) {
try {
// doc.insertAfterStart(startElem, "<b>WTF</b>");
doc.remove(selectStart, selectEnd-selectStart);
ekit.insertHTML((HTMLDocument) doc.getDocument(), selectStart, "<b>"+txt+"</b>", 0, 0, HTML.Tag.B);
} catch (BadLocationException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}

(JavaFX) How come my ListView is empty even though the string I'm adding to it is not empty?

I have a ListView that can be saved to a text file. The text file is successfully populated but when I try to read from the text file to fill the ListView, nothing appears. Furthermore, to make sure that the text file isn't empty, I print its contents to the console which shows up perfectly. Why aren't the strings appearing in the ListView? Thanks.
if (event.getSource() == accept0) {
stage0.close();
DirectoryChooser chooser1 = new DirectoryChooser();
chooser1.setTitle("Select Folder");
File dir1 = chooser1.showDialog(null);
String line;
if (dir1.isDirectory()) {
try {
BufferedReader br1 = new BufferedReader(new FileReader(dir1.getAbsoluteFile() + "\\ListViewItems.txt"));
if (!br1.ready()) {
br1.close();
throw new IOException();
}
while ((line = br1.readLine()) != null) {
items.getItems().add(line); //adding line from text file to ListView
System.out.println(line);
}
br1.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Declaration and initialization of the ListView and ObservableList
private ObservableList<String> item = FXCollections.observableArrayList();
private ListView<String> items = new ListView<String>(item);

Why my JTable row is not selected at first click?

Why my JTable row is not selected at first click? It is selected every time after first click. What is the problem?
I need to get all the values from the row which is clicked. Here is my code. It works well from second click.
private void tblAccountInfoMouseReleased(java.awt.event.MouseEvent evt) {
try {
DefaultTableModel model = (DefaultTableModel) tblAccountInfo.getModel();
txtUserName.setText(model.getValueAt(tblAccountInfo.getSelectedRow(), 0).toString());
try {
txtPassword.setText(model.getValueAt(tblAccountInfo.getSelectedRow(), 1).toString());
} catch (NullPointerException npe) {
}
try {
txtType.setText(model.getValueAt(tblAccountInfo.getSelectedRow(), 2).toString());
} catch (NullPointerException npe) {
}
try {
txtUrl.setText(model.getValueAt(tblAccountInfo.getSelectedRow(), 3).toString());
} catch (NullPointerException npe) {
}
updateId = tblAccountInfo.getSelectedRow();
btnSave.setEnabled(false);
btnUpdate.setEnabled(true);
btnDelete.setEnabled(true);
} catch (ArrayIndexOutOfBoundsException aiobe) {
aiobe.printStackTrace();
}
}

When I choose item in jList and use getSelectedIndex() it returns -1

I am trying to make a ToDoList , and I create a jButton to remove a Task from the Database ,when i check the index it always gives (-1)
if (jListTasks.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(null, "No task selected!!");
} else {
JOptionPane.showConfirmDialog(null, "Are you sure?!", "Remove task", JOptionPane.YES_NO_OPTION);}
update:
// set DefaultListModel
tasksListModel = new DefaultListModel();
jListTasks.setModel(tasksListModel);
Then I create this method
// to clear and fill list every time method invoked
private void fillTaskList() {
tasksListModel.clear();
try {
resultSet = pstmt.executeQuery();
while (resultSet.next()) {
// System.out.println("xxx");
tasksListModel.addElement("\"" + resultSet.getString("task_name") +
"\"" + " starts at " + resultSet.getString("start_time"));
}
} catch (SQLException ex) {
Logger.getLogger(ToDoFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
and this is the ActionListener of the RemoveButton
jbtnRemoveTask.addActionListener((ActionEvent e) -> {
// to fill the list with latest values in database
sqlQuery = "SELECT * FROM tasks";
try {
pstmt = connection.prepareStatement(sqlQuery);
fillTaskList();
} catch (SQLException ex) {
Logger.getLogger(ToDoFrame.class.getName()).log(Level.SEVERE, null, ex);
}
// to restore the Frame to default size as I change size during the using of application
if (ToDoFrame.this.getSize().width > 515 || ToDoFrame.this.getSize().height > 440) {
// implementation for these two methods comes at the end
decreaseHeight();
decreaseWidth();
}
// System.out.println(jListTasks.getLastVisibleIndex());
// System.out.println(jListTasks.getSelectedIndex());
// this code is always executed even there is item selected
if (jListTasks.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(null, "No task selected!!");
} else {
JOptionPane.showConfirmDialog(null, "Are you sure?!", "Remove task", JOptionPane.YES_NO_OPTION);
try {
// System.out.println(jListTasks.getSelectedValue());
String s = jListTasks.getSelectedValue().toString();
s = s.substring(s.length() - 5);
// System.out.println(s);
// the code for updating database
sqlUpdate = "DELETE FROM tasks WHERE start_time = ?";
pstmt = connection.prepareStatement(sqlUpdate);
pstmt.setString(1, s);
pstmt.executeUpdate();
JOptionPane.showMessageDialog(null, "Task removed successfully!");
sqlQuery = "SELECT * FROM tasks";
pstmt = connection.prepareStatement(sqlQuery);
fillTaskList();
} catch (SQLException ex) {
Logger.getLogger(ToDoFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
// here are the code of decreaseWidth and decreaseHeight methods
private void decreaseWidth() {
for (int i = ToDoFrame.this.getSize().width; i > 510; i -= 10) {
ToDoFrame.this.setSize(i, ToDoFrame.this.getSize().height);
ToDoFrame.this.setLocationRelativeTo(null);
try {
Thread.sleep(20);
} catch (InterruptedException ex) {
Logger.getLogger(ToDoFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private void decreaseHeight() {
for (int i = ToDoFrame.this.getSize().height; i > 435; i -= 10) {
ToDoFrame.this.setSize(ToDoFrame.this.getSize().width, i);
ToDoFrame.this.setLocationRelativeTo(null);
try {
Thread.sleep(20);
} catch (InterruptedException ex) {
Logger.getLogger(ToDoFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Note: the code was working perfectly before making methods to re-size the Frame , when doing the re-sizing directly inside the ActionListener
Thanks for help
It looks like the action listener of your remove button calls the fillTaskList method before retrieving the selected index. The refill of the todo list will clear the selection in the list and the call to jListTasks.getSelectedIndex() will return -1.
I think you only need to update the todo list after removing the selected item.

How to improve the performance of JTextPane when loading large files

I want to load a large file(1MB of plain text) contents using JTextPane. It took nearly two minutes to load a large file. I want to load the large file into JTextPane within seconds. If it possible to improve the performance of the JTextPane. My Open action code is available in openActionPerformed() method. Please check it and give me some suggestions. Thank you.
Constructor code:
public class OpenDemo extends javax.swing.JFrame {
JTextPane textPane;
JScrollPane scrollPane;
int i=0;
public OpenDemo() {
initComponents();
textPane=new JTextPane();
}
OpenActionPerformed() method:
private void openActionPerformed(java.awt.event.ActionEvent evt) {
int offset = 0;
FileDialog fd = new FileDialog(OpenDemo.this, "Select File", FileDialog.LOAD);
fd.setVisible(true);
String title;
String path;
Path filePath = null;
File file;
if (fd.getFile() != null) {
path = fd.getDirectory() + fd.getFile();
file=new File(path);
filePath=file.toPath();
title=fd.getFile();
JInternalFrame internalFrame = new JInternalFrame("",true,true);
i++;
internalFrame.setName("Doc "+i);
internalFrame.setTitle(title);
scrollPane=new JScrollPane(textPane);
internalFrame.add(scrollPane);
tp.add(internalFrame);
myOffsetTextField=new JTextField();
List<String> allLines = null;
try {
allLines = Files.readAllLines(filePath, Charsets.UTF_8);
}
catch (MalformedURLException ex) {
Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex) {
Logger.getLogger(OpenDemo.class.getName()).log(Level.SEVERE, null, ex);
}
try{
offset = Integer.parseInt(myOffsetTextField.getText());
}
catch(NumberFormatException ne){
}
int numberOfLinesToShow = 10000;
int start = Math.min(allLines.size(), offset);
int end = Math.min(allLines.size(), start + numberOfLinesToShow);
List<String> sublist = allLines.subList(start, end);
textPane.setText(Joiner.on('\n').join(sublist));
textPane.setCaretPosition(0);
}
Main method:
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(OpenDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new OpenDemo().setVisible(true);
}
});
}
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem open;
private javax.swing.JTabbedPane tp;
}
For a 1 MB text file it's impossible to take two minutes to load unless it's read from a diskette or alike.
Putting it all into a user interface is a non-sense, nobody can do anything with it. Scrolling using a scroll bar get completely unusable, too. Allow the user to enter a starting offset (in lines), read the file using Files.readLines into a List<String>, and display a few lines only.
Code idea
All non-JDK classes come from Guava.
List<String> allLines = Files.readLines(file, Chatsets.UTF8);
int offset = Integer.parseInt(myOffsetTextField.getText());
int numberOfLinesToShow = 10000;
int start = Math.min(allLines.size(), offset);
int end = Math.min(allLines.size(), start + numberOfLinesToShow);
// a sane-sized list of at most `numberOfLinesToShow` lines
List<String> sublist = allLines.sublist(start, end);
textPane.setText(Joiner.on('\n').join(sublist));

Categories