Have some problems with my revalidate/repaint - java

i tried to fix it with revalidate() & repaint() but it didn't work out for me, i searched for some more solutions, but everytime i try it doesn't work for me, could anyone help me please?
thanks alot,
Here is my script (not full)
public JPanel createPanel() throws SQLException, ClassNotFoundException
{
FormLayout formlayout1 = new
FormLayout("FILL:DEFAULT:NONE,FILL:119PX:NONE,
FILL:30PX:NONE,FILL:24PX:NONE,FILL:130PX:NONE,
FILL:16PX:NONE","CENTER:DEFAULT:NONE,CENTER:30PX:NONE,
CENTER:30PX:NONE,CENTER:25PX:NONE,CENTER:25PX:NONE,
CENTER:25PX:NONE,CENTER:25PX:NONE,CENTER:25PX:NONE");
CellConstraints cc = new CellConstraints();
jpanel1.setLayout(formlayout1);
JLabel lbl = null;
JTextArea col = null;
int i = 3;
for (OverzichtVo o : OverzichtBusiness.getOverzicht()){
lbl = new JLabel(mapServices.get(o.getServiceid()));
jpanel1.add(lbl, cc.xy(2, i));
col = new JTextArea();
col.setEditable(false);
LineBorder lineborder1 = new LineBorder(new Color(0,0,0),2,false);
col.setBorder(lineborder1);
col.setBackground(colors[o.getStatusid()-1]);
jpanel1.add(col, cc.xy(3, i));
lbl = new JLabel(o.getExtrainfo());
jpanel1.add(lbl, cc.xy(5, i));
i++;
button.setFont(new Font("Poor Richard",Font.PLAIN,20));
button.setName("button");
LineBorder lnbord = new LineBorder(new Color(0,0,0),2,false);
button.setBorder(lnbord);
refresh();
jpanel1.add(button,cc.xy(5,2));
m_lbloverzicht.setFont(new Font("Poor Richard",Font.PLAIN,30));
m_lbloverzicht.setName("lbloverzicht");
m_lbloverzicht.setText("Overzicht");
LineBorder lineborder1 = new LineBorder(new Color(0,0,0),2,false);
m_lbloverzicht.setBorder(lineborder1);
jpanel1.add(m_lbloverzicht,cc.xy(2,2));
addFillComponents(jpanel1,new int[]{ 1,2,3,4,5,6 },new int[]{ 1,2,3,4,5,6,7,8 });
return jpanel1;
}
private void refresh(){
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e)
{
jpanel1.revalidate();
jpanel1.repaint();
}
});
}
and i activate it all in another class :
public static void main(String args[]) throws SQLException, ClassNotFoundException{
JFrame frame = new JFrame();
AlgemeneFrm frm_alg = new AlgemeneFrm();
frame.add(frm_alg);
frame.setVisible(true);
frame.setSize(350,250);
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent evt)
{
System.exit(0);
}
});
}
I'm trying to refresh my whole Jpanel/panel cause my Jtextarea(background) is green, when i change something it's suppose to go red. that works fine for me if i stop application and start it again, but i added a button, so i could refresh/update my application or just panel. but it won't work with my 'refresh' button within 'panelname'.revalidate();and 'panelname'.repaint();
help please

Related

What 'no such child' means in java swing when trying to makeCompactGrid with class SpringUtilities

