Today I have a problem..
My program make a 8x8 grid and show the coord when I click on a JButton.
BUT I refuse to use JButton and I need to go for JPanel.. But my addMouseListener isn't working so I don't know how is it possible to fix that I'm searching since 4h.....
package coordboutons;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CoordBoutons extends JFrame {
CoordBoutons() {
super("GridLayout");
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container contenant = getContentPane();
contenant.setLayout(new GridLayout(8, 8));
for (int i = 0; i < 8; i++)
for (int j = 0; j < 8; j++)
contenant.add(new CaseEchiquier(i, j));
pack();
setVisible(true);
}
**class CaseEchiquier extends JPanel** {
private int lin, col;
CaseEchiquier(int i, int j) {
lin = i;
col = j;
setPreferredSize(new Dimension(80, 75));
setBackground((i + j) % 2 == 0 ? Color.WHITE : Color.GRAY);
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out.println((char)('a' + col) + "" + (8 - lin));
}
});
}
}
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
CoordBoutons coordBoutons = new CoordBoutons();
}
}
JPanel doesn't have ActionListener capabilities. Instead, you need to use a MouseListener
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class CoordBoutons extends JFrame {
CoordBoutons() {
super("GridLayout");
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container contenant = getContentPane();
contenant.setLayout(new GridLayout(8, 8));
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
contenant.add(new CaseEchiquier(i, j));
}
}
pack();
setVisible(true);
}
class CaseEchiquier extends JPanel {
private int lin, col;
CaseEchiquier(int i, int j) {
lin = i;
col = j;
setPreferredSize(new Dimension(80, 75));
setBackground((i + j) % 2 == 0 ? Color.WHITE : Color.GRAY);
addMouseListener(new MouseAdapter() {
private Color background;
#Override
public void mousePressed(MouseEvent e) {
background = getBackground();
setBackground(Color.RED);
repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
setBackground(background);
}
});
// addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent evt) {
// System.out.println((char) ('a' + col) + "" + (8 - lin));
//
// }
// });
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame.setDefaultLookAndFeelDecorated(true);
CoordBoutons coordBoutons = new CoordBoutons();
}
});
}
}
Take a look at How to Write Mouse Listeners for more details...
The problem is that the method addActionListener does not exists for a JPanel. You should use the appropriate listener for this case (java.awt.event.MouseListener). Since MouseListener is an interface (and you don't want to implement all of its methods), you could use a MouseAdapter and override only the method(s) you need, like this:
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
System.out.println((char)('a' + col) + "" + (8 - lin));
}
});
Related
My goal is to create a list with a length controlled by another component where each item's value can be edited.
My attempt uses an editable JComboBox that has a certain number of elements. In my code below, however, the selected index keeps changing to -1, which does not allow me to modify the item. Is there a way to select and edit an item using JComboBox?
//cb is a JComboBox with elements of type ComboItem. idx is defined elsewhere.
cb.addItemListener(new ItemListener() {
#SuppressWarnings("unchecked")
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED)
idx = ((JComboBox<ComboItem>) e.getSource()).getSelectedIndex();
System.out.println("idx:"+idx);
}
});
//Pressing enter should commit changes.
cb.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
if(e.getKeyChar() == KeyEvent.VK_ENTER) {
String parse = ((JTextComponent) cb.getEditor().getEditorComponent()).getText();
parse = parse.substring(parse.lastIndexOf(":")+1).replaceAll("[^0-9]+", ""); //Processes edits.
cb.getItemAt(idx).change("Layer "+idx, Integer.parseInt(parse)); //This method should change the
System.out.println("selected item:"+cb.getSelectedItem()); // data for each item.
}
}
});
//Editing the text in the JComboBox and pressing the enter key should update the selected item.
JComboBox is not required, so feel free to suggest a different component if it is a better choice for this task.
After a day's worth of trial and error, I finally made a working solution. Instead of using a JComboBox, which was probably not designed to perform the desired task, I made a JScrollPane that adds a child JPanel every time a button is pressed. Each panel has a text field object that can be customized and a button to delete it. In my case, I added a DocumentFilter that allows positive < 5 digit integers.
I cannot figure out how to remove the spacing between the added panels before the scroll bar appears, so please comment a solution if you have one. Also, if there are any other improvements that can be made, please comment those suggestions as well.
Scroll Panel
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.JLabel;
#SuppressWarnings("serial")
public class TestScrollPane extends JPanel {
private int w,h;
private JPanel content;
private JScrollPane scroll;
private JButton add;
private JLabel getTextLabel;
private JButton getTextBtn;
/**
* Create the panel.
*/
public TestScrollPane(int width, int height) {
setLayout(null);
w = width; h = height;
scroll = new JScrollPane();
scroll.setBounds(0, 0, w, h);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
add(scroll);
content = new JPanel();
scroll.setViewportView(content);
content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
add = new JButton("+");
add.setBounds(0, h, 89, 23);
add(add);
getTextLabel = new JLabel("");
getTextLabel.setBounds(10, 425, 215, 14);
add(getTextLabel);
getTextBtn = new JButton("Get Text");
getTextBtn.setBounds(225, 425, 215, 14);
getTextBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String a[] = getText(),
b = "";
b += "[";
for(int i = 0; i < a.length - 1; i++)
b += a[i]+", ";
b += a[a.length-1]+"]";
System.out.println(b);
getTextLabel.setText(b);
}
});
add(getTextBtn);
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("adding "+content.getComponentCount());
content.add(new ScrollItem(content.getComponentCount()));
validate();
repaint();
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(w, h);
}
public String[] getText() {
String out[] = new String[content.getComponentCount()],s;
for(int i = 0; i < out.length; i++)
out[i] = (s = ((ScrollItem) content.getComponent(i)).out) == null ? "0" : s;
return out;
}
private class ScrollItem extends JPanel {
private JTextField text;
private JButton del;
private int idx;
private String out;
public ScrollItem(int id) {
idx = id;
setBounds(0, idx*20, w-5, 20);
setLayout(null);
text = new JTextField();
text.setBounds(0, 0, (w-5)*3/4, 20);
text.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
out = text.getText();
}
});
AbstractDocument d = (AbstractDocument) text.getDocument();
d.setDocumentFilter(new TextFilter(4));
del = new JButton("X");
del.setBounds((w-5)*3/4, 0, (w-5)/4, 20);
del.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
content.remove(idx);
for(int i = idx; i < content.getComponentCount(); i++)
((ScrollItem) content.getComponent(i)).moveUp();
content.validate();
content.repaint();
System.out.println("Removed "+idx);
}
});
add(text);
add(del);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(w-5, 20);
}
public void moveUp() {
idx--;
content.validate();
content.repaint();
}
}
private class TextFilter extends DocumentFilter {
private int max;
public TextFilter(int maxChars) {
max = maxChars;
}
#Override
public void insertString(FilterBypass fb, int offs, String str, AttributeSet a) throws BadLocationException {
System.out.println("insert");
if ((fb.getDocument().getLength() + str.length()) <= max && str.matches("\\d+"))
super.insertString(fb, offs, str, a);
else
showError("Length: "+((fb.getDocument().getLength() + str.length()) <= max)+" | Text: "+str.matches("\\d+")+" | Str: "+str);
}
#Override
public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a) throws BadLocationException {
System.out.println("replace");
if ((fb.getDocument().getLength() + str.length() - length) <= max && str.matches("\\d+"))
super.replace(fb, offs, length, str, a);
else
showError("Length: "+((fb.getDocument().getLength() + str.length() - length) <= max)+" | Text: "+str.matches("\\d+")+" | Str: "+str);
}
private void showError(String cause) {
JOptionPane.showMessageDialog(null, cause);
}
}
}
Test Window
import java.awt.EventQueue;
import javax.swing.JFrame;
public class TestWindow {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestWindow window = new TestWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public TestWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 435, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestScrollPane(430, 247));
}
}
Im creating a program in which I must from time to time reset a button Array and display it on a jPanel. The function below adds the jButtons to my panel and displays them perfectly the first time that it is called, but from then on, every time I call it (after emptying the jButton array and applying .removeAll() to the panel) it wont let me change the background color of the jButton. Some assistance to help me find out why this is would be great, thanks.
import java.awt.*;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import javafx.scene.layout.Border;
import javax.swing.*;
/**
*
* #author Luis
*/
public class MineSweeper extends JFrame implements ActionListener {
int int_dim = 11;
int int_cellsShown = 0;
JButton[][] arr_btnField = new JButton[int_dim][int_dim];
int[][] arr_solution = new int[int_dim][int_dim];
Color[] clr_palette = {Color.white, new Color(0X00, 0X94, 0XFF), new Color(0X00, 0X26, 0XFF), new Color(0X00, 0XAA, 0X0A), Color.red, Color.MAGENTA, new Color(0XFF, 0X00, 0X00), new Color(0X9B, 0X00, 0X00)};
boolean bool_change = false;
boolean bool_won = false;
boolean bool_firstround = false;
javax.swing.border.Border border = BorderFactory.createLineBorder(Color.darkGray, 1, true);
MenuBar menu_bar;
Menu menu;
MenuItem optionNew;
//boolean[][] arr_boolShowed=new boolean[int_dim][int_dim];
int int_mines = 8;
ArrayList<Integer> arl_field = new ArrayList<Integer>();
JPanel jpanel = new JPanel();
JPanel jpanel2 = new JPanel();
//ArrayList<Boolean> arl_boolShowed = new ArrayList<Boolean>();
/**
* #param args the command line arguments
*/
public MineSweeper() throws FontFormatException, IOException {
resetGame();
//JFrame frame = new JFrame("");
this.getContentPane().add(jpanel);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(true);
this.setTitle("Minesweeper");
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
this.setSize(500, 500);
menu_bar = new MenuBar();
menu = new Menu("File");
optionNew = new MenuItem("Win");
optionNew.addActionListener(this);
menu.add(optionNew);
menu_bar.add(menu);
this.setMenuBar(menu_bar);
}
public void resetGame() {
jpanel.removeAll();
arl_field.clear();
arr_btnField = new JButton[int_dim][int_dim];
arr_solution = new int[int_dim][int_dim];
bool_change = false;
bool_won = false;
//arl_field = new ArrayList<Integer>();
for (int i = 0; i < arr_solution.length; i++) {
for (int j = 0; j < arr_solution[i].length; j++) {
arr_solution[i][j] = 1;
}
}
jpanel.setLayout(new GridLayout(0, int_dim));//if(bool_firstround==false)jpanel.setLayout(new GridLayout(0,int_dim));
for (int i = 0; i < arr_btnField.length; i++) {
for (int j = 0; j < arr_btnField[i].length; j++) {
arr_btnField[i][j] = new JButton();////if(bool_firstround==false)arr_btnField[i][j] = new JButton();//arl_field.get(i*int_dim+j)+"");
arr_btnField[i][j].setText("");
arr_btnField[i][j].setBackground(new Color(0X00, 0X94, 0XFF));
arr_btnField[i][j].setBorder(border);
arr_btnField[i][j].setForeground(clr_palette[1]);
arr_btnField[i][j].addMouseListener(listener);
arr_btnField[i][j].setFocusable(false);
jpanel.add(arr_btnField[i][j]);
}
}
jpanel.revalidate();
jpanel.repaint();
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new MineSweeper();
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
}
});
}
MouseListener listener = new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
outerloop:
for (int i = 0; i < arr_btnField.length; i++) {
for (int j = 0; j < arr_btnField[i].length; j++) {
if (e.getSource() == arr_btnField[i][j]) {
if (SwingUtilities.isLeftMouseButton(e)) {
labelText(i, j);
}
if (SwingUtilities.isRightMouseButton(e)) {
arr_btnField[i][j].setBackground(Color.red);
}
//bool_won=false;
break outerloop;
}
}
}
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
if (bool_won == true)
gameWon();
}
#Override
public void mouseExited(MouseEvent e) {
}
};
public void labelText(int i, int j) {
if (bool_won == false) {
arr_btnField[i][j].setText("1");
arr_btnField[i][j].setBackground(Color.white);
if (arr_btnField[i][j].getBorder() == border) {
int_cellsShown++;
System.out.println("Cells shown: " + int_cellsShown);
if (int_cellsShown >= (int_dim * int_dim - int_mines)) {
bool_won = true;
}
}
if (bool_won == false)
arr_btnField[i][j].setBorder(BorderFactory.createLineBorder(Color.darkGray, 1, true));
}
}
public void gameWon() {
int dialogResult = JOptionPane.showConfirmDialog(null, "You Won! Do you want to start a new game?", "Congratulations!", JOptionPane.YES_NO_OPTION);
if (dialogResult == JOptionPane.YES_OPTION) {
bool_won = false;
int_cellsShown = 0;
resetGame();
}
}
#Override
public void actionPerformed(ActionEvent e) {
int_cellsShown = 0;
int_dim++;
resetGame();
for (int i = 0; i < arr_btnField.length; i++) {
for (int j = 0; j < arr_btnField[i].length; j++) {
arr_btnField[i][j].setBackground(Color.red);
}
}
}
}
Display after the first time:
Display after the second time:
I invoke .revalidate in the fourth line of the method.
That doesn't do anything since there on no components added to the panel. The revalidate() needs to be done AFTER the components have been added.
The displayed panel is not jpanel, the displayed panel is jpanel2, thats why I assign jpanel2 to the value of jpanel in the end of the method.
You can't just change a reference and expect the components to be moved from one panel to another.
The components need to be added to the panel that is added to the GUI.
Edit:
First of all Swing components start with "J". Don't use AWT components (MenuBar, Menu, MenuItem) in a Swing application.
The problem is your LAF:
new MineSweeper();
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
The components are created with the current LAF. When you first create the game, the default LAF is used to create all the buttons (and other components). This LAF allows you to change the background color of the buttons.
However, then you change the LAF. So when you reset the game board the buttons are now created with the System LAF. This LAF apparently does not allow you to change the background color of the button.
This should be easy to test. Create a GUI:
//UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
JButton button = new JButton("testing");
button.setBackground(Color.RED);
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( button );
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
First test the code as above to see if the background of the button changes.
Then uncomment the LAF change and retest.
A possible solution so you are not dependent on the LAF is to use an Icon to represent the background color of the button. Then you can center any text on top of the Icon. Something like:
import java.awt.*;
import javax.swing.*;
public class ColorIcon implements Icon
{
private Color color;
private int width;
private int height;
public ColorIcon(Color color, int width, int height)
{
this.color = color;
this.width = width;
this.height = height;
}
public int getIconWidth()
{
return width;
}
public int getIconHeight()
{
return height;
}
public void paintIcon(Component c, Graphics g, int x, int y)
{
g.setColor(color);
g.fillRect(x, y, width, height);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI()
{
JPanel panel = new JPanel( new GridLayout(2, 2) );
for (int i = 0; i < 4; i++)
{
Icon icon = new ColorIcon(Color.RED, 50, 50);
JLabel label = new JLabel( icon );
label.setText("" + i);
label.setHorizontalTextPosition(JLabel.CENTER);
label.setVerticalTextPosition(JLabel.CENTER);
panel.add(label);
}
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(panel);
f.setSize(200, 200);
f.setLocationRelativeTo( null );
f.setVisible(true);
}
}
Yep, I too just noticed, that the problem is here:
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new MineSweeper();
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
}
});
}
If you comment out the UIManager line, your code works. This line is only valid after the GUI has been created, and so doesn't take effect until new components are created. Note that I was working on minimizing your code to discover this, and was cutting out code to see what caused the problem until this was all that was left.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.UIManager;
#SuppressWarnings("serial")
public class MineSweeper extends JFrame implements ActionListener {
private static final Color BTN_COLOR = new Color(0X00, 0X94, 0XFF);
int int_dim = 11;
JButton[][] arr_btnField = new JButton[int_dim][int_dim];
JMenuBar menu_bar;
JMenu menu;
JMenuItem optionNew;
JPanel jpanel = new JPanel();
public MineSweeper() {
resetGame();
this.getContentPane().add(jpanel);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(true);
this.setTitle("Minesweeper");
menu_bar = new JMenuBar();
menu = new JMenu("File");
menu.setMnemonic(KeyEvent.VK_F);
optionNew = new JMenuItem("Win");
optionNew.setMnemonic(KeyEvent.VK_W);
optionNew.addActionListener(this);
menu.add(optionNew);
menu_bar.add(menu);
this.setJMenuBar(menu_bar);
this.setPreferredSize(new Dimension(500, 500));
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public void resetGame() {
jpanel.removeAll();
arr_btnField = new JButton[int_dim][int_dim];
jpanel.setLayout(new GridLayout(0, int_dim));
for (int i = 0; i < arr_btnField.length; i++) {
for (int j = 0; j < arr_btnField[i].length; j++) {
arr_btnField[i][j] = new JButton();
arr_btnField[i][j].setBackground(BTN_COLOR);
jpanel.add(arr_btnField[i][j]);
}
}
jpanel.revalidate();
jpanel.repaint();
}
#Override
public void actionPerformed(ActionEvent e) {
resetGame();
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new MineSweeper();
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
}
});
}
}
i want to make a JButton that can be moved with keyboard arrows inside a grid panel. Any ideas on how to make this happen ?
Here is what i have done so far, but it does not really works
button.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
System.out.println("KEY ^$$#$#$##$ " + key);
int position = 0;
int previousPosition = 0;
int counter = 0;
position = Integer.parseInt(button.getName());
int nextPosition = position;
if (key == KeyEvent.VK_LEFT) {
nextPosition = nextPosition - 1;
previousPosition = position;
System.out.println("PREVIOUS POSITION: " + position);
bt[1].setVisible(false);
System.out.println("POSITION: " + position);
button.setName("" + nextPosition);
bt[nextPosition].add(button);
}
else if (key == KeyEvent.VK_DOWN) {
counter++;
if (counter == 1) {
nextPosition = nextPosition + 6;
}
else if (counter == 2) {
nextPosition = nextPosition + 12;
}
else {
nextPosition = 18;
}
System.out.println("next position:" + nextPosition);
System.out.println("counter: " + counter);
System.out.println("DOWN ARROW");
System.out.println("DOWN ARROW");
System.out.println("POSITION VALUE: " + nextPosition);
bt[previousPosition].setVisible(false);
System.out.println("POSITION: " + nextPosition);
button.setName("" + nextPosition);
bt[nextPosition].add(button);
System.out.println("end");
}
}
#Override
public void keyReleased(KeyEvent e) {
}
});
Thanks for your help
Well, it depends.
I would, how ever, recommend using Key Bindings over KeyListener as it doesn't suffer from focus issues.
This basically use a GridLayout and simply changes the z-order of the button...
You could achieve something similar with GridBagLayout with a little more work, but which would result in more flexible layout
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.LineBorder;
public class MoveButtons {
public static void main(String[] args) {
new MoveButtons();
}
public MoveButtons() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JButton button;
public TestPane() {
setLayout(new GridLayout(4, 4));
button = new JButton("...");
add(button);
for (int index = 0; index < (4 * 4) - 1; index++) {
JPanel panel = new JPanel();
panel.setBorder(new LineBorder(Color.GRAY));
add(panel);
}
requestFocus();
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "left");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "right");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "up");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "down");
am.put("left", new MoveAction(-1));
am.put("right", new MoveAction(1));
am.put("down", new MoveAction(4));
am.put("up", new MoveAction(-4));
}
public class MoveAction extends AbstractAction {
private int delta;
public MoveAction(int delta) {
this.delta = delta;
}
#Override
public void actionPerformed(ActionEvent e) {
int index = getComponentZOrder(button);
index += delta;
if (index < 0) {
index = 0;
} else if (index >= getComponentCount()) {
index = getComponentCount() - 1;
}
setComponentZOrder(button, index);
revalidate();
}
}
}
}
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MoveButton extends JFrame {
JButton button;
JPanel[] p = new JPanel[100];
int k = 0;
public MoveButton() {
super();
button = new JButton("G");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
requestFocusInWindow();
}
});
JPanel panel = new JPanel(new GridLayout(10, 10));
for (int i = 0; i < 100; i++) {
p[i] = new JPanel(new BorderLayout());
p[i].setBorder(BorderFactory.createLineBorder(Color.RED));
panel.add(p[i]);
}
p[0].add(button);
setFocusable(true);
requestFocusInWindow();
addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
try {
if (k <= 99 && k >= 0) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
if (k + 1 <= 99) {
p[++k].add(button);
}
repaint();
} else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
if (k - 1 >= 0) {
p[--k].add(button);
}
repaint();
} else if (e.getKeyCode() == KeyEvent.VK_UP) {
if (k - 10 >= 0) {
p[k -= 10].add(button);
}
repaint();
} else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
if (k + 10 <= 99) {
p[k += 10].add(button);
}
repaint();
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
#Override
public void keyReleased(KeyEvent e) {
}
});
setSize(600, 600);
add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new MoveButton();
}
}
I'm trying to show and hide a panel during run time, so I call the methods from another class:
Con.Action(1);
to this method:
public void Action(int whichPanel) {
if (whichPanel == 1) {
if (frame.Data.isVisible()) {
frame.Data.setVisible(false);
// frame.splitPaneSec.remove(frame.Data);
} else {
System.out.println(".....");
//frame.Data.setVisible(false);
frame.Data.setVisible(true);
//frame.getContentPane().validate();
//frame.revalidate();
//frame.repaint();
//frame.pack();
}
}
So far i'm able to hide a panel but I can't show it again once I hidden it.
I've tried many ways some of them are commented out.
Any help is appreciated, cheers
I think I would rather remove and add it back.
parent.remove(dataPanel);
parent.validate();
parent.repaint();
parent.add(dataPanel);
parent.validate();
parent.repaint();
I highly recommed you to use enums for Tasks like this:
public void Action(int whichPanel) {
if (whichPanel == 1) {}
//Better;
public void Action(enumType myPanel){
if(myPanel == enumType.LoginScreen){}
with `
public enum enumType
{
LoginScreen,EditScreen //...
}`
You can hide and show Enums if you perfom the setVisible method directly on the Panel you want to show:
public void showLoginScreen()
{
loginPanel.setVisible(true);
registerMenu.setVisible(false);
}
The issue was because after setting the component back to visible
it was required to GUIClass.splitPane.setDividerLocation(157);
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
public class HidePanel extends JFrame {
private static final int PANEL_HEIGHT = 50;
private static final int INITIAL_PANEL_WIDTH = 50;
private static final int TIMER_INTERVAL = 1;
private static final int PIXEL_DELTA = 2;
private Dimension panelDimension = new Dimension(INITIAL_PANEL_WIDTH, PANEL_HEIGHT);
private int vertOffset = -PANEL_HEIGHT;
private Timer showTimer = new HidePanel.ShowPanelTimer();
private Timer hideTimer = new HidePanel.HidePanelTimer();
static JLayeredPane lpane = new JLayeredPane();
JPanel panel = new JPanel();
public HidePanel() {
setBackground(Color.BLACK);
setLayout(null);
panel.setBounds(1200, 50, 100, 600);
panel.setBorder(new TitledBorder(new EtchedBorder(), "Hide"));
panel.add(new JButton("Click Me"));
lpane.add(panel);//, //new Integer(0), 0);
add(panel);
addMouseMotionListener(new MouseMotionListener() {
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
final int height = e.getY() - 100 ;
if (height < 50 && !showTimer.isRunning() && !panel.isVisible()) {
showTimer.start();
} else if (height > PANEL_HEIGHT + 5 && !hideTimer.isRunning() && panel.isVisible()) {
hideTimer.start();
}
}
});
}
public static void main(String args[]) {
HidePanel h = new HidePanel();
h.setSize(1350, 700);
h.setVisible(true);
h.add(lpane, BorderLayout.CENTER);
}
private void positionPanel(final int offset) {
int panelWidth = getWidth();
System.out.println(" offset = " + offset);
panelDimension.setSize(panelWidth, PANEL_HEIGHT);
//panel.setBounds(insets.left, offset + insets.top, size.width, size.height);
}
private class ShowPanelTimer extends Timer implements ActionListener {
ShowPanelTimer() {
super(TIMER_INTERVAL, null);
addActionListener(this);
}
public void start() {
vertOffset = -PANEL_HEIGHT;
panel.setVisible(true);
super.start();
}
public void actionPerformed(ActionEvent e) {
if (vertOffset <= 0) {
positionPanel(vertOffset);
} else {
showTimer.stop();
}
vertOffset += PIXEL_DELTA;
}
}
private class HidePanelTimer extends Timer implements ActionListener {
HidePanelTimer() {
super(TIMER_INTERVAL, null);
addActionListener(this);
}
public void stop() {
panel.setVisible(false);
super.stop();
}
public void actionPerformed(ActionEvent e) {
if (vertOffset >= (-PANEL_HEIGHT)) {
vertOffset -= PIXEL_DELTA;
positionPanel(vertOffset);
} else {
hideTimer.stop();
}
}
}
}
I'm new to Java and I can't seem to fix this bug with Translucent backgrounds.
Whenever I change parts of my panel it draws the changes as well as some random pictures of the window.
Clearer pictures of the bug
http://shujin.homelinux.net/fong/Working.jpg
http://shujin.homelinux.net/fong/Bugged.jpg
Here is a link to the full working project so you can clearly see the bug. Just give it a minute to load my server is slow http://fong.shujindesigns.net
I made this smaller version of the bug so you can test.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.MouseEvent;
public class Example1 extends JApplet implements MouseListener {
Container Con = getContentPane();
JPanel panel1 = new JPanel(new GridLayout(5, 5, 0, 0));
JPanel[][] panel2 = new JPanel[5][5];
JLabel[] label = new JLabel[25];
Color color;
int count = 0;
public void init() {
int col = 0;
int row = 0;
color = new Color(0.00f, 0.24f, 0.70f, 0.50f);
for (int i = 0; i < 25; i++) {
if (col > 4) {
col = 0;
row++;
}
label[i] = new JLabel("test");
label[i].addMouseListener(this);
panel2[col][row] = new JPanel();
panel2[col][row].add(label[i]);
color = new Color(0.00f, 0.24f, 0.70f, 0.20f);
panel2[col][row].setBackground(color);
label[i].setBorder(BorderFactory.createLineBorder(Color.red));
panel1.add(panel2[col][row]);
color = new Color(0.50f, 0.24f, 0.10f, 0.20f);
panel1.setBackground(color);
col++;
}
Con.add(panel1);
panel1.setOpaque(false);
label[5].setText("test2");
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
label[5].setText("Test 3" + count);
count++;
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
}
}
In the mouseClicked event, add "repaint()"
If that doesn't work, try invalidate(), repaint()
public void mouseClicked(MouseEvent e) {
label[5].setText("Test 3" + count);
count++;
//revalidate();
repaint();
}