Я пытаюсь обновить панель из другой. Один отображает график и путь, другой выполняет алгоритм и изменяет путь. Когда путь будет обновлен, я бы хотел, чтобы панель графа обновлялась, но этого не происходит.Невозможно обновить JPanel с другой панели
Это как классы панели: (Один получает другой в качестве параметра это плохая идея.?)
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.io.IOException;
import javax.swing.JPanel;
import algcomp.util.Graph;
// main canvas class where points of the graph are drawn
public class GraphPanel extends JPanel {
private Graph graph;
private int[] path;
private boolean hasPath;
public GraphPanel(String gf) throws IOException{
super();
graph = new Graph(gf);
hasPath = false;
repaint();
}
//preferred size of panel
public Dimension getPreferredSize(){
return (new Dimension(500, 400));
}
public void setGraph(Graph gr){
graph = gr;
repaint();
}
public Graph getGraph() {
return graph;
}
public void setPath(int[] _path){
path = _path;
hasPath = true;
//printArray(path);
removeAll();
revalidate();
repaint();
}
//for testing
private void printArray(int[] arr){
for(int i = 0;i<arr.length;i++){
System.out.print(arr[i]+",");
}
}
public void paintComponent(Graphics g)
{
//System.out.println("amieventrying");
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
for(int i=0;i<graph.points.size();i++){
g2d.fillOval(graph.points.get(i).getX(), graph.points.get(i).getY(),5, 5);
}
g2d.setColor(Color.RED);
if(hasPath == true){
for(int i=0; i<path.length-1;i++){
g2d.drawLine(graph.getPoint(i).getX(), graph.getPoint(i).getY(), graph.getPoint(i+1).getX(), graph.getPoint(i+1).getY());
}
}
}
}
Другой класс:
package algcomp.gui.main;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import algcomp.alg.Genetic;
import algcomp.alg.PathChromosome;
public class OptionPanel extends JPanel{
String type;
GraphPanel gp;
Genetic genalg;
boolean alg_initialized;
//genetic
JLabel gensizeL;
JLabel mutprobL;
JLabel timerL;
JTextField gensizeTF;
JTextField mutprobTF;
JTextField timerTF;
JButton runstepB;
JButton runallB;
public OptionPanel(String _type, GraphPanel _gp){
type = _type;
gp = _gp;
runstepB = new JButton("Run Step");
runallB = new JButton("Full Run");
if(type.equals("Genetic")){
genPan();
alg_initialized = false;
}
}
//preferred size of panel
public Dimension getPreferredSize(){
return (new Dimension(250,150));
}
//
private void genPan(){
gensizeL = new JLabel("Generation size: ", SwingConstants.RIGHT);
mutprobL = new JLabel("Mutation probability: ", SwingConstants.RIGHT);
timerL = new JLabel("Timer for full run (ms): ", SwingConstants.RIGHT);
gensizeTF = new JTextField("20");
mutprobTF = new JTextField("0.1");
timerTF = new JTextField("60000");
this.setLayout(new GridLayout(4,2));
this.add(gensizeL);
this.add(gensizeTF);
this.add(mutprobL);
this.add(mutprobTF);
this.add(timerL);
this.add(timerTF);
this.add(runstepB);
this.add(runallB);
//This function runs when runstep button is clicked
runstepB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(!alg_initialized){
if(type.equals("Genetic")){
genalg = new Genetic(gp.getGraph(),Integer.parseInt(gensizeTF.getText()),Double.parseDouble(mutprobTF.getText()),Integer.parseInt(timerTF.getText()));
alg_initialized = true;
}
}
if(type.equals("Genetic")){
gp.setPath(((PathChromosome) genalg.step()).getPath());
}
}
});
//This function runs when runall button is clicked
runallB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Will launch a full run someday :D ");
}
});
}
}
aaaand это, как они называется:
public void displayGUI() throws IOException{
JFrame frame = new JFrame("Algorithm Comparison");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fixedop = new FixedOptionPanel();
allop = new JPanel();
JPanel mainpanel = new JPanel();
mainpanel.setLayout(new GridLayout(1,2));
canvas = new GraphPanel("/u1/cmperezgavilantorres/workspacejava/graphs/g1");
options = new OptionPanel("Genetic",canvas);
allop.setLayout(new GridLayout(2,1));
allop.add(fixedop);
allop.add(options);
mainpanel.add(canvas);
mainpanel.add(allop);
mainpanel.setBackground(Color.WHITE);
frame.setContentPane(mainpanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
вы можете увидеть причину, почему метод setPath в классе GraphPanel кажется, не имеет Effe кар ??
Пожалуйста, помогите :(
Может быть, лучше иметь метод updateAllPanels() в вашем основном классе. –
. Кажется, вы ничего не рисуете на основе нового пути. 'paintComponent()' имеет 'hasPath ', но используемые данные исходят от объекта графа (и уже вычерчены один раз?) – kiheru
Я бы ссылался на другой класс, не используя его в качестве параметра, но вместо этого делаю canvas public & static, поэтому вы можете получить к нему доступ с помощью 'Class.canvas' (замените' Class' на любой класс, содержащий 'displayGUI()'). , независимо от того, работает ли это, зависит от структуры вашего проекта - возможно, вам придется слегка его изменить, например. добавив другой проект в ваш путь строительства или что-то в этом роде. – PixelMaster