Jtabbedpane使用多个类 [英] Jtabbedpane using multiple classes
问题描述
我是相当新的java和创建一个windowbuilder程序。我想知道是否是可能的,当使用Jtabbedpane和在程序窗口中的选项卡之间切换,如果我可以使用actionlistener从一个单独的类获取内容。例如,我有一个程序有两个选项卡和两个类,第一个选项卡将有一个类的代码和第二个类的第二个选项卡。
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.
谢谢
推荐答案
如果你想把创建GUI的代码分成多个类,你可以使用这个aproach:
If you want to separate your code which creates GUI, to multiple classes, you could use this aproach:
这将是你的主类,它将包含 JTabbedPane
:
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();
}
});
}
}
扩展 JPanel
或其他类型的容器:
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);
}
}
第三类的示例也扩展 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);
}
}
屏幕截图:
>
EDIT:
此外,与 JPanel
明智地在该类中创建一个方法,该方法返回自定义的 JPanel
。这种方式,你的类继承开放继承。
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.
这篇关于Jtabbedpane使用多个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!