So I tried to make a simple java swing program, i didn't finish the program but I wanted to see how it looks before doing the functionality part, this is my code:
import layouts.SpringUtilities;
import javax.swing.*;
import layouts.SpringUtilities;
public class FactorialCalculatorFrame extends JFrame {
public FactorialCalculatorFrame(){
JPanel panel = new JPanel();
panel.setLayout(new SpringLayout());
JTextField brojText = new JTextField();
brojText.setColumns(10);
panel.add(new JLabel("Broj:", SwingConstants.RIGHT));
panel.add(brojText);
JButton start = new JButton("Start");
panel.add(new JLabel("Pokreni izracun:",SwingConstants.RIGHT));
panel.add(start);
JProgressBar napredakProgressBar = new JProgressBar();
add(new JLabel("Napredak:", SwingConstants.RIGHT));
add(napredakProgressBar);
JLabel rezultat = new JLabel("Rezultat:");
JLabel ispisiRez = new JLabel("");
add(new JLabel("Rezultat:", SwingConstants.RIGHT));
add(ispisiRez);
start.addActionListener((e)->{
try {
int number = Integer.parseInt(brojText.getText());
//reset GUI components
napredakProgressBar.setValue(0);
start.setEnabled(false);
ispisiRez.setText("");
//schedule for execution on one of working threads
new primeNumberJavaSwingApp().execute();
} catch (Exception ex) {
ex.printStackTrace();
}
});
SpringUtilities.makeCompactGrid(panel,4, 2, 0, 0, 5, 5);
add(panel);
}
public static void main(String[] args){
FactorialCalculatorFrame frame = new FactorialCalculatorFrame();
frame.setVisible(true);
}
public class primeNumberJavaSwingApp extends SwingWorker<Long, Integer> {
#Override
protected Long doInBackground() throws Exception {
Long l = (long)3.2;
return l;}}}
the Exception that occurs is this Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: No such child: 4
at layouts.SpringUtilities.makeCompactGrid(SpringUtilities.java:190)
at FactorialCalculatorFrame.<init>(FactorialCalculatorFrame.java:55)
Why does this occurs, what did I do wrong?
I also use SpringUtilities class that I copied from Oracle.
Any help is greatly appriciated!
I downloaded source code for class SpringUtilities from here.
Your problem is that you are not adding all the components to the panel. You are calling add() when you should be calling panel.add(). Hence you are only adding 4 components to panel rather than 8. Hence the error message.
I also added a call to method pack(), of class JFrame, in order to make the JFrame big enough to display all the components it contains.
Here is your code with my fixes:
import layout.SpringUtilities; // in your code this import is added twice
import javax.swing.*;
public class FactorialCalculatorFrame extends JFrame {
public FactorialCalculatorFrame() {
setDefaultCloseOperation(EXIT_ON_CLOSE); // I added this line
JPanel panel = new JPanel();
panel.setLayout(new SpringLayout());
JTextField brojText = new JTextField();
brojText.setColumns(10);
panel.add(new JLabel("Broj:", SwingConstants.RIGHT));
panel.add(brojText);
JButton start = new JButton("Start");
panel.add(new JLabel("Pokreni izracun:",SwingConstants.RIGHT));
panel.add(start);
JProgressBar napredakProgressBar = new JProgressBar();
panel.add(new JLabel("Napredak:", SwingConstants.RIGHT)); // change here
panel.add(napredakProgressBar); // change here
JLabel rezultat = new JLabel("Rezultat:");
JLabel ispisiRez = new JLabel("");
panel.add(new JLabel("Rezultat:", SwingConstants.RIGHT));
panel.add(ispisiRez);
start.addActionListener((e)->{
try {
int number = Integer.parseInt(brojText.getText());
//reset GUI components
napredakProgressBar.setValue(0);
start.setEnabled(false);
ispisiRez.setText("");
//schedule for execution on one of working threads
new primeNumberJavaSwingApp().execute();
} catch (Exception ex) {
ex.printStackTrace();
}
});
SpringUtilities.makeCompactGrid(panel, 4, 2, 0, 0, 5, 5);
add(panel);
}
public static void main(String[] args){
FactorialCalculatorFrame frame = new FactorialCalculatorFrame();
frame.pack(); // I added this line
frame.setLocationRelativeTo(null); // I added this line
frame.setVisible(true);
}
public class primeNumberJavaSwingApp extends SwingWorker<Long, Integer> {
#Override
protected Long doInBackground() throws Exception {
Long l = (long) 3.2;
return l;
}
}
}
Here is a screen capture of the JFrame when running the above code.

Gui Interactions

