Things get displayed differently on a pane - java

I display everything raw off the frame. But if I create a JPanel) and add the contents to that, then add the panel to the frame using frame.add(pane, BorderLayout.CENTER); but its displayed differently and isnt put properly.
For example normally raw everything is displayed properly. On a pane Text isn't displayed properly from a JTextPane, the start is cut off and it doesn't take up the whole window.
And when I add a JTextBox to the mainPane, it doesn't take the whole width of the window and is put at the half way line when i specifically put BorderLayout.SOUTH, also the text box looks like this [] and you can't type in it.
Here is code for start:
public class ConsoleApp {
public static JFrame frame;
public static JTextPane consoleOutput;
public static JTextField consoleInput;
public JScrollPane scroll;
public static JTabbedPane tabs;
public static JPanel mainPane;
public static JPanel backupPane;
public static InputStream commandInput;
public static StyledDocument doc;
public static boolean trace = false;
public boolean debug = false;
public Font consoleFont = new Font("Courier New", Font.PLAIN, 12);
//public Color consoleColour = new Color(50, 50, 50);
public Color consoleColour = new Color(255, 255, 255);
//public Logger internalConsole;
public void start()
{
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(Exception e)
{
}
initializeFrame();
}
public void initializeFrame()
{
frame = new JFrame();
frame.setTitle("sebagius7110's Minecraft Server Wrapper");
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
consoleOutput = new JTextPane();
consoleOutput.setEditable(false);
consoleOutput.setFont(consoleFont);
consoleOutput.setBorder(null);
consoleOutput.setOpaque(false);
doc = consoleOutput.getStyledDocument();
consoleInput = new JTextField();
consoleInput.setFont(consoleFont);
//consoleInput.setBorder(null);
consoleInput.setOpaque(false);
consoleInput.setEditable(true);
Property.readProperties();
consoleInput.setCaret(new ConsoleCaret());
consoleInput.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
String text = consoleInput.getText();
if(text.length() >= 1)
{
if(text.startsWith("."))
{
onCommand(text);
} else {
try{
InputStream is = new ByteArrayInputStream(consoleInput.getText().getBytes(Charset.forName("UTF-8")));
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String input;
//input = br.readLine();
while(Util.ServerRunning && (input=br.readLine())!=null){
Stream.PutString(input);
}
br.close();
}catch(IOException io){
io.printStackTrace();
}
}
consoleInput.selectAll();
}
}
});
consoleInput.addKeyListener(new KeyListener()
{
#Override
public void keyPressed(KeyEvent arg0) {}
#Override
public void keyReleased(KeyEvent arg0) {}
#Override
public void keyTyped(KeyEvent arg0) {}
});
scroll = new JScrollPane(consoleOutput);
scroll.setBorder(null);
scroll.setOpaque(false);
scroll.getViewport().setOpaque(false);
scroll.setBackground(GetPropValues.cbcolor);
tabs = new JTabbedPane();
mainPane = new JPanel();
backupPane = new JPanel();
//frame.setUndecorated(true);
tabs.addTab("Main", mainPane);
tabs.addTab("Backup", backupPane);
mainPane.setBorder(null);
mainPane.setOpaque(false);
mainPane.add(scroll, BorderLayout.CENTER);
mainPane.add(consoleInput, BorderLayout.SOUTH);
frame.setContentPane(mainPane);
//frame.add(scroll, BorderLayout.CENTER);
//frame.add(consoleInput, BorderLayout.SOUTH);
frame.setSize(660, 350);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
}
That isn't the whole class, just some of it, so the brackets are not giving errors.

To set window size with position for any swing component use :
eg. compVariable.setBounds(x,y,width,height);

Related

Change button's text with an external combobox java

I've two class. Can i change a text of a button in a class "home" with an actionlistener of the combobox in a class "panelGestisciImpianti"? I don't unterstand becasue don't works.
The code is this:
//home
package s;
public class home extends JFrame {
private JPanel contentPane;
private panelImpostazioni panel5= new panelImpostazioni();
private JButton btnImpostazioni = new JButton("no"); //$NON-NLS-1$
public static void main(String[] args) {
home frame = new home();
frame.setVisible(true);
}
public home() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setExtendedState( JFrame.MAXIMIZED_BOTH) ;
setBounds(0, 0, 1963, 688);
contentPane = new JPanel();
setContentPane(contentPane);
contentPane.setLayout(null);
btnImpostazioni.setBounds(0, 560, 140, 140);
contentPane.add(btnImpostazioni);
btnImpostazioni.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
contentPane.add(panel5);
revalidate();
repaint();
}
});
}
public void changetext() {
btnImpostazioni.setText("yes");
}
}
//panelGestisciImpostazioni
package s;
public class panelImpostazioni extends JPanel {
private JComboBox comboboxLingua = new JComboBox();
static home h=new home();
public panelImpostazioni() {
setBounds(140, 0, 800, 560);
setLayout(null);
comboboxLingua.setBounds(100, 24, 150, 45);
comboboxLingua.setModel(new DefaultComboBoxModel(new String[] {"italiano", "inglese"}));
add(comboboxLingua);
comboboxLingua.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
h.changetext();
}
});
}
}
Thank you.
Its because when you create panel5 you have a new home created.
static home h = new home ().
So when you call changetext method you do it in a new invisible frame.
In order to make this work (it is really really bad) you have to pass your visible "home" as an argument to your panel5. Which means you have to initiate it in home's constructor and not as a field.
public panelImpostazioni(home h)
And in your combobox action listener
h.changetext ()

