Next and Previous Buttons Displaying Charts Malfunction - java

I am trying to step through a ArrayList<JPanel> which contains ChartPanels. The Next button correctly steps through the charts as expected, but when I click the Previous button nothing happens. I feel like my logic may be convoluted. Thanks!
Note: panelCombination is a JPanel.
Code for the buttons:
public static int advance = 0;
public static ArrayList<JPanel> chartList = new ArrayList<>();
private void NextMouseClicked(java.awt.event.MouseEvent evt) {
panelCombination.removeAll();
panelCombination.add(chartList.get(advance));
panelCombination.validate();
if (advance < chartList.size()-1) {
advance++;
}
}
private void PreviousMouseClicked(java.awt.event.MouseEvent evt) {
if (advance > 0) {
advance--;
}
panelCombination.removeAll();
panelCombination.add(chartList.get(advance));
panelCombination.validate();
}

Use a CardLayout to change views, instead of trying to remove and add panels. What you're trying to do can easily be accomplished by calling the next() and previous() methods of the CardLayout. All you really need to do is set the layout of your panelCombination to CardLayout, add all you panels to the panelCombination and use those methods
CardLayout layout = new CardLayout();
panelCombination.setLayout(layout);
// add all panels.
....
private void PreviousMouseClicked(java.awt.event.MouseEvent evt) {
layout.previous(panelCombination);
See more at How to Use CardLayout
Also from the looks of you method signatures, it looks like you are using NetBeans GUI Builder. You can see How to Use CardLayout with Netbeans GUI Builder

In case anyone else has this issue in the future: the code that I used after reading through the javadoc and links peeskillet provided:
public class ResultsFrame extends javax.swing.JFrame {
public static CardLayout switchPanels;
/**
* Creates new form ResultsFrame
*/
public ResultsFrame() {
initComponents();
switchPanels = new CardLayout();
panelCombination.setLayout(switchPanels);
getPDDGraph();
//getProfileGraph();
}
private void NextMouseClicked(java.awt.event.MouseEvent evt){
switchPanels.next(panelCombination);
}
private void PreviousMouseClicked(java.awt.event.MouseEvent evt) {
switchPanels.previous(panelCombination);
}
public static void getPDDGraph() {
.....
JFreeChart chart = new JFreeChart(xyplot);
ChartPanel chartPanel = new ChartPanel(chart);
panelCombination.add(chartPanel);
}
Thanks again, it was much easier than what I was doing before and more condensed!

Related

How to update values of a JFrame main after using a JDialog of Java Swing?

I have a main window called MainFrame which is a jForm to which I update the data depending on a timer, but the problem is that I cannot update the data in the same MainFrame after using the jdialog, since I end up creating another duplicate window, but with the data changed, one with the original timer and the other with the new timer, I know that I can close the first window with dispose() and then keep the second, but I would like to avoid changing windows so much
the code with which I create another window when pressing the jDialog button is the following
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
String textoFieldTimer = jTextField1.getText();
int timeUserConfig = Integer.parseInt(textoFieldTimer);
Timer timeDefault = new Timer(timeUserConfig, null);
TokenAccess token = new TokenAccess();
token.access_code = code;
MainFrame mainFrame = new MainFrame(token);
mainFrame.setVisible(true);
mainFrame.timeDefault.stop();
mainFrame.timeDefault = timeDefault;
mainFrame.setUpdateTime(timeUserConfig);
this.dispose();
}//GEN-LAST:event_jButton1ActionPerformed
Is there any alternative to update the window? something like mainFrame.update(); or maybe send the value of the jTextField from the jDialog to mainFrame? since the previous code creates another MainFrame for me.
Method main setLabel and Timer.start/stop
public void setUpdateTime(int timeUserConfig) {
this.timeUserConfig = timeUserConfig;
if (timeUserConfig == 0) {
timeDefault.start();
timeDefault.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
setLabelText();
String timeUserConfigStr = Integer.toString(timeDefaultInt);
tiempoActualizado.setText("Tiempo de Actualizado: " + timeUserConfigStr+"ms");
}
});
} else {
timeDefault.stop();
timeDefault = new Timer(timeUserConfig, null);
timeDefault.start();
timeDefault.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
setLabelText();
String timeUserConfigStr = Integer.toString(timeUserConfig);
tiempoActualizado.setText("Tiempo de Actualizado: " + timeUserConfigStr+"ms");
}
});
}
}
setLabelText is a method set of label
public void setLabelText() {
String humedadStr = String.valueOf(humedad);
String temperaturaStr = String.valueOf(temperatura);
String presionStr = String.valueOf(co2);
temporalHum.setText(humedadStr);
temporalTemperatura.setText(temperaturaStr);
temporalPresion.setText(presionStr);
}
Any help would be appreciated.
Thanks for the update, and I found another solution without using an OptionPane from this question: programmatically close a JPanel which is displayed in JDialog.
I cannot replicate your codings
Start with the MainFrame, assuming you opened the JDialog by clicking on a button and wants to setText() to label lbSomething:
private void btInputActionPerformed(java.awt.event.ActionEvent evt) {
// Open new JDialog when button is clicked
NewJDialog dialog = new NewJDialog(new javax.swing.JFrame, true);
dialog.setVisible(true);
// Get user input from JDialog
String temp = dialog.getInput();
if (temp != null) {
/*
* Perform jButton1ActionPerformed() content here
* Including timeUserConfig, timeDefault and setUpdateTime() here
* so that you don't have to access mainFrame in the JDialog.
*/
lbSomething.setText(temp);
}
}
Then about the JDialog (with simple input detection):
public class NewJDialog extends javax.swing.JDialog {
// Set the variable as class variable
private String textTOFieldTimer;
public NewJDialog(java.awt.Frame parent, boolean modal) {
// default contents
}
#SupressWarinings("unchecked")
private void initComponents() {
// default contents
}
private void btSaveAction Performed(java.awt.event.ActionEvent evt) {
// Check if input correct and whether to disable JDialog
if (tfInput.getText.length() != 0) {
input = tfInput.getText();
// Connect to the whole JDialog by getWindowAncestor()
Window window = SwingUtilities.getWindowAncestor(NewJDialog.this);
// Just setVisible(false) instead of dispose()
window.setVisible(false);
} else {
JOptionPane.showMessageDialog(this, "Wrong Input");
}
}
public String getInput() {
return textToFieldTimer;
}
// default variables declarations
}
Hope this answer helps you well.
Would be better if you displayed the source code, but a simple solution to update values to an existing JFrame is by using setText() and getText().
For example:
String input = JOptionPane.showInputDialog(this, "Nuevo valor");
lbPresionActual.setText(input);
If you created a self-defined JDialog, it is about to transfer the input value when closing the JDialog, and that could be a different question.

