Switch between JPanels of different classes - java

How do I switch between JPanels of different classes? I do not wish to use a Card Layout.
I have 2 classes - MainPage & MenuPage. For instance, I would like to clear the contentPane (a JPanel) # MainPage and replace it with the content pane # MenuPage. For testing purposes, I included a button # MenuPage.
Please see my following attempt - it gives an error:
java.lang.IllegalArgumentException: adding a window to a container
MainPage
public class MainPage extends JFrame {
private static JPanel contentPane;
private JLabel imgBackground;
private JLabel lblTitle;
private JLabel imgLogo;
private Dimension dim;
//timer
private final static int interval = 40;
private int i;
private Timer t;
//private JButton start;
//private JLabel lblLoading;
private JProgressBar pbar;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainPage frame = new MainPage();
frame.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
public MainPage() {
dim = Toolkit.getDefaultToolkit().getScreenSize();
System.out.println(dim);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
contentPane.setBounds(0,0,dim.width,dim.height);
setContentPane(contentPane);
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
t = new Timer (interval, new ActionListener(){
public void actionPerformed(ActionEvent e) {
if (i == 20){
t.stop();
//start.setEnabled(true);
//refresh + load next page ???
contentPane.removeAll();
MenuPage loadpanel2 = new MenuPage();
setContentPane(loadpanel2);
revalidate();
repaint();
}
else{
i++;
pbar.setValue(i);
}
}
});
t.start();
MenuPage
public class MenuPage extends JFrame {
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MenuPage frame = new MenuPage();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public MenuPage() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
setContentPane(contentPane);
JButton btnSadfsafsa = new JButton("sadfsafsa");
btnSadfsafsa.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnSadfsafsa.setBounds(10, 52, 89, 23);
btnSadfsafsa.setEnabled(true);
btnSadfsafsa.setVisible(true);
contentPane.add(btnSadfsafsa);
}
}

java.lang.IllegalArgumentException: adding a window to a container
That is pretty straightforward. Both GUIs extend JFrame and are therefore top level containers. We cannot add one top level container to another.
Instead of extending frame, both GUIs might extend JPanel. A JPanel (or more than one) can then be added to a JFrame instantiated in the main(String[]) or a showGUI() method.

Related

How to center component vertically in JPanel which useFlowLayout

I have a certain panel which contains a random number of items. This panel is added to the EAST of a JPanel which use BorderLayout.
I'd like to have them vertically centered.
How do i achieve this?
here is a code you can run
public class MainFrame {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new AlignDemo());
}
}
class AlignDemo implements Runnable {
#Override
public void run(){
try {
JFrame mainWindow = new JFrame();
mainWindow.getContentPane().add(initPanel());
mainWindow.pack();
mainWindow.setVisible(true);
} catch (Throwable th) {
JOptionPane.showMessageDialog(null,null,"General Error", JOptionPane.ERROR_MESSAGE);
}
}
private JPanel initPanel() {
FlowLayout layout = new FlowLayout(FlowLayout.LEFT);
layout.setHgap(15);
JPanel myContent = new JPanel();
myContent.setPreferredSize(new Dimension(400,200));
myContent.setBorder(BorderFactory.createLineBorder(Color.blue));
JButton button1 = new JButton("I'm a button");
JButton button2 = new JButton("I'm a button");
JButton button3 = new JButton("I'm a button");
myContent.add(button1,Component.CENTER_ALIGNMENT);
myContent.add(button2,Component.CENTER_ALIGNMENT);
myContent.add(button3,Component.CENTER_ALIGNMENT);
return myContent;
}
}
It can easily be achieved by combining layouts. A JPanel with FlowLayout (controls) to position the buttons relative to one another, placed as a single component into a JPanel with a GridBagLayout (ui).
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class CenteredButtons2 {
private JComponent ui = null;
CenteredButtons2() {
initUI();
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new GridBagLayout()); // to center a single component
ui.setBorder(new EmptyBorder(4,4,4,4));
JPanel controls = new JPanel(new FlowLayout());
for (int ii=1; ii<4; ii++) {
controls.add(new JButton("Button " + ii));
}
controls.setBorder(new EmptyBorder(50, 90, 50, 90));
ui.add(controls);
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
CenteredButtons2 o = new CenteredButtons2();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}

Java JFrame Graphics dont show up