How to add an JPanel from an other class to an existing Frame

I have my MainWindow class where menue buttons and everything else are. In the middle of it is an Panel called content. I want to load JPanels from other classes into this field. But when i start the code below nothing shows up.
MainWindow Class:
public class MainWindow {
private JFrame frame;
private JScrollPane Content;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow window = new MainWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MainWindow() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scrollPane = new JScrollPane();
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
JPanel TopPanel = new JPanel();
scrollPane.setColumnHeaderView(TopPanel);
JLabel lblNewLabel = new JLabel("Made by " + Globals.Author);
TopPanel.add(lblNewLabel);
JButton btnHome = new JButton("Home");
TopPanel.add(btnHome);
btnHome.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
Content.add(new Home());
}
});
Content = new JScrollPane();
scrollPane.setViewportView(Content);
}
}
JPanel Class:
public class Home extends JPanelContentTemplate {
/**
* Create the panel.
*/
protected void InitializeComponents(){
setLayout(new BorderLayout(0, 0));
JPanel OptionsMenuePanel = new JPanel();
add(OptionsMenuePanel, BorderLayout.WEST);
JPanel ConentPanel = new JPanel();
add(ConentPanel, BorderLayout.CENTER);
ConentPanel.setLayout(new GridLayout(1, 2, 0, 0));
JLabel lblConnectedWith = new JLabel("Connected With:");
ConentPanel.add(lblConnectedWith);
JTextPane textServerIP = new JTextPane();
ConentPanel.add(textServerIP);
}
#Override
protected void Refresh() {
// TODO Auto-generated method stub
}
}
The InitializeComponents method comes from an Self Created Superclass:
public abstract class JPanelContentTemplate extends JPanel {
/**
* Create the panel.
*/
public JPanelContentTemplate() {
InitializeComponents();
}
protected abstract void InitializeComponents();
protected abstract void Refresh();
}
I also tried an repaint etc.
Thanks for Help
Nothing shows up because you add nothing but empty JScrollPanes to your GUI:
Content = new JScrollPane();
scrollPane.setViewportView(Content);
Here is a simple example of adding separate panels to the MainFrame. I hope it helps you.
public class SidePanel extends JPanel {
private JLabel label;
public SidePanel() {
setBorder(BorderFactory.createEtchedBorder());
label = new JLabel("Hello");
setVisible(true);
/* More Code Goes Here */
}
}
public class CenterPanel extends JPanel {
/* Center Panel Code */
}
public class MainFrame extends JFrame {
private SidePanel sidePanel;
private CenterPanel centerPanel;
public MainFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
sidePanel = new SidePanel();
centerPanel = new CenterPanel();
add(sidePanel, BorderLayout.WEST);
add(centerPanel, BorderLayout.CENTER);
setSize(300, 300);
setVisible(true);
}
}
/* Main App */
public static void main(String [] args) {
try {
/* Lambda Expression */
SwingUtitlities.InvokeLater(() -> new MainFrame());
} catch(Exception ex) {
ex.printStackTrace();
}
}

Undo the effect of method setText() of JEditorPane in one step not in three