Calling a JFrame method from another JFrame on Button Click

I searched on stack overflow for the similar answers for my question, but neither of them helped me.
So my problem is the following:
I have a main JFrame called Main_Window, on which I have a JTable and a JButton. After clicking the Button another JFrame (Update_Window) opens from Which I can update the table. The Update_Window JFrame has two TextFields and a SUBMITButton.
Briefly, I want to update my JTable in the Main_Window from the Update_Window JFrame. After I type something in the TextFields and Submit with the Button, the data should appear in the Main_Window's JTable, but it is not working.
This is my Main_Window JFrame:
private void updateBtnActionPerformed(java.awt.event.ActionEvent evt) {
Update_Window newWindow = new Update_Window();
newWindow.setVisible(true);
newWindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
public void putDataIntoTable(Integer data, int row, int col) {
jTable1.setValueAt(data,row,col);
}
This is my Update_Window JFrame:
private void submitBtnActionPerformed(java.awt.event.ActionEvent evt) {
quantity = Integer.parseInt(quantityTextField.getText());
price = Integer.parseInt(priceTextField.getText());
Main_Window mw = new Main_Window();
mw.putDataIntoTable(price,3,2);
}
I think my problem is here Main_Window mw = new Main_Window();, because this creates a new Instance and it doesn't add the data to the correct window, or something like that.
Yes, you are right. The line Main_Window mw = new Main_Window(); is definitely wrong.
Better solution is:
public class UpdateWindow extends JFrame {
private final MainWindow mainWindow;
public UpdateWindow(MainWindow mainWin) {
mainWindow = mainWin;
}
private void submitBtnActionPerformed(java.awt.event.ActionEvent evt) {
quantity = Integer.parseInt(quantityTextField.getText());
price = Integer.parseInt(priceTextField.getText());
mainWindow.putDataIntoTable(price,3,2);
}
}
Also you need to correct the call of constructor for UpdateWindow
private void updateBtnActionPerformed(java.awt.event.ActionEvent evt) {
UpdateWindow newWindow = new UpdateWindow(this);
newWindow.setVisible(true);
newWindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
Please note: I've corrected your class names as it proposed by Java naming convention. Main_Window -> MainWindow, Update_Window -> UpdateWindow.
When my suggestion don't solve your problems, please provide a [mcve] so we can better identify your problems.

How to repaint JPanel from outside its parent JFrame?

I can add/remove elements to/from a panel and repaint it when the method used to fill the panel is called by one of its parent JFrame events, but I can not repaint it by events from other classes even if their sources have been added to it, or that is how I understand the problem for now.
I want to understand what is going on here, Thank you.
Main Class
public class Principal extends JFrame implements ActionListener{
private static Principal instPrincipal = null;
private SubClass subClassInst =new SubClass();
public JPanel panelPrincipal;
public static Principal getInstance() {
if (instPrincipal != null)
return instPrincipal ;
else {
instPrincipal = new Principal ();
return instPrincipal ;
}
}
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
try {
if(source == btnSub)
{
subClassInst.fillPanelPrincipal();
}
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
Sub Classes Example
public class SubClass implements ActionListener {
private JPanel tempPanel;
private JButton btnSave;
private Principal instPrincipal;
public void fillPanelPrincipal() {
instPrincipal = Principal.getInstance();
instPrincipal.panelPrincipal.removeAll();
//Start adding elements..
tempPanel = new JPanel();
instPrincipal.panelPrincipal.add(tempPanel);
btnSave = new JButton("Save");
btnSave.addActionListener(this);
tempPanel.add(btnSave);
//End.
instPrincipal.panelPrincipal.repaint();
}
public void actionPerformed(ActionEvent event) {
instPrincipal = Principal.getInstance();
Object source = event.getSource();
if (source == btnSave) {
// modify local data, Database .. ; //work but need to be repainted on panelPrincipal
instPrincipal.panelPrincipal.repaint();//does not work
}
}
}
Update
To clarify the problem more, I have one single JPanel on a JFrame and there are different classes to fill it for multiple functionalities, I call their methods using JMenuItems on the main frame, these Classes implement ActionListener, passing the panel didn't work, and also the method I am trying here.
I thought about changing the design to use CardLayout, but it was very difficult.
You are calling Principal as a static reference, so how is it supposed to know what frame to repaint? You should pass the instance of the JFrame through the constructor of the subclass. Like so:
private SubClass subClassInst = new SubClass(this);
And create the constructor like this
private JFrame parent;
public SubClass(JFrame parent) { this.parent = parent; }
You can then use it like so
this.parent.repaint();

How to make interaction between Swing components, which are in different classes?

I have a complicated GUI with lot of components (JButtons, JLabels, JComboBoxes, JSpinners, etc). That's why I have to split it on several classes (add components to JPanels, this JPanels add to bigger JPanels, this JPanels add to JTabbedPane, and JTabbedPane add to JFrame).
Depend on user choises and filling in data some components enabled or disabled or get some value and set not editable (in a word - interact). It's easy to done and worked properly, if components (which are interact) are in the same class, but if only it are in different classes - any results... AAA!!!
I made simple example to explane what I need. There are four classes. First one create JFrame and add JTabbedPane:
public class MainFrame extends JFrame {
MainFrame() {
super("MainFrame");
go();
}
public void go() {
Tabs tabs = new Tabs();
getContentPane().add(tabs);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 300);
setVisible(true);
}
public static void main(String[] args) {
MainFrame frame = new MainFrame();
}
}
The second class create JTabbedPane and add two JPanels as tabs. Second tab.setEnabledAt(1, false):
public class Tabs extends JTabbedPane {
public Tabs() {
go();
}
public void go() {
TabData data = new TabData();
add(" Data ", data);
TabCalculation calculation = new TabCalculation();
add("Calculation", calculation);
setEnabledAt(1, false);
}
}
The third class create JPanel with JComboBox:
public class TabData extends JPanel {
public TabData() {
go();
}
JComboBox someData;
public void go() {
String type[] = { " ", "Type 1", "Type 2", "Type 3" };
someData = new JComboBox(type);
add(someData);
someData.addActionListener(new DataListener());
}
public class DataListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {
if (someData.getSelectedIndex() > 0) {
Tabs tabs = new Tabs();
tabs.setEnabledAt(1, true);
}
}
}
}
... and fourth class create some JPanel. Second tab with this JPanel disabled. When user set some value in JComboBox (selectedIndex>0) - tab have to enabled. But Tabs tabs = new Tabs(); tabs.setEnabledAt(1, true); didn't help...
How can I do that? PLEASE HELP!!! I can't sleep... I can't work... I always thinking about it and try to find out a solution...
When user set some value in JComboBox (selectedIndex>0) - tab have to
enabled.
If you need to have all of these classes split, then I would suggest you make this change in your 3rd class:
public class TabData extends JPanel {
JComboBox someData;
...
// Get rid of DataListener class and add this public method instead:
public void addActionListenerToComboBox(ActionListener listener) {
someData.addActionListener(listener);
}
}
And make this change in your 2nd class:
public class Tabs extends JTabbedPane {
public Tabs() {
go();
}
public void go() {
TabData data = new TabData();
data.addActionListenerToComboBox(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JComboBox comboBox = (JComboBox)e.getSource();
boolean enableSecondTab = comboBox.getSelectedIndex() > -1;
setEnabledAt(1, enableSecondTab);
}
});
add(" Data ", data);
TabCalculation calculation = new TabCalculation();
add("Calculation", calculation);
setEnabledAt(1, false);
}
}
Take a look to EventObject.getSource() javadoc for more details.

