Jtabbedpane using multiple classes
class, java, jtabbedpane, swing
Solution
If you want to separate your code which creates GUI, to multiple classes, you could use this aproach:
This would be your main class which will contain `JTabbedPane`:
import javax.swing.JFrame;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
public class Main {
JFrame frame = new JFrame();
JTabbedPane tabbedPane = new JTabbedPane();
FirstPanel fp = new FirstPanel();
SecondPanel sp = new SecondPanel();
public Main() {
tabbedPane.add("First", fp);
tabbedPane.add("Second", sp);
frame.getContentPane().add(tabbedPane);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(640, 480);
// frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Main();
}
});
}
}
This would be your second class which extends `JPanel` or some other type of container:
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.JPanel;
public class FirstPanel extends JPanel{
public void paintComponent(Graphics g){
g.setColor(Color.BLACK);
g.setFont(new Font("Verdana",Font.BOLD,16));
g.drawString("Hello there", 20, 20);
}
}
Example of third class which also extends `JPanel`:
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class SecondPanel extends JPanel{
JButton button = new JButton("Click me!");
public SecondPanel() {
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(null, "You just clicked button");
}
});
add(button);
}
public void paintComponent(Graphics g){
g.setColor(Color.BLACK);
g.setFont(new Font("Verdana",Font.BOLD,16));
g.drawString("Hello there again!", 20, 20);
}
}
Screenshot:
EDIT:
Also, instead of extending classes with `JPanel`, it would be wise to create just a method in that class which returns customized `JPanel`. This way your class stays "opened" for inheritance.
Problem
I'm fairly new to java and am creating a windowbuilder program. I am wondering if it is possible when using Jtabbedpane and switching between the tabs in the program window if i can use an actionlistener to get the contents from a separate class. For example, i have a program with two tabs and two classes, the first tab will have the code from one class and the second tab from the second class. Thanks