I'm trying to undo the setText() method effect in a JEditorPane. Here is my code:
public final class UndoManagerTestForJEditorPane {
private final JEditorPane editor = new JEditorPane();
private final UndoManager undoManager = new UndoManager();
public JComponent makeUI() {
editor.setContentType("text/html");
HTMLDocument document = (HTMLDocument) editor.getDocument();
document.addUndoableEditListener(undoManager);
editor.setText("Hello");
JPanel p = new JPanel();
p.add(new JButton(new AbstractAction("undo") {
#Override
public void actionPerformed(ActionEvent e) {
if (undoManager.canUndo()) {
undoManager.undo();
}
}
}));
p.add(new JButton(new AbstractAction("redo") {
#Override
public void actionPerformed(ActionEvent e) {
if (undoManager.canRedo()) {
undoManager.redo();
}
}
}));
p.add(new JButton(new AbstractAction("setText(new Date())") {
#Override
public void actionPerformed(ActionEvent e) {
String str = new Date().toString();
editor.setText(str);
}
}));
Box box = Box.createVerticalBox();
box.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
box.add(makePanel("Default", editor));
JPanel pp = new JPanel(new BorderLayout());
pp.add(box, BorderLayout.NORTH);
pp.add(p, BorderLayout.SOUTH);
return pp;
}
private static JPanel makePanel(String title, JComponent c) {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createTitledBorder(title));
p.add(c);
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new UndoManagerTestForJEditorPane().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
The default behaviour is done with four steps:
1) Nothing is done, the cursor doesn't even move..
2) The cursor gets down with almost 10 lines under the inserted word..
3) The text get disappeared..
4) the old text appears finally..
So, instead of these steps, could we do it just only with one undo step like in this link for JTextField JTextArea setText() & UndoManager, but with JEditorPane ?
The problem the replace method for JEditorPane does not get executed when setText() is called on JEditorPane...
Please any help ?
Thank you
You could do it with a separate class (can be nested to directly access the necessary GUI elements, if you only have to do your edits with informations from one class) which extends AbstractUndoableEdit. You can save the exact old state that you want to load after one undo operation and the exact new state which you want to reload after a redo operation. You can then set the correct values in the redo and undo methods directly by overriding them in the State class. This could look like this:
public final class UndoManagerTestForJEditorPane {
private final JEditorPane editor = new JEditorPane();
private final UndoManager undoManager = new UndoManager();
public JComponent makeUI() {
editor.setContentType("text/html");
HTMLDocument document = (HTMLDocument) editor.getDocument();
//document.addUndoableEditListener(undoManager); -> Not used anymore
editor.setText("Hello");
JPanel p = new JPanel();
p.add(new JButton(new AbstractAction("undo") {
#Override
public void actionPerformed(ActionEvent e) {
if (undoManager.canUndo()) {
undoManager.undo();
}
}
}));
// New class to hold the state and load the correct string
class State extends AbstractUndoableEdit
{
String oldText;
String newText;
State(String oldText, String newText)
{
this.oldText = oldText;
this.newText = newText;
}
#Override
public void undo() throws CannotUndoException {
editor.setText(oldText);
}
#Override
public boolean canUndo() {
return true;
}
#Override
public void redo() throws CannotRedoException {
editor.setText(newText);
}
#Override
public boolean canRedo() {
return true;
}
}
p.add(new JButton(new AbstractAction("redo") {
#Override
public void actionPerformed(ActionEvent e) {
if (undoManager.canRedo()) {
undoManager.redo();
}
}
}));
p.add(new JButton(new AbstractAction("setText(new Date())") {
#Override
public void actionPerformed(ActionEvent e) {
String str = new Date().toString();
// Add a new edit by saving the old string (by calling getText) and the new string 'str'
undoManager.addEdit(new State(editor.getText(), str));
editor.setText(str);
}
}));
Box box = Box.createVerticalBox();
box.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
box.add(makePanel("Default", editor));
JPanel pp = new JPanel(new BorderLayout());
pp.add(box, BorderLayout.NORTH);
pp.add(p, BorderLayout.SOUTH);
return pp;
}
private static JPanel makePanel(String title, JComponent c) {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createTitledBorder(title));
p.add(c);
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new UndoManagerTestForJEditorPane().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}

Enable/Disable buttons on main frame from jInternalFrame in Eclipse

