So I have been trying to disable/enable a jPanel within a jTabbedPane (on Netbeans) using a simple boolean and the boolean always gets stuck on false. The disabling/enabling of the jPanel within the jTabbedPane is triggered by the click of a button. Here is an excerpt of my code:
package programming.club;
/**
*
* #author RandomGuy
*/
public class GranadaProgrammingClubUI extends javax.swing.JFrame {
public static boolean allowNavigation = true;
/**
* Creates new form ProgrammingClubUI
*/
public ProgrammingClubUI() {
initComponents();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if (allowNavigation == false) {
jTabbedPane1.setEnabledAt(0, true);
allowNavigation = true;
}
if (allowNavigation == true) {
jTabbedPane1.setEnabledAt(0, false);
allowNavigation = false;
}
System.out.println(allowNavigation);
}
I put the System.out.println(allowNavigation); just to check what the value of allowNavigation was, and every time I click the button, the value just stays as false, but it should be switching, and changing the status of the jPanel, enabled or disabled! (I think) I really can't figure out what's wrong here. Thank you for your time.
i think problem is
if (allowNavigation == false) {
jTabbedPane1.setEnabledAt(0, true);
allowNavigation = true;
}
if (allowNavigation == true) {
jTabbedPane1.setEnabledAt(0, false);
allowNavigation = false;
}
you should use
if (allowNavigation == false) {
jTabbedPane1.setEnabledAt(0, true);
allowNavigation = true;
}
else if (allowNavigation == true) {
jTabbedPane1.setEnabledAt(0, false);
allowNavigation = false;
}
because if allownavigation false it will go to first if and make it true and then go to second if and make it false
and also good boolean check is
if (!allowNavigation) {
jTabbedPane1.setEnabledAt(0, true);
allowNavigation = true;
}
else if (allowNavigation) {
jTabbedPane1.setEnabledAt(0, false);
allowNavigation = false;
}
Related
I am trying to have one Button for pause and resume game background music on Jpanel form, what I have done below is just resets/repeats the sound from the beginning rather than pause and play. and I have look at few other examples here and tried to implement, same thing happened. or just paused it. any idea what to add to it to make it function? thanks
Boolean isPaused = false;
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
if (isPaused = false ) {
Game.gameMusic.pause();
isPaused = true;
}
else {
Game.gameMusic.resume();
isPaused = true;
}
}
if (isPaused = false ) { is an assignment, not an evaluation, you should be using ==
that will become
Boolean isPaused = false;
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {
if (!isPaused ) {
Game.gameMusic.pause();
jButton6.setText("resume");
}
else {
Game.gameMusic.resume();
jButton6.setText("pause");
}
isPaused = !isPaused;
}
I am trying to write a Jython script in Fiji (ImageJ) that allows a user to place a point and upon placing the point adds it to the region of interest manager. This I can do but I also wish the user to be able to drag and drop already placed points without adding a new entry in the region of interest manager. Basically I want to be able to call mouseClicked and mouseDragged independently from each other whereas currently dragging the mouse will still activate a mouseClicked event. (I didn't know whether to put down Java as one of the tags but I feel it's closely related enough, I apologize if wrong).
Cheers!
class ML(MouseAdapter):
def mouseClicked(self, event):
canvas = event.getSource()
imp = canvas.getImage()
print click
roi.runCommand("Add")
roi.runCommand("UseNames", "true")
class ML2(MouseAdapter):
def mouseDragged(self, event):
canvas = event.getSource()
imp = canvas.getImage()
print "move!"
roi = ij.plugin.frame.RoiManager()
listener = ML()
listener2 = ML2()
for imp in map(WindowManager.getImage, WindowManager.getIDList()):
win = imp.getWindow()
if win is None:
continue
win.getCanvas().addMouseListener(listener)
win.getCanvas().addMouseMotionListener(listener2)
public void mouseClicked(MouseEvent arg0) {
}
/**
* handles mouse pressed event
*/
public void mousePressed(MouseEvent arg0)
{
// if filling we shouldn't add anything
if(b_Filling == true)
return;
// if dragging we shouldn't add anything
if(isDragging == true)
return;
// handles first vertex for each polygon
if(i_ThreeVertices == 0)
{
p_Start = arg0.getPoint();
p_End = new Point();
p_FirstVertex = new Point(p_Start);
}
else
{
// not the first vertex
p_Start = new Point(p_End);
p_End = arg0.getPoint();
}
// adds the vertex
b_Drawing = true;
addAPoint();
b_Drawing = false;
b_repaintFlag = true;
// repaints
this.repaint();
}
/**
* handles mouse released event
*/
public void mouseReleased(MouseEvent arg0)
{
// if filling we shouldn't add a vertex.
if(b_Filling == true)
return;
if(b_FirstVertexInPolygon == true && isDragging == false)
{
// unlocks first vertex state
b_FirstVertexInPolygon = false;
return;
}
// save previous vertex and add current if mouse is dragged
// and more than non vertices
if(isDragging == true && i_ThreeVertices != 0)
{
p_Start = new Point(p_End);
p_End = arg0.getPoint();
isDragging = false;
b_Drawing = true;
// adds a vertex
addAPoint();
b_Drawing = false;
}
else
p_End = arg0.getPoint();
b_repaintFlag = true;
// repaint
this.repaint();
}
/**
* handles mouse dragged event
*/
public void mouseDragged(MouseEvent arg0)
{
// repaints if not filling
if(b_Filling == true)
return;
p_End = arg0.getPoint();
isDragging = true;
b_repaintFlag = true;
this.repaint();
}
/**
* handles mouse moved event
*/
public void mouseMoved(MouseEvent arg0)
{
// if not filling, and we have at least one vertex
// and not dragging mouse, then repaint.
if(b_Filling == true)
return;
if(i_ThreeVertices == 0)
return;
if(isDragging == true)
return;
p_End = arg0.getPoint();
b_repaintFlag = true;
this.repaint();
}
public void mouseEntered(MouseEvent arg0){
}
public void mouseExited(MouseEvent arg0){
}
My task is again to modify my BMI Calculator. My previous code was working correctly but this time, I have added an ItemListener for my radio buttons. I need to store and save the state of the radio buttons currently selected, and then according to their selected state, the Calculate button should perform its calculation in Metric or Imperial. When I run the code, there are no syntax errors. Instead there is a logical error since nothing is being done when I press calculate button after entering weight and height and selecting my radio buttons.
I have created a Boolean variables here to determine what has been selected:
private Boolean selected = false; //selected is for metric and imperial
private Boolean Gselected = false; // Gselected is for gender
These are outside, and above my constructor and act as global variable.
I think my problem lies here, when i use them here in a inner private class:
private class bmiItemListener implements ItemListener
{
public void itemStateChanged(ItemEvent event)
{
if (metric.isSelected() && male.isSelected() ) {
selected = true;
Gselected = true;
}
else if (imperial.isSelected() && male.isSelected()) {
selected = false;
Gselected = true;
}
if (metric.isSelected() && female.isSelected() ) {
selected = true;
Gselected = false;
}
else if (imperial.isSelected() && female.isSelected()) {
selected = false;
Gselected = flase;
}
}
This is my action listener for my calculate button:
private class bmiActionListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
String heightText, weightText, bmiTotal;
double heightVal, weightVal, bmi;
heightText = height.getText();
weightText = weight.getText();
heightVal = Double.parseDouble (heightText) ;
weightVal = Double.parseDouble (weightText) ;
if(selected == flase && Gselected == false)
{
bmi=(weightVal*703)/(heightVal*heightVal);
bmiTotal = String.valueOf(bmi);
resultLabel.setText(bmi ) ;
}
else if(selected == true && Gselected == false)
{
bmi=weightVal/(heightVal*heightVal)*10000;
bmiTotal = String.valueOf(bmi);
resultLabel.setText(bmi ) ;
}
else if(selected == false && Gselected == true)
{
bmi=(weightVal*703)/(heightVal*heightVal);
bmiTotal = String.valueOf(bmi);
resultLabel.setText(bmi ) ;
}
else if(selected == false && Gselected == false)
{
bmi=(weightVal*703)/(heightVal*heightVal);
bmiTotal = String.valueOf(bmi);
resultLabel.setText(bmi ) ;
}
}
}
I'm not very familiar with ItemListener, but I would recommend using ActionListener with your radio buttons.
Exmaple:
JRadioButton male = new JRadioButton("Male");
JRadioButton female = new JRadioButton("Female");
male.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
gselected = true;
female.setSelected(false); //if you can only select male or female
}
});
female.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
gselected = true;
male.setSelected(false); //if you can only select male or female
}
});
EDIT: haven't tested this code or coded for all cases of button presses. just for a general idea
I have made a custom BasicScrollBarUI.
I have replaced the incrButton / decrButton by JLabels.
Therefore i had to override the InstallListeners(), to add the Listener to the incr/decrLabel instead of the JButtons.
//TODO
protected void installListeners() {
trackListener = createTrackListener();
buttonListenerCustom = createArrowButtonListenerCustom();
modelListener = createModelListener();
propertyChangeListener = createPropertyChangeListener();
scrollbar.addMouseListener(trackListener);
scrollbar.addMouseMotionListener(trackListener);
scrollbar.getModel().addChangeListener(modelListener);
scrollbar.addPropertyChangeListener(propertyChangeListener);
// scrollbar.addFocusListener(getHandler());
if (incrLabel != null) {
incrLabel.addMouseListener(buttonListenerCustom);
System.out.println("OK gemacht");
}
if (decrLabel != null) {
decrLabel.addMouseListener(buttonListenerCustom);
}
scrollListener = createScrollListener();
scrollTimer = new Timer(scrollSpeedThrottle, scrollListener);
scrollTimer.setInitialDelay(300); // default InitialDelay?
}
Therefore i had to override the ArrowButtonListener, to react on the Labels.
protected class ArrowButtonListenerCustom extends MouseAdapter {
boolean handledEvent;
public void mousePressed(MouseEvent e) {
if (!scrollbar.isEnabled()) {
return;
}
// not an unmodified left mouse button
// if(e.getModifiers() != InputEvent.BUTTON1_MASK) {return; }
if (!SwingUtilities.isLeftMouseButton(e)) {
return;
}
int direction;
if (e.getSource() == incrLabel) {
direction = 1;
incrLabel.setIcon(new ImageIcon(increaseButtonPressedImage));
} else {
direction = -1;
decrLabel.setIcon(new ImageIcon(decreaseButtonPressedImage));
}
scrollByUnit(direction);
scrollTimer.stop();
scrollListener.setDirection(direction);
scrollListener.setScrollByBlock(false);
scrollTimer.start();
handledEvent = true;
if (!scrollbar.hasFocus() && scrollbar.isRequestFocusEnabled()) {
scrollbar.requestFocus();
}
}
public void mouseReleased(MouseEvent e) {
scrollTimer.stop();
handledEvent = false;
scrollbar.setValueIsAdjusting(false);
incrLabel.setIcon(new ImageIcon(increaseButtonImage));
decrLabel.setIcon(new ImageIcon(decreaseButtonImage));
}
}
Of course createArrowButtonListenerCustom() returns a new instance of ArrowButtonListenerCustom.
Now my Problem:
When I click on the incr/decrLabel, the List scrolls correctly, but the thumb of the ScrollBar doesn't move (or better: the Thumb isn't repainted. If I move the Mouse over the thumb, it gets repainted on the right place). I have the same problem, when I scroll with the MouseWheel.
I don't understand, why this doesn't work.
Thanks for your help!
If you have JTable set with table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION) and then you click drag on a row that is not already selected, it starts selecting multiple rows. We don't want that behavior. We want it so if you click on a node, even if it's not already selected, it will start dragging it.
We do need the multi select mode on, so setting it to single select (which does result in the behavior we want) is not an option.
Update: At this point, it appears it will require some type of ugly hack since the logic is in a private method BasicTableUI$Handler.canStartDrag
I found one possible solution. You bracket the mouse listeners so you can lie to the call to isCellSelected during the canStartDrag call.
Subclass JTable (or in my case, JXTreeTable). In the constructor call this:
private void setupSelectionDragHack()
{
// Bracket the other mouse listeners so we may inject our lie
final MouseListener[] ls = getMouseListeners();
for (final MouseListener l : ls)
{
removeMouseListener(l);
}
addMouseListener(new MouseAdapter()
{
#Override
public void mousePressed(final MouseEvent e)
{
// NOTE: it might not be necessary to check the row, but... I figure it's safer maybe?
mousingRow = rowAtPoint(e.getPoint());
mousingInProgress = true;
}
});
for (final MouseListener l : ls)
{
addMouseListener(l);
}
addMouseListener(new MouseAdapter()
{
#Override
public void mousePressed(final MouseEvent e)
{
mousingInProgress = false;
}
});
}
And then you'll need this:
#Override
public boolean isCellSelected(final int row, final int column)
{
if (mousingInProgress && row == mousingRow)
{
// Only lie to the canStartDrag caller. We tell the truth to everyone else.
final StackTraceElement[] elms = Thread.currentThread().getStackTrace();
for (int i = 0; i < 3; i++)
{
if (elms[i].getMethodName().equals("canStartDrag"))
{
return mousingInProgress;
}
}
}
return super.isCellSelected(row, column);
}
It's an ugly hack in many ways, but... for now it seems to work.
Unfortunately none of the other answers worked for me.
So I made my own hack/fix for the problem (I'm posting it here for others with the same problem):
public class SFixTable extends JTable {
private static final long serialVersionUID = 1082882838948078289L;
boolean pressed = false;
int currSRow = -100;
public SFixTable(TableModel dm) {
super(dm);
}
public SFixTable() {
super();
}
public SFixTable(Vector<?> rowData, Vector<?> columnNames) {
super(rowData, columnNames);
}
#Override
protected void processMouseEvent(MouseEvent e) {
int row = rowAtPoint(e.getPoint());
int col = columnAtPoint(e.getPoint());
if (SwingUtilities.isLeftMouseButton(e) && !e.isShiftDown() && !e.isControlDown()) {
boolean isDragRelease = (e.getID() == MouseEvent.MOUSE_RELEASED) && row != currSRow;
boolean isStartClick = (e.getID() == MouseEvent.MOUSE_PRESSED);
if (row >= 0 && col >= 0) {
if (isStartClick) {
super.changeSelection(row, col, false, false);
} else if (isDragRelease) {
super.changeSelection(currSRow, col, false, false);
}
}
pressed = (e.getID() == MouseEvent.MOUSE_PRESSED);
if (pressed) {
currSRow = row;
} else {
currSRow = -100;
}
}
super.processMouseEvent(e);
}
#Override
public boolean isCellSelected(int row, int col) {
return (pressed)? (row == currSRow) : super.isCellSelected(row, col);
}
}
It's a bug:
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6349223
and as you already assumed, it requires some ugly hack. Here's one (not from me, but from a user Aephyr on old sun forums which didn't survive the migration to OTN)
table = new JTable() {
// fix for http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6349223
// requirement is the option to turn off drag-selection if dragEnabled
// fix posted in sun dev forum by Aephyr
// http://forums.sun.com/thread.jspa?threadID=5436355&tstart=0
private boolean pressed;
#Override
protected void processMouseEvent(MouseEvent e) {
pressed = e.getID() == MouseEvent.MOUSE_PRESSED;
if (pressed && !e.isShiftDown() && !e.isControlDown())
clearSelection();
try {
super.processMouseEvent(e);
} finally {
pressed = false;
}
}
#Override
public boolean isCellSelected(int row, int col) {
return pressed ? true : super.isCellSelected(row, col);
}
};
Similar to kleopatra's answer, but this seems to handle a few issues with the previous one -- you can control-click to both add and remove items from a multiple selection, and you can successfully drag a multi-select group. I've tested this only with an ETable/Outline from NetBeans, but should work with a regular JTable.
table = new JTable() {
private boolean inPress = false;
#Override protected void processMouseEvent(MouseEvent e) {
inPress = e.getID() == MouseEvent.MOUSE_PRESSED && e.getButton() == MouseEvent.BUTTON1 && !e.isShiftDown() && !e.isControlDown();
try {
super.processMouseEvent(e);
} finally {
inPress = false;
}
}
#Override public boolean isCellSelected(int row, int col) {
boolean selected = super.isCellSelected(row, col);
if (inPress) {
if (!selected)
clearSelection();
return true;
}
return selected;
}
};
If what you are looking for is to drag an unselected row in a single selection JTable, setting the table's selection model to SINGLE_SELECTION mode is not enough, you also have to set the column model's selection mode.
JTable table = new JTable();
table.getSelectionModel()
.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.getColumnModel().getSelectionModel()
.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);