JTable: update behavior by using the arrow button
Dear Experts,I create the following JTable to act as a calculator.
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.text.NumberFormat;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;
public class CalculatorTable extends JFrame {
//Fields
private final String[] COLUMN_NAMES = {"1", "2", "3"};
private final int[] intArrayFirst = {1, 10, 100, 1000};
private NumberFormat nf = NumberFormat.getNumberInstance();
private TableBalanceCalculator tbc; // extends JPanel
private JPanel pnlX, pnlY;
private JButton btnClear;
private JLabel lblTotal;
private JTextField txtTotal;
private int intTotal;
//Constructors
public CalculatorTable() {
// Set up frame
setTitle("Calculator");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setSize(380, 280);
// Initialize form and set to be visible
initComponents();
setVisible(true);
}// end of constructors
private void initComponents() {
getContentPane().setLayout(new BorderLayout());
pnlY = new JPanel();
pnlY.setLayout(new BoxLayout(pnlY, BoxLayout.Y_AXIS));
pnlX = new JPanel();
pnlX.setLayout(new BoxLayout(pnlX, BoxLayout.X_AXIS));
pnlX.add(Box.createHorizontalStrut(10));
pnlX.setAlignmentX(JFrame.RIGHT_ALIGNMENT);
pnlY.add(Box.createVerticalStrut(15));
pnlY.add(pnlX);
tbc = new TableBalanceCalculator();
pnlX = new JPanel();
pnlX.setLayout(new BoxLayout(pnlX, BoxLayout.X_AXIS));
pnlX.add(Box.createHorizontalStrut(10));
pnlX.add(tbc);
pnlY.add(Box.createVerticalStrut(10));
pnlY.add(pnlX);
lblTotal = new JLabel("Total:");
txtTotal = new JTextField();
txtTotal.setFocusable(false);
txtTotal.setHorizontalAlignment(JTextField.RIGHT);
pnlX = new JPanel();
pnlX.setLayout(new BoxLayout(pnlX, BoxLayout.X_AXIS));
pnlX.add(Box.createHorizontalStrut(140));
pnlX.add(lblTotal);
pnlX.add(Box.createHorizontalStrut(20));
pnlX.add(txtTotal);
pnlX.add(Box.createHorizontalStrut(25));
pnlY.add(Box.createVerticalStrut(10));
pnlY.add(pnlX);
btnClear = new JButton("Clear");
btnClear.setMnemonic(KeyEvent.VK_C);
btnClear.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
tbc.clearTable();
}
});
pnlX = new JPanel();
pnlX.setLayout(new BoxLayout(pnlX, BoxLayout.X_AXIS));
pnlX.add(Box.createHorizontalStrut(60));
pnlX.add(btnClear);
pnlX.add(Box.createHorizontalStrut(15));
pnlY.add(Box.createVerticalStrut(20));
pnlY.add(pnlX);
pnlY.add(Box.createVerticalStrut(20));
getContentPane().add(pnlY);
}
//Class to create tables with one model
private class TableBalanceCalculator extends JPanel {
// Fields
static final long serialVersionUID = 200907131455L; // YYYY MM DD hh mm
private JScrollPane tblScrPn;
private CalculatorJTable tblCalc;
private CalculatorTableModel mdlTableCalc;
// Constructor
private TableBalanceCalculator(){
mdlTableCalc = new CalculatorTableModel(COLUMN_NAMES, intArrayFirst);
mdlTableCalc.addTableModelListener(new TableModelListener() {
public void tableChanged(TableModelEvent tme) {
intTotal = 0;
for (int i = 0; i < intArrayFirst.length; i++) {
intTotal = intTotal + (Integer)(tblCalc.getValueAt(i, 2));
}
txtTotal.setText(nf.format(intTotal));
}
});
tblCalc = new CalculatorJTable(mdlTableCalc);
tblCalc.setPreferredScrollableViewportSize(new Dimension(320, 100));
tblCalc.setRowHeight(25);
tblCalc.setRowSelectionAllowed(false);
tblCalc.setColumnSelectionAllowed(false); // Only allow cell selection
// Set column width
TableColumn col;
for (int i = 0; i < COLUMN_NAMES.length; i++){
col = tblCalc.getColumnModel().getColumn(i);
if (i == 0) col.setPreferredWidth(60);
else if (i==1) {
col.setPreferredWidth(40);
col.setCellRenderer(new DefaultTableCellRenderer() {
static final long serialVersionUID = 201101151629L;
// Override the renderer to format String
public Component getTableCellRendererComponent(
JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column)
{
JLabel jlabRender = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
jlabRender.setHorizontalAlignment(SwingConstants.CENTER);
return jlabRender;
}
});
}
else col.setPreferredWidth(120);
}
// Create the scroll pane and add the table to it.
tblScrPn = new JScrollPane(tblCalc);
// Add the scroll pane to this panel.
add(tblScrPn);
tblCalc.changeSelection(0, 1, false, false); // set initial selection
} // end of constructor
// Methods
CalculatorJTable getTable() {
return tblCalc;
}
void clearTable() {
for (int i = 0; i < intArrayFirst.length; i++) {
tblCalc.setValueAt(null, i, 1);
tblCalc.changeSelection(0, 1, false, false); // return to the first cell in the column
tblCalc.requestFocusInWindow(); // otherwise the focus is still in btnClear
}
}
} // end of class Table Cash Inventory
//Special JTable class to override changeSelection
private class CalculatorJTable extends JTable {
// Fields
static final long serialVersionUID = 201111121009L;
// Constructor
private CalculatorJTable(CalculatorTableModel dm) {
super(dm);
}
// Overriding to prevent selection on some columns
public void changeSelection(int rowIndex, int columnIndex, boolean toggle, boolean extend) {
super.changeSelection(rowIndex, 1, toggle, extend); // only column 2 is editable.
}
}
public class CalculatorTableModel extends AbstractTableModel {
// Fields
static final long serialVersionUID = 201101111111L; // YYYY MM DD hh mm
private final int MAX_ROWS;
private String[] columnNames;
private Object[][] objData;
// Constructor
CalculatorTableModel(String[] astrC, int[] aintBNoteType) {
MAX_ROWS = aintBNoteType.length;
columnNames = astrC;
objData = new Object[MAX_ROWS][columnNames.length];
for (int i = 0; i < MAX_ROWS; i++) {
objData[0] = aintBNoteType[i];
}
}
// Three methods that must be implemented
public int getRowCount(){
return MAX_ROWS; // Set table to have maximum allowable items in a transaction
}
public int getColumnCount(){
return columnNames.length;
}
public Object getValueAt(int row, int col){
if (col == 2) { // the column is summarized to obtain a sum in a JTextField
if ((objData[row][col] == null) || (objData[row][col].toString().length() == 0)) return 0;
else return objData[row][col];
} else return objData[row][col];
}
// Method to set column name
public String getColumnName(int col){
return columnNames[col];
}
// Override setValueAt to update objData, because column 1 is editable
public void setValueAt(Object value, int row, int col) {
if (col == 1) {
objData[row][col] = value;
objData[row][2] = (value != null ? (Short)value * (Integer)objData[row][0] : null);
}
fireTableCellUpdated(row, col);
}
// Wihtout the following method no cell is editable
public boolean isCellEditable(int row, int col) {
if (col == 1) return true;
else return false;
}
public Class<?> getColumnClass(int c) {
if (c==1) return Short.class;
else return Integer.class;
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new CalculatorTable();
}
});
}
}
I don't have any problem when I use <Enter> key to confirm my input in Column 2. However, if I use <ARROW DOWN> key, it will not work perfectly in the last row. When I reach the bottom row, press a number and then <ARROW DOWN> key, only the total sum is updated, but the value in Column 3 remains unchanged.
My questions are:
1. What is the best explanation of this behavior?
2. What is the best approach to solve the problem? I have thought of disabling the arrow key, but the problem also occurs on the first row with <ARROW UP> key.
Thank you for your help.
Patrick
your model should trigger rowsUpdated (instead of cellUpdated) as the other cell values are changed so
Basically, it's an accident (due to the internal implementation of paint on updates) it seems to work in other rows
See you soon
Jeanette
Tags: Java
Similar Questions
-
I have a MacBook Pro and update to the latest iOS and iTunes. I can't scroll in my podcasts to choose which episodes to synchronize. I can only use the arrow keys to navigate, but then while he list of podcasts on the left, it moves also down from the bar on the list of episodes, so by the time I spend the first 7 or 8 I can't see the episodes more to choose which to add/remove.
Same here, very frustrating.
I found if you go in your library > Podcast, then control click on the podcast, you can select Add to the device, which works, but is in no way acceptable.
-
After my upgrade that Mac is not closed by using the drop-down menu option, it also seems to crash the finder. Finder raises with force quit. I can only shut it down using the power button. Is this a bug/problem of a part of the El Capitan?
Wacom tablet software is known to cause this problem. Options:
Uninstalling the Wacom software
Completely and remove items from connection
The Wacom driver update
-
for example, if I searched word on google, then clicked on a page of results, then inside this page, I entered a link, etc if I wanted to 'go back' directly to the instance of google search I could click on the arrow button and I would be able to choose this exact moment instead of click the 'back' several times until I reached the desired past page
The arrow to open the history tab of the previous buttons and following was removed in Firefox 4 and later versions.
Use one of the following methods to open the tab history list:
- Right-click on the back or next button
- Press and hold the left button of the mouse on the active back or forward button until the list opens
You can watch this extension:
- Backward forward history Dropdown: https://addons.mozilla.org/firefox/addon/backforedrop/
-
Even within this field of text that I type, everything is normal, but a back using the arrow keys (and then spacing also forward using the arrow keys as I go back to typing) deletes chunks of the text. Once I have started typing again in this area, the components are deleted to normal. This effect can be captured in a screenshot. After inspection, it seems to be a second invisible cursor, a character to the right of the cursor visible. So when the back arrow back, the invisible cursor trails that visible, destroying the text behind. When the spacing before using the arrow keys, the text gets fact sinking in front of the cursor visible.
Try turning off hardware acceleration.
- Tools > Options > advanced > General > Browsing: "use hardware acceleration when available.
If disable hardware acceleration works then check if there is an update available for your graphics display driver.
-
Can you have SMU 1062 q turn on without using the power button
I use a q SMU-1062 for a test project that will take place inside a protective case. The power button on the chassis will be covered by a plate on the protective case that make it boring and difficult to switch on using the power button on the chassis. The chassis will be plugged into a power strip of travel - lite which is mounted in the case. Is it possible that I can have the power to frame on when I turn on the power strip?
I found another route. In the controller BIOS, I changed the parameters of loss of AC power to TURN on after that AC is returned. This allows me to use the power strip in my configuration to control the electric network distributed to the controller. The following steps will describe how I got this.
- Power of the SMU-8115 controller.
- A message will appear on your screen, press
to enter SETUP
- Select 'Remove' (quickly, because you don't have a lot of time before the window disappears and the controller continues to load normally.)
- This will open the main Menu of the BIOS
- Select the Advanced tab (use the arrow keys to highlight the selections and the different tabs, select a setting change with 'enter'
- Select > Configuration power and rest
- Change the configuration to power on when power is restored.
The controller can be normally close by using the start menu, and "shut down".
Start button / stop of the chassis is still capable of turning the power on to the controller, but now when I shut off the AC power strip and then return power, get the controller chassis.
-
MY PAGES HAVE BEEN VERY WELL UNTIL I DOWNLOADED SOMETHING, I DON'T KNOW EXACTLY. I THOUGHT I TRY TO DELETE WHAT I DOWNLOADED ARRIVE TO WHERE I WAS, BUT I DON'T THINK IT WORKED OR I DELETE ANYTHING! SO I'M GOING TO STILL USE THE ARROW LEFT AND ARROW RIGHT TO VIEW ALL PAGES. I WENT TO CONTROL PANEL, DISPLAY, SETTINGS, WENT TO A HIGH NUMBER TO THE PIXEL NUMBER LOW, CE WHICH WAS THE ONLY SOLUTION POSSIBLE, AND ALL GROW. SO I PUT IT BACK TO THE LOT WHERE HE WAS! DON'T KNOW WHAT TO DO, SO HERE I AM ASKING FOR HELP! Thank you!!! MY email * address email is removed from the privacy *.
First remove everything you have installed, check if it works.
In case of failure and then update the display on the computer drivers
-
How to use the "back" button to return to the new page tab in FF15
In FF14 I could
(1) open the new tab and see the new tabs with thumbnails of page 9 page.
2) click on a thumbnail and go to this page.
(3) click on the back of FF button, who took me to the new tab page so I could click on some other thumbnail.
In FF15 which doesn't seem to work. In step 3 above, the previous button is not active/active and so I can easily go back to the new page tab. How to get back in a simple way?
No, you can no longer use the previous button back to the topic: newtab page if you have opened a page by clicking on one of the slots on this page.
You need to close the tab and open a new tab to get this page or set as the home page and click on the Home button.
-
recently, my mac started hanging. the screen freezes and I have to use the power button to turn it off
Run this test and post the results here.
-
When I use the new button tab in the tab tool bar, it opens the Yahoo! search engine. I would like to change it to open my home page, or a search engine different. Is it possible to do it and how?
Thanks for any help!
I think that is changed by an extension. If you run Firefox in Mode safe search engine comes up when you open a new tab? http://support.Mozilla.com/en-us/KB/safe+mode
-
Whenever I click in a window to scroll through my arrows is put a cursor in the window and scrolling out of it, instead of scrolling the entire page using the arrow key it scrolls by the location of the cursor within the window as a word document.
Press F7 to disable the keyboard navigation.
-
I went to record a live concert, and I need to use a single interface to record the members of the group with microphones near directly to a computer and another interface running for my model of Macbook 4.1 end of 2007, to get signals from the map of the House.
When I plug my converter USB 3.0 AD / DA in my Macbook 4,1 - the computer sends immediately a window indicating to me to "reboot" the computer using the power button / stop. Ideas or comments about why this happens?
I read on this forum that USB ports should work with retroactive effect, or accept USB 3.0 devices, but just use a speed 2.0?
Thank you.
It could be that it is a requirement of your converter AD / DA she needs to be present at a properly accessible to the OS X when startup sequence it is plugged into a USB2 port.
Its also interesting to note that, well that peripheral USB3 can be plugged into the USB2 ports... it could be that your device may not work properly unless it is used with a port USB3... for reasons of bandwidth or even certain types of power supply.
But to be sure...
Which converter AD / DA are you using?
-
How to remove the support contact at screenshot using the "home" button
guys, please help, how to remove the support contact at screenshot using the "home" button? I use 6 s ios 9.2, but when I take screenshot with the menu help key, the help key disappear on my photo, but the problem is, I want to take screenshot with my home button, please help... Thank you
What turned the problem into a screen with the home button? Quickly, you press the power off button and home together and release - if the sounds are enabled - you should hear the camera shutter sound and have the capture in your app screen shots. The help key is not displayed
-
HP b209a printer range will not connect to router comcast using the WPS button
HP b209a printer range will not connect to router comcast using the WPS button. I try to use a new Comcast router (technicolor TC8305C). When I try to connect the printer times out and says that no connections are when I check for wireless connections. Yet, when I print the network configuration page, the SSID for the new router is at the top of the list. I reinstalled the software by the support of Comcast, but it did not help. I'm ideas please help!
Thank you
Never use WPS to connect. If done it should be disabled in the router for security reasons. Connect manually via the SSID and password following the instructions in the manual.
-
When I have one on the internet and you want to scroll up and down, I use the arrow keys or the scroll bar, but the screen is moving slowly in the kind of a stall model.
Any suggestions?
Hello
- This happens only on Internet Explorer?
You can refer to the following steps:
Step 1:
Verify that if the problem exists in Mode safe mode with networking, if the computer works as expected in mode safe, then we can solve the problem in the clean boot state.
a. refer to the article below for the procedure safe mode in Windows XP
A description of the options to start in Windows XP Mode
http://support.Microsoft.com/kb/315222
Step 2:
b. you need to perform a clean boot to find the program that is causing and then disable or remove.
How to configure Windows XP to start in a "clean boot" State
http://support.Microsoft.com/kb/310353/en-us
Note: When you are finished troubleshooting, follow the steps as explained in the article to reset the computer to start as usual.
Maybe you are looking for
-
Hello guys,. I am again facing the same problem with the latest version of Skype, my webcam is not found... I feel already frustrated about this problem that cannot be solved once forever. I m on Windows 7 Ultimate 64-bit. Thank you for the support,
-
Image of XP SP3 not extending the full disk correctly or not displayed correctly.
I use HP 7600 P4 2 GB, 40 GB HD PCs I have an image (XP, SP3) which included the "ExtendOemPartition = 1" command in the sysprep file. On some installs the image extends to the full 40 GB drive, on others it isn't. Readers who do not extend correctly
-
Multiple, partially printed pages on photosmart 2575 since coming to windows 8
Whenever I have print something on my new computer laptop (which is Windows 8, my old laptop was running windows vista), it prints several unfinished copies before you finally print a complete copy. To try to solve this problem, I have: Rebooted prin
-
How can I keep from being hacked?
This is the 3rd time I've been hacked. I scanned for virus and change password each time. What else can I do to avoid being hacked? I tried not opening not send people I know not if it's just a link. I never open emails from someone I don't know. Tha
-
OBIEE 11 g: export to the question of the full dashboard
HelloMy dashboard contains four pages and each page contains a single report.If I export to any dashboard and then receive 25 first lines of each report only.How to get all the lines of each report.Note: Each report contains about 2000 lines. That's