As I said in the title, I am writing a code for a small program in java. I used Internal Frames to implement it. The thing is I am trying to add a login option to the program. The login class is a jInternalFrame and I want it to Enable/Disable specific buttons in my main window. I tried google-ing a solution but didn't seem to find it. (Keep in mind that I'm really new to programing so I expect there might be other problems in my code I don't see at the moment).
Main Window code:
import javax.swing.JDesktopPane;
public class FereastraPrincipala extends JFrame {
private static final long serialVersionUID = 1L;
JDesktopPane jdpDesktop;
static int openFrameCount = 0;
public FereastraPrincipala() {
super("Fereastra Principala");
// Make the main window positioned as 50 pixels from each edge of the
// screen.
int inset = 50;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(inset, inset, screenSize.width - inset * 2,screenSize.height - inset * 2);
// Add a Window Exit Listener
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// Create and Set up the GUI.
jdpDesktop = new JDesktopPane();
// A specialized layered pane to be used with JInternalFrames
setContentPane(jdpDesktop);
setJMenuBar(createMenuBar());
// Make dragging faster by setting drag mode to Outline
jdpDesktop.putClientProperty("JDesktopPane.dragMode", "outline");
}
private JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu mnFile = new JMenu("File");
mnFile.setMnemonic(KeyEvent.VK_F);
JMenuItem mntmLogin = new JMenuItem("Login");
mnFile.add(mntmLogin);
mntmLogin.setMnemonic(KeyEvent.VK_N);
menuBar.add(mnFile);
mntmLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
login();
}
});
JMenuItem mntmLogout = new JMenuItem("Logout");
mnFile.add(mntmLogout);
mntmLogout.setEnabled(true);
JMenuItem mntmCreazaUser = new JMenuItem("Creaza User");
mntmCreazaUser.setMnemonic(KeyEvent.VK_C);
mnFile.add(mntmCreazaUser);
mntmCreazaUser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
creazaUser();
}
});
JMenuItem mntmExit = new JMenuItem("Exit");
mntmExit.setMnemonic(KeyEvent.VK_X);
mnFile.add(mntmExit);
mntmExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
JMenu mnAdministrator = new JMenu("Administrator");
mnAdministrator.setMnemonic(KeyEvent.VK_N);
menuBar.add(mnAdministrator);
mnAdministrator.setEnabled(true);
JMenu mnPresedinte = new JMenu("Presedinte");
mnPresedinte.setMnemonic(KeyEvent.VK_P);
menuBar.add(mnPresedinte);
mnPresedinte.setEnabled(true);
JMenuItem mnHelp = new JMenuItem("Help");
mnHelp.setMnemonic(KeyEvent.VK_H);
menuBar.add(mnHelp);
mnHelp.setEnabled(true);
mnHelp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
help();
}
});
return menuBar;
}
protected void login() {
Login frame = new Login();
frame.setVisible(true);
// Every JInternalFrame must be added to content pane using JDesktopPane
jdpDesktop.add(frame);
try {
frame.setSelected(true);
} catch (java.beans.PropertyVetoException e) {
}
}
protected void help() {
Help frame1 = new Help();
frame1.setVisible(true);
jdpDesktop.add(frame1);
try {
frame1.setSelected(true);
} catch (java.beans.PropertyVetoException e) {
}
}
protected void creazaUser() {
CreazaUser frame = new CreazaUser();
frame.setVisible(true);
jdpDesktop.add(frame);
try {
frame.setSelected(true);
} catch (java.beans.PropertyVetoException e) {
}
}
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
FereastraPrincipala frame = new FereastraPrincipala();
frame.setVisible(true);
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
}
Login class code:
import java.awt.EventQueue;
public class Login extends JInternalFrame {
private static Login instance = null;
private JTextField textField;
private JPasswordField passwordField;
public static Login getInstance(){
if(instance == null) {instance = new Login(); }
return instance;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login frame = new Login();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Login() {
super("Login", false, true, false, false);
setVisible(true);
setBounds(200, 200, 290, 173);
JPanel panel = new JPanel();
getContentPane().add(panel, BorderLayout.CENTER);
panel.setLayout(null);
JLabel lblNewLabel = new JLabel("Username:");
lblNewLabel.setBounds(22, 29, 79, 14);
panel.add(lblNewLabel);
JLabel label = new JLabel("Parola:");
label.setBounds(22, 54, 79, 14);
panel.add(label);
textField = new JTextField();
textField.setColumns(10);
textField.setBounds(123, 26, 98, 20);
panel.add(textField);
passwordField = new JPasswordField();
passwordField.setBounds(123, 51, 98, 20);
panel.add(passwordField);
JButton button = new JButton("Autentificare");
button.setBounds(80, 97, 112, 23);
panel.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String user = textField.getText();
String pass = passwordField.getText();
if(user.equals("admin") && pass.equals("admin")) {
FereastraPrincipala(mntmLogout.setEnabled(true));
FereastraPrincipala(mnAdministrator.setEnabled(true));
JOptionPane.showMessageDialog(null,"Login esuat","Login esuat",JOptionPane.ERROR_MESSAGE);
} else if (user.equals("prez") && pass.equals("prez")) {
/* FereastraPrincipala(mntmLogout.setEnabled(true)):
FereastraPrincipala(mnPresedinte.setEnabled(true)); */
JOptionPane.showMessageDialog(null,"Login esuat","Login esuat",JOptionPane.ERROR_MESSAGE);
} else { JOptionPane.showMessageDialog(null,"Login esuat","Login esuat",JOptionPane.ERROR_MESSAGE);}
}
});
}
}