public class FrameTest extends JFrame {
private JPanel contentPane;
private JPanel spielPane;
private JPanel infoPane;
private JButton btnStart;
private JLabel lblRunde;
private Monster monster1;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FrameTest frame = new FrameTest();
frame.setVisible(true);
Monster m = new Monster();
frame.repaintSpielPanel();
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
public FrameTest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 600);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
setContentPane(contentPane);
spielPane = new JPanel();
spielPane.setBounds(6, 6, 566, 566);
spielPane.setLayout(null);
spielPane.setBackground(Color.yellow);
contentPane.add(spielPane);
infoPane = new JPanel();
infoPane.setBounds(578, 6, 216, 566);
infoPane.setLayout(null);
infoPane.setBackground(Color.yellow);
contentPane.add(infoPane);
btnStart = new JButton("Start");
btnStart.setBounds(44, 6, 117, 29);
infoPane.add(btnStart);
lblRunde = new JLabel("Runde");
lblRunde.setBounds(77, 47, 61, 16);
infoPane.add(lblRunde);
monster1 = new Monster();
monster1.setVisible(true);
spielPane.add(monster1);
}
private class Monser extends JLabel {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.fillRect(0, 0, 10, 10);
}
}
public void repaintSpielPanel() {
spielPane.repaint();
}
}
I tried to put a Rectangle into my frame, but it isn't there. I'm just starting to program, so probably I just don't know how to get it onto the screen. Pls help!
Don't paint in a JLabel which isn't opaque. Instead do so in a JPanel.
Don't use null layouts and setBounds(...). While null layouts and setBounds() might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.
Most important, you never add an instance of your drawing component, here Monser, to anything. To see that this is true, search your code for any calls to new Monser(). If a constructor isn't being called, an instance isn't going to be created.
Also note that you're creating a Monster instance, and this is a class that you've not shown us.
You're adding it to a null layout using JPanel, and so since it has no size, it won't show at all. Again, don't use null layouts.
For example:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import javax.swing.*;
#SuppressWarnings("serial")
public class MyTest extends JPanel {
private static final Color BG = Color.yellow;
private static final int GAP = 8;
private JButton btnStart = new JButton("Start");
private JLabel lblRunde = new JLabel("Runde", SwingConstants.CENTER);
private MonsterPanel monsterPanel = new MonsterPanel(600, 600, BG);
public MyTest() {
JPanel buttonPanel = createButtonPanel();
buttonPanel.setBackground(BG);
setLayout(new BorderLayout(GAP, GAP));
setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
add(monsterPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.LINE_END);
}
private JPanel createButtonPanel() {
JPanel btnPanel = new JPanel();
btnPanel.setBackground(BG);
JPanel gridPanel = new JPanel(new GridLayout(0, 1, 0, 5));
gridPanel.setOpaque(false);
gridPanel.add(btnStart);
gridPanel.add(lblRunde);
btnPanel.add(gridPanel);
return btnPanel;
}
private static void createAndShowGui() {
MyTest mainPanel = new MyTest();
JFrame frame = new JFrame("MyFrameTest");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class MonsterPanel extends JPanel {
public static final int MONST_WIDTH = 10;
public static final Color MONST_COLOR = Color.red;
private int prefW;
private int prefH;
private int monstX = 0;
private int monstY = 0;
public MonsterPanel(int prefW, int prefH, Color bkgrnd) {
this.prefW = prefW;
this.prefH = prefH;
setBackground(bkgrnd);
}
public void setMonstXY(int x, int y) {
this.monstX = x;
this.monstY = y;
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(MONST_COLOR);
g.fillRect(monstX, monstY, MONST_WIDTH, MONST_WIDTH);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(prefW, prefH);
}
}

Adding a JTable to JFrame

I want to add test2 to my DFrametest class, so that the table of test2 shows up in my window. I get an empty window and can't find the mistake.
public class test2 extends JPanel {
JTable tbl;
DefaultTableModel dt;
public test2(){
JLabel label = new JLabel("Course Lookup GUI");
this.add( label );
tbl = new JTable();
dt = new DefaultTableModel();
dt.addColumn("ID");
dt.addColumn("Name");
tbl.setModel(dt);
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/lagerverwaltungwin", "root", "");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT ArtNr, Beschreibung FROM artikel");
}catch(Exception e){
e.printStackTrace();
}
JScrollPane jp = new JScrollPane();
jp.getViewport().add(tbl);
add(jp);
}
}
This is my Frameclass which should have the table from test2:
public class DFrametest extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DFrametest frame = new DFrametest();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public DFrametest() {
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);
test2 t = new test2();
this.add(t);
this.setVisible(true);
}
}
Never Use null Layout. Also donot use setBounds(100, 100, 450, 300);
use pack();
Change your DFrametest class like this
contentPane.setLayout(new BorderLayout());
contentPane.add(t, BorderLayout.CENTER);
Full Code of DFrametest class:
public class DFrametest extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DFrametest frame = new DFrametest();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public DFrametest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
test2 t = new test2();
contentPane.setLayout(new BorderLayout());
contentPane.add(t, BorderLayout.CENTER);
pack();
}
}
Try to use setBounds() method since you haven't mentioned any layout (setLayout is null).
Add setBounds method before adding the jpanel to the jframe
setBounds(x-axis,y-axis,width,height);
EX:-
setBounds(10,20,200,400);
Note:

SWT widget into Swing

I have a simple JFrame and a JPanel inside it.
public class TestPanel extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestPanel frame = new TestPanel();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public TestPanel() {
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(new BorderLayout(0, 0));
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
}
}
And I have an SWT widget (Nebula Gantt Chart). -->
http://hexapixel.com/software/ganttwidget
I would like to add this SWT widget to the JPanel, actually embed it.
What are the possible ways to do it? Thank you for help! :-)

Substitute the currently displayed JPanel with another JPanel within a JFrame

I have three Java classes:
a JFrame: HomeView,
a JPanel: TopicListView,
another JPanel: ReplyListView.
In HomeView, I have a menu item that I can click to display TopicListView. In TopicListView, I want to have a button that I can click to display ReplyListView. When the button is clicked, it will invoke the openReplyListView() method. The method will create a new JPanel and replace the current JPanel with it. However, the code in openReplyListView() do not work.
Note: I am not using CardLayout.
Any help would be appreciated on how to get this working.
Thanks in advance.
HomeView class:
public class HomeView extends JFrame {
private JPanel contentPane;
private JMenuBar menuBar;
private JMenu mnForum;
private JMenuItem mntmReply;
private JMenuItem mntmTopic;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
HomeView frame = new HomeView();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public HomeView() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 1280, 720);
setJMenuBar(getMenuBar_1());
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
}
private JMenuBar getMenuBar_1() {
if (menuBar == null) {
menuBar = new JMenuBar();
menuBar.add(getMnForum());
}
return menuBar;
}
private JMenu getMnForum() {
if (mnForum == null) {
mnForum = new JMenu("Forum");
mnForum.add(getMntmTopic());
mnForum.add(getMntmReply());
}
return mnForum;
}
private JMenuItem getMntmReply() {
if (mntmReply == null) {
mntmReply = new JMenuItem("Reply");
mntmReply.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JPanel panel = new ReplyView();
getContentPane().removeAll();
getContentPane().add(panel);
getContentPane().validate();
getContentPane().repaint();
}
});
}
return mntmReply;
}
private JMenuItem getMntmTopic() {
if (mntmTopic == null) {
mntmTopic = new JMenuItem("Topic");
mntmTopic.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JPanel panel = new TopicListView();
getContentPane().removeAll();
getContentPane().add(panel);
getContentPane().validate();
getContentPane().repaint();
}
});
}
return mntmTopic;
}
}
TopicListView class:
public class TopicListView extends JPanel {
private JTable table;
private JScrollPane scrollPane;
private JLabel lblTopics;
/**
* Create the panel.
*/
public TopicListView() {
setLayout(null);
add(getTable());
add(getScrollPane());
add(getLblTopics());
}
**Code snippet for the table and the scrollpane:**
private void openReplyListView(){
JPanel panel = new ReplyListView();
getContentPane().removeAll();
getContentPane().add(panel);
getContentPane().validate();
getContentPane().repaint();
}
ReplyListView class (In general it's the same as TopicListView)
public class ReplyListView extends JPanel {
private JTable table;
private JScrollPane scrollPane;
private JLabel lblTest;
/**
* Create the panel.
*/
public ReplyListView() {
setLayout(null);
add(getTable());
add(getScrollPane());
add(getLblTest());
}
private JTable getTable() {
if (table == null) {
table = new JTable();
table.setBounds(414, 114, 464, 354);
}
return table;
}
private JScrollPane getScrollPane() {
if (scrollPane == null) {
scrollPane = new JScrollPane(getTable());
scrollPane.setBounds(414, 114, 464, 349);
}
return scrollPane;
}
private JLabel getLblTest() {
if (lblTest == null) {
lblTest = new JLabel("TEST");
lblTest.setFont(new Font("Tahoma", Font.PLAIN, 30));
lblTest.setBounds(593, 35, 81, 68);
}
return lblTest;
}
}
Your TopicListView have no LayoutManger (i.e. setLayout(null) in constructor).
It's usually a bad idea. (I'm pretty sure that's the cause of your problem)
Try something like this
private void openReplyListView(){
JPanel panel = new ReplyListView();
removeAll();
setLayout(new BorderLayout());
add(panel, BorderLayout.CENTER);
validate();
repaint();
}

Categories

Resources