This is my first time creating a Gui and I'm stumped on how to create interactions.
I'm trying to implement a single selection mode when the combobox is on single, and multiple when it's placed on multiple. I placed them on the multi line comment.
Any ideas?
//Interactions
//When “Single” is selected then the JList changes so only one item
can be selected.
//When “Multiple” is selected, the JList changes so multiple items can
be selected
//When a country, or multiple countries, is selected the JLabel
changes to reflect the new selections
public class GuiTest {
public static String[] Countries = {"Africa", "Haiti", "USA", "Poland", "Russia", "Canada", "Mexico", "Cuba"};
public static String[] Selection = {"Single", "Multiple"};
JPanel p = new JPanel();
JButton b = new JButton("Testing");
JComboBox jc = new JComboBox(Selection);
JList jl = new JList(Countries);
private static void constructGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame();
frame.setTitle("Countries Selection");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// add a JLabel that says Welcome
JLabel label = new JLabel("Selected Items:");
frame.add(label);
frame.pack();
JComboBox jc = new JComboBox(Selection);
frame.add(jc);
frame.pack();
frame.setVisible(true);
JList jl = new JList(Countries);
frame.add(jl);
frame.pack();
JComponent panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.add(new JLabel("Choose Selection Mode:"));
panel.add(jc);
frame.add(panel, BorderLayout.NORTH);
frame.add(jl, BorderLayout.WEST);
frame.add(label, BorderLayout.SOUTH);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
constructGUI();
}
});
}
}
you should start adding the modes to the ComboBox:
comboBoxCategoria.addItem("Single",0);
comboBoxCategoria.addItem("Multiple",1);
then add a ActionListener to your ComboBox to modify the list selection mode
jc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(jc.getSelectedItem().equals("Single")){
jl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}else{//must equals
jl.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
}
}
});
finally add a MouseListener on the list to detect changes on the list selections and change the JLabel to reflect the new selections
jl.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent e) {
label.setText(list.getSelectedValuesList().toString());
}
});
edit: you should also add a KeyListener to update the label since the selection can be changed via arrow keys
jl.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
label.setText(list.getSelectedValuesList().toString());
}
});
It would be something like this:
jc.addActionListener((evt) -> {
if ("Single".equals(jc.getSelectedItem())) {
jl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
int[] sel = jl.getSelectedIndices();
if (sel != null && sel.length > 1) {
jl.setSelectedIndex(sel[0]);
}
} else {
jl.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
}
});
jl.addListSelectionListener((evt) -> {
StringBuilder buf = new StringBuilder();
for (Object o: jl.getSelectedValuesList()) {
if (buf.length() > 0) {
buf.append(", ");
}
buf.append(o);
}
label.setText(buf.toString());
});
jc.setSelectedItem("Single");

Window not appearing properly after opening with JButton in Java

I have a very strange problem with my java application. I basically click the JButton and the new window I want to open opens but with no content showing. Here is what happens.
If I run the class on its own without using a JButton it runs proberly like so.
Here is the code for the button.
public Create()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 629, 316);
contentPane = new JPanel();
contentPane.setBackground(new Color(255, 255, 204));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
btnBuildData = new JButton("Build Graph");
btnBuildData.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
//CreateTest frame = new CreateTest();
new CreateTest().setVisible(true);
}
});
btnBuildData.setBackground(Color.WHITE);
btnBuildData.setForeground(Color.BLACK);
btnBuildData.setBounds(29, 59, 107, 23);
contentPane.add(btnBuildData);
This is strange to me because I have used this code for other classes and it works as intended. I have tried many different ways to do the same thing but none of them have worked. Here is some code for the frame I am opening with the button.
public class CreateTest extends JFrame {
public CreateTest() {
}
//Create the connection to Neo4j
Driver driver = GraphDatabase.driver( "bolt://localhost", AuthTokens.basic( "*****", "*******" ) );
Session session = driver.session();
StatementResult resultVariable;
Record recordVariable;
//Create variables to manage communication with Neo4j
String resultString = new String();
Query neoQuery = new Query();
private JTextField progressTextField;
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new CreateTest().initUI();
}
});
}
protected void initUI()
{
final JFrame frame = new JFrame();
//the form
frame.setTitle(CreateTest.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Click here to add data");
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
doWork();
}
});
progressTextField = new JTextField(25);
progressTextField.setEditable(false);
frame.getContentPane().add(progressTextField, BorderLayout.NORTH);
frame.getContentPane().add(button, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
protected void doWork() {
SwingWorker<Void, Integer> worker = new SwingWorker<Void, Integer>() {
#Override
protected Void doInBackground() throws Exception {
CreateTest frame = new CreateTest();
}
#Override
protected void process(List<Integer> chunks) {
progressTextField.setText(chunks.get(chunks.size() - 1).toString());
}
#Override
protected void done() {
progressTextField.setText("Success: All Nodes have been added ");
}
};
worker.execute();
}
}
There is a difference between the two windows. One being absolute layout and the other jpanel but I don't think this is the problem. If anyone has any ideas please let me know, any ideas will be appreciated. Thanks.
Your calling an empty constructor with new CreateTest()
public CreateTest() {
}
It does nothing since your code is outside of it.

JPanel How to make button work?