How do I hide the current JPanel and show a new one with a button in Java?

I unfortunately have to use multiple windows in this program and I don't think CardLayout is going to work because I can't have any buttons constant between the different layouts. So I'm trying to code a button to hide the present JPanel (thePanel) and show a new one (thePlacebo).
I'm trying to hide thePanel in an ActionListener like this:
frame.getContentPane().remove(thePanel);
I thought this would work, but it just freezes my program as soon as I hit the button.
Here's a chunk of the code for context:
public class Reflexology1 extends JFrame{
JButton button1, button2;
JButton movingButton;
JTextArea textArea1;
int buttonAClicked, buttonDClicked;
private long _openTime = 0;
private long _closeTime = 0;
JPanel thePanel = new JPanel();
JPanel thePlacebo = new JPanel();
final JFrame frame = new JFrame("Reflexology");
public static void main(String[] args){
new Reflexology1();
}
public Reflexology1(){
frame.setSize(600, 475);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Reflexology 1.0");
frame.setResizable(false);
button1 = new JButton("Accept");
button2 = new JButton("Decline");
movingButton = new JButton("Click Me");
ListenForAcceptButton lForAButton = new ListenForAcceptButton();
ListenForDeclineButton lForDButton = new ListenForDeclineButton();
button1.addActionListener(lForAButton);
button2.addActionListener(lForDButton);
//movingButton.addActionListener(lForMButton);
JTextArea textArea1 = new JTextArea(24, 50);
textArea1.setText("Tracking Events\n");
textArea1.setLineWrap(true);
textArea1.setWrapStyleWord(true);
textArea1.setSize(15, 50);
FileReader reader = null;
try {
reader = new FileReader("EULA.txt");
textArea1.read(reader, "EULA.txt");
} catch (IOException exception) {
System.err.println("Problem loading file");
exception.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException exception) {
System.err.println("Error closing reader");
exception.printStackTrace();
}
}
}
JScrollPane scrollBar1 = new JScrollPane(textArea1, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
AdjustmentListener listener = new MyAdjustmentListener();
thePanel.add(scrollBar1);
thePanel.add(button1);
thePanel.add(button2);
thePlacebo.add(movingButton);
frame.add(thePanel);
ListenForWindow lForWindow = new ListenForWindow();
frame.addWindowListener(lForWindow);
frame.setVisible(true);
}
// Implement listeners
private class ListenForAcceptButton implements ActionListener{
public void actionPerformed(ActionEvent e){
if (e.getSource() == button1){
Calendar ClCDateTime = Calendar.getInstance();
System.out.println(ClCDateTime.getTimeInMillis() - _openTime);
_closeTime = ClCDateTime.getTimeInMillis() - _openTime;
frame.getContentPane().remove(thePanel);
}
}
}
Does anybody know what I might be doing wrong?
After removing components from a container, it goes into the invalidate state. To bring it back to the valid state you have to revalidate and repaint that. In your case you are directly adding/removing components from JFrame so depending on the Java version you can do this :
frame.revalidate(); // For Java 1.7 or above
frame.getContentPane().validate(); // For Java 1.6 or below
frame.repaint();
Here is one working example for your help :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Assignment
{
private JFrame frame;
private JPanel firstPanel;
private JPanel secondPanel;
private JButton forwardButton;
private JButton backButton;
private void displayGUI()
{
frame = new JFrame("Assignment");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
firstPanel = new JPanel();
firstPanel.setOpaque(true);
firstPanel.setBackground(Color.BLUE);
secondPanel = new JPanel();
secondPanel.setOpaque(true);
secondPanel.setBackground(Color.RED);
forwardButton = new JButton("Forward");
forwardButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
frame.remove(firstPanel);
frame.add(secondPanel);
frame.revalidate(); // For Java 1.7 or above.
// frame.getContentPane().validate(); // For Java 1.6 or below.
frame.repaint();
}
});
backButton = new JButton("Back");
backButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
frame.remove(secondPanel);
frame.add(firstPanel);
frame.revalidate(); // For Java 1.7 or above.
// frame.getContentPane().validate(); // For Java 1.6 or below.
frame.repaint();
}
});
firstPanel.add(forwardButton);
secondPanel.add(backButton);
frame.add(firstPanel);
frame.setSize(300, 300);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new Assignment().displayGUI();
}
});
}
}
correct way could be (only) by using CardLayout
otherwise have to remove JPanel from container and to call (as last code line and call only one times after all changes for container are done)
.
myJPanelsContainer#revalidate(); // in Java6 for JFrame validate()
myJPanelsContainer#repaint();

Categories