I need to add listeners to the checkboxes and changes in selection is shown in the textArea

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class JDorm implements ItemListener{
public static void main(String[] args){
JCheckBox privateroom = new JCheckBox("Private Room",false);
JCheckBox interweb = new JCheckBox("Internet Connection",false);
JCheckBox cable = new JCheckBox("Cable TV connection",false);
JCheckBox fridg = new JCheckBox("Refridgerator",false);
JCheckBox microwave = new JCheckBox("Microwave",false);
JCheckBox soon = new JCheckBox(",and so on",false);
JLabel greet = new JLabel("Please choose ammenities");
String sel = "Your selected options";
JTextArea textBox = new JTextArea(sel,0,1);
cable.addItemListener();
JFrame dormFrame = new JFrame("Dorm Options");// creates frame with title
final int WIDTH = 250;
final int HEIGHT = 500;
dormFrame.setSize(WIDTH, HEIGHT);// sets the size of frame in pixels
dormFrame.setVisible(true);// note: default visibility is false
dormFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
dormFrame.setLayout(new FlowLayout());
dormFrame.add(greet);
dormFrame.add(microwave);
dormFrame.add(fridg);
dormFrame.add(cable);
dormFrame.add(interweb);
dormFrame.add(privateroom);
dormFrame.add(soon);
dormFrame.add(textBox);
}
public void itemStateChanged(ItemEvent event){
Object source = event.getSource();
int select = event.getStateChange();
}
}
This is what I have so far, I know I need listeners, and a message to appear in the box when selection is checked and unchecked.
Do I need if statements for the changes?
Create a generic listener that can be added to all the check boxes. Something like:
ItemListener listener = new ItemListener()
{
public void itemStateChanged(ItemEvent event)
{
JCheckBox checkBox = (JCheckBox)event.getSource();
textBox.setText( checkBox.getText() );
}
};
Then you add the listener to each check box:
privateRoom.addItemListener( listener );
interweb.addItemListener( listener );
I have tried for one Checkbox and you can do others similarly
final JCheckBox privateroom = new JCheckBox("Private Room",false);
Now add item listener to checkbox privateroom and also the actions which you would like to happen i.e.
privateroom.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent event)
{
if (event.getItemSelectable() == privateroom)
textBox.setText("Private Room");
}
});
The reason i have declared Checkbox privaterroom as final is because privaterroom is local and is being accessed from an inner class.
One more thing I don't know the way you have written your program is good or bad because I am also learning swing and am a newbie. But the way i write my program has the following structure
class MyClass extends JFrame implements LISTENER_NAME
{
// Components declared here
// constructor starts
public MyClass()
{
//Componenets instantiated
// add listeners to appropriate components
// setVisible(), setDefaultCloseOperation(),setSize() etc called
}
// listener interface methods here like
public void itemStateChanged(ItemEvent ie)
{
................
}
// main method
public static void main(String[] args)
{
new MyClass();
}
} // class over
This way I have never encountered the final keyword etc problems. I hope some expert will guide us.

Categories