How to switch JPanels in a JFrame from within the panel?

Like so : import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Color; import java.awt.Dimension; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class CardLayoutDemo extends JFrame { public final String YELLOW_PAGE = “yellow page”; public final String RED_PAGE = “red page”; private final CardLayout cLayout; private final JPanel mainPane; boolean isRedPaneVisible; public CardLayoutDemo(){ setTitle(“Card Layout Demo”); setDefaultCloseOperation(EXIT_ON_CLOSE); setLocationRelativeTo(null); mainPane … Read more

How to add an image to a JFrame title bar?

Since JPanel doesn’t have a title bar, I’m assuming that you’re referring to JFrame. That being said, use setIconImage(…). Here is an example of using setIconImages(). import java.awt.Image; import javax.swing.*; import javax.imageio.ImageIO; import; import java.util.*; class FrameIcons { public static void main(String[] args) throws Exception { URL url16 = new URL(“”); URL url32 = … Read more

How to add JCheckBox in JTable?

Start with How to use tables. Your table model needs several things. It needs to return Boolean.class from the getColumnClass method for the appropriate column. You will need to override this method. The method isCellEditable will need to return true for the table column you want to make editable (so the user can change the … Read more

Drag and Resize undecorated JFrame

You can check out mr Rob Camick’s ComponentResizer class. Pretty simple and straight forward to use. Just instantiate the ComponentResizer and register the frame with something like: JFrame frame = new JFrame(); ComponentResizer cr = new ComponentResizer(); cr.registerComponent(frame); cr.setSnapSize(new Dimension(10, 10)); cr.setMaximumSize(new Dimension(…)); cr.setMinimumSize(new Dimension(…)); Here’s a complete example of using the class import java.awt.*; … Read more

How to use KeyListener with JFrame?

The rectangle is not moving because you are not using JFrame correctly. You have to assign frame to new mainFrame() instead of ignoring the instantiated mainFrame object. There are several other issues as @MadProgrammer points out. Here is the code that fixes some of the issues: import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JFrame; … Read more

Center JDialog over parent

On the JDialog you’ve created you should call pack() first, then setLocationRelativeTo(parentFrame), and then setVisible(true). With that order the JDialog should appear centered on the parent frame. If you don’t call pack() first, then setting the location relative to the parent doesn’t work properly because the JDialog doesn’t know what size it is at that … Read more