As you read this code, you will realize I got one action event to work, it opens up a new JPanel that displays the button that will run the ballBounce, but for now im stuck trying to get a working button within that frame because that frame is already within a actionEvent, any help?
public class MainJPanelOperation
{
public static void main(String[] a)
{
JPanel panel1 = new JPanel(new GridLayout(5, 10, 1, 1));
JButton t1 = new JButton();
JButton t2 = new JButton();
JButton letsStart = new JButton("Start The Program!");
JButton t3 = new JButton();
JButton t4 = new JButton();
//letsStart.setBounds(200,250,12,12);
panel1.add(t1);
panel1.add(t2);
panel1.add(letsStart);
panel1.add(t3);
panel1.add(t4);
final JFrame frame1 = new JFrame("Game");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.add(panel1);
frame1.setSize(1000,1000);
frame1.setVisible(true);
t1.setVisible(false);
t2.setVisible(false);
t3.setVisible(false);
t4.setVisible(false);
letsStart.setBackground(Color.yellow);
panel1.setBackground(Color.black);
letsStart.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("panel 2 main menu intro online");
JPanel panelMM = new JPanel(new GridLayout(5, 10, 1, 0));
JButton MM1 = new JButton("BallBounce");
panelMM.add(MM1);
JFrame frameMM = new JFrame("Game/Main Menu");
frameMM.add(panelMM);
frameMM.setSize(1000,1000);
frameMM.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frameMM.setVisible(true);
frame1.setVisible(false);
}
});//end of start sequence
}
}
JPanel panelMM = new JPanel(new GridLayout(5, 10, 1, 0));
JButton MM1 = new JButton("BallBounce");
panelMM.add(MM1);
final JFrame frameMM = new JFrame("Game/Main Menu");
frameMM.add(panelMM);
frameMM.setSize(1000,1000);
frameMM.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
letsStart.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("panel 2 main menu intro
frameMM.setVisible(true);
frame1.setVisible(false);
}
});
You can make frameMM final and there is no need to have all of your code inside the ActionListener.
Try This :it is working inside a Action Listener.
JButton MM1 = new JButton("BallBoe");
MM1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("panel 2");
}
});
or class MainJPanelOperation implements ActionListener
You can use class MainJPanelOperation
{
static JButton MM1;
//your code
}
MM1=new JButton("Button");
MM1.addActionListener(this);
write a Method outside Main()
public void ActionPerformed(ActionEvent e)
{
if(e.getSource()==MM1)
{
System.out.print("");
}
if(e.getSource()==Buttonobject)
{
//your code for button Pressing Event
}
}

How do i make next button go to next Frame? GUI

How do I make the next button go to the next Frame in this GUI? I need to have it where I can click next to display 20 more details:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class FilledFrameViewer
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
/*JButton button = new JButton*/
JButton nextButton = new JButton("NEXT");
JLabel label = new JLabel("Frame 1.");
JPanel panel = new JPanel();
panel.add(nextButton);
panel.add(label);
frame.add(panel);
final int FRAME_WIDTH = 300;
final int FRAME_HEIGHT = 100;
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setTitle("A frame with two components");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
If you want to hide or show the frame, you can use like this
JFrame f1 = new JFrame("Frame 1");
JFrame f2 = new JFrame("Frame 2");
to hide f1, call f1.setVisible(false);
to show f2, call f2.setVisible(true);
A bit unclear. Do you want to move a JButton to another JFrame? I don't think you can manage that without dynamic programming or such (I guess?).
You should look through a tutorial of the Swing components from Oracle http://docs.oracle.com/javase/tutorial/uiswing/
And see your comments. I agree having multiple JFrame is a bad habit.
Edit
Use the eventlistner (see other answer) and make it follow a switch case? Then there you can make it display like a dialog or change a JLable inside your JFrame?
Dialog tutorial here: http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html.
I think you should go with a lable and change it's text.
JButton nextButton = new JButton("Next");
nextButton.addActionListener(new ActionListner(
private int counter = 0;
public void actionPerformed(ActionEvent e) {
counter++;
switch(counter){
case 1: somelable.setText("Your text here");
};
}));
I wrote this on free hand but I guess something like this would work?
You have to edit the codes in your next frame...
Example for your NextFrame,
public class NextFrame
public static void main(String[] args)
{
private static FilledFrameViewer parentFrame; //ADD THIS FOR CONNECTION TO FIRST FRAME
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
NextFrame frame = new NextFrame(null); //CHANGES MADE HERE
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
public NextFrame(FilledFrameViewer f) { //CHANGES MADE HERE
this.parentFrame = f; //CHANGES MADE HERE
setTitle("Personal Assistant");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
Ah, Yes...and also you'll have to add some things in the Next button...
Example:
btnNext = new JButton();
btnNext.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
goNext();
{
private void goNext(){
NextFrame nextframe= new NextFrame(null);
nextframe.setVisible(true);
}
}
});

Categories

Resources