why does my code not show both frame.add? - java

the script works fine for dragging around one image but if I try to get two of them going at once it acts as if the class can only be called once? here is the code where i am adding two imageicons , but only one is showing:
import java.awt.*;
import javax.swing.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseAdapter;
public class TestMouseDrag {
public static void main(String[] args) {
new TestMouseDrag();
}
public TestMouseDrag() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new DragMyIcon("C:\\Users\\anon\\Desktop\\Hobbit.png")).setLocation(100, 100);
frame.add(new DragMyIcon("C:\\Users\\anon\\Desktop\\alien.png")).setLocation(100, 100)
frame.pack();
frame.setSize(700,700);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class DragMyIcon extends JPanel {
public static final long serialVersionUID = 172L;
private JLabel label;
public DragMyIcon(String path) {
setLayout(null);
ImageIcon icon = null;
icon = new ImageIcon(path);
label = new JLabel(icon);
label.setBounds(0,0,100, 100);
label.setHorizontalAlignment(JLabel.CENTER);
label.setVerticalAlignment(JLabel.CENTER);
add(label);
MouseHandler handler = new MouseHandler();
label.addMouseListener(handler);
label.addMouseMotionListener(handler);
}
}
protected class MouseHandler extends MouseAdapter {
private boolean active = false;
private int xDisp;
private int yDisp;
#Override
public void mousePressed(MouseEvent e) {
active = true;
JLabel label = (JLabel) e.getComponent();
xDisp = e.getPoint().x - label.getLocation().x;
yDisp = e.getPoint().y - label.getLocation().y;
label.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
}
#Override
public void mouseReleased(MouseEvent e) {
active = false;
JLabel label = (JLabel) e.getComponent();
label.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
#Override
public void mouseDragged(MouseEvent e) {
if (active) {
JLabel label = (JLabel) e.getComponent();
Point point = e.getPoint();
label.setLocation(point.x - xDisp, point.y - yDisp);
label.invalidate();
label.repaint();
}
}
#Override
public void mouseMoved(MouseEvent e) {
}
}}

Your code does not respect the layout managers that it is using -- BorderLayout. When you add a component to a BorderLayout using container without specifying position, it is placed by default BorderLayout.CENTER and covers anything added previously.
Solution: read up on the layout managers including BorderLayout to see how to use them.
Also, you're probably better off not adding two DragMyIcon objects, but rather changing DragMyIcon so that it allows for multiple JLabels.

Related

How can I open a JInternalFrame inside a panel (inside parent) from another child JInternalFrame?

I have 3 frames, Main (as the parent) and 2 JInternalFrames (F1 and F2 as children). When a button (inside parent) is pressed, I make an instance of F1 and send it as a parameter to ShowIntrlFrame() so F1 can be displayed inside frmContainter. My question here is, how can I open F2 from F1 and display it on frmContrainer (which is in the Main frame)?
public class Main extends javax.swing.JFrame{
public Main(){
}
private void btnOpenFrmActionPerformed(java.awt.event.ActionEvent evt) {
F1 f1 = new F1();
frmContainer(f1);
}
}
public void ShowIntrlFrame(JInternalFrame f){
f.setSize(1100, 620);
f.setLocation(0, 0);
f.setVisible(true);
frmContainer.removeAll();
frmContainer.add(f, BorderLayout.CENTER);
frmContainer.revalidate();
frmContainer.repaint();
}
What I would do is follow a delegation pattern via dependency injection.
This is, I would "delegate" the functionality need to generate and show the window to some other class and then "inject" that into the workflow as required
I'd start with a concept of a "window manager"...
public interface WindowManager {
enum Window {
FIRST, SECOND;
}
public void openWindow(Window window);
}
At the moment, this is pretty basic and just opens a specified window. The nice thing about this, is we don't care if it's a JInternalFrame or JFrame which gets generated, that's not the callers responsibility.
Next, we make a implementation which supports JDesktopPane
public class DesktopWindowManage implements WindowManager {
private JDesktopPane desktopPane;
private int initialX = 0;
private int initialY = 0;
public DesktopWindowManage(JDesktopPane desktopPane) {
this.desktopPane = desktopPane;
}
public JDesktopPane getDesktopPane() {
return desktopPane;
}
#Override
public void openWindow(Window window) {
JInternalFrame frame = new JInternalFrame(window.name(), true, true, true, true);
frame.setContentPane(makeContentFor(window));
frame.pack();
frame.setLocation(initialX, initialY);
frame.setVisible(true);
try {
frame.setSelected(true);
} catch (PropertyVetoException ex) {
}
desktopPane.add(frame);
frame.toFront();
initialX += 20;
initialY += 20;
}
protected JPanel makeContentFor(Window window) {
switch (window) {
case FIRST: return new FirstPane(this);
case SECOND: return new SecondPane();
}
return null;
}
}
Now, important to note, this class is acting as kind of factory, in that it's generating the content view and JInternalFrame. I'd probably consider making a "content factory" which could be injected into this which would then create the content based on the desired destination, but that's probably getting a little more complicated then is required right now.
Now, before you ask, the actual content is based on JPanel, for example...
public class FirstPane extends JPanel {
public FirstPane(WindowManager windowManager) {
setBorder(new EmptyBorder(32, 32, 32, 32));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = gbc.REMAINDER;
add(new JLabel("I am first"), gbc);
JButton showSecond = new JButton("Show second");
showSecond.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
windowManager.openWindow(WindowManager.Window.SECOND);
}
});
add(showSecond, gbc);
}
}
public class SecondPane extends JPanel {
public SecondPane() {
setBorder(new EmptyBorder(32, 32, 32, 32));
setLayout(new GridBagLayout());
add(new JLabel("I am second"));
}
}
Why? Because it's a JPanel can be added to any container and, generally, we don't care if it's a JInternalFrame or JFrame.
And finally, some kind of "starting point"....
public class MainPane extends JPanel {
private WindowManager windowManager;
private JDesktopPane desktopPane;
public MainPane() {
setLayout(new BorderLayout());
JButton open = new JButton("Open");
desktopPane = new JDesktopPane() {
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
};
windowManager = new DesktopWindowManage(desktopPane);
add(open, BorderLayout.NORTH);
add(desktopPane);
open.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
windowManager.openWindow(WindowManager.Window.FIRST);
}
});
}
}
Runnable example...
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyVetoException;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new MainPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public interface WindowManager {
enum Window {
FIRST, SECOND;
}
public void openWindow(Window window);
}
public class DesktopWindowManage implements WindowManager {
private JDesktopPane desktopPane;
private int initialX = 0;
private int initialY = 0;
public DesktopWindowManage(JDesktopPane desktopPane) {
this.desktopPane = desktopPane;
}
public JDesktopPane getDesktopPane() {
return desktopPane;
}
#Override
public void openWindow(Window window) {
JInternalFrame frame = new JInternalFrame(window.name(), true, true, true, true);
frame.setContentPane(makeContentFor(window));
frame.pack();
frame.setLocation(initialX, initialY);
frame.setVisible(true);
try {
frame.setSelected(true);
} catch (PropertyVetoException ex) {
}
desktopPane.add(frame);
frame.toFront();
initialX += 20;
initialY += 20;
}
protected JPanel makeContentFor(Window window) {
switch (window) {
case FIRST: return new FirstPane(this);
case SECOND: return new SecondPane();
}
return null;
}
}
public class MainPane extends JPanel {
private WindowManager windowManager;
private JDesktopPane desktopPane;
public MainPane() {
setLayout(new BorderLayout());
JButton open = new JButton("Open");
desktopPane = new JDesktopPane() {
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
};
windowManager = new DesktopWindowManage(desktopPane);
add(open, BorderLayout.NORTH);
add(desktopPane);
open.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
windowManager.openWindow(WindowManager.Window.FIRST);
}
});
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.dispose();
}
}
public class FirstPane extends JPanel {
public FirstPane(WindowManager windowManager) {
setBorder(new EmptyBorder(32, 32, 32, 32));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = gbc.REMAINDER;
add(new JLabel("I am first"), gbc);
JButton showSecond = new JButton("Show second");
showSecond.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
windowManager.openWindow(WindowManager.Window.SECOND);
}
});
add(showSecond, gbc);
}
}
public class SecondPane extends JPanel {
public SecondPane() {
setBorder(new EmptyBorder(32, 32, 32, 32));
setLayout(new GridBagLayout());
add(new JLabel("I am second"));
}
}
}
But wait, there's more...
Currently, if you tap "Open" or "Show second" multiple times, you get a bunch of new windows. This may or may not be desirable, but could be easily fixed via the WindowManager, in fact, you could create different WindowManagers based on your needs, for example...
public class DesktopWindowManage implements WindowManager {
private JDesktopPane desktopPane;
private int initialX = 0;
private int initialY = 0;
private Map<Window, JInternalFrame> windowCache = new HashMap<>();
public DesktopWindowManage(JDesktopPane desktopPane) {
this.desktopPane = desktopPane;
}
public JDesktopPane getDesktopPane() {
return desktopPane;
}
#Override
public void openWindow(Window window) {
JInternalFrame frame = windowCache.get(window);
if (frame == null) {
frame = new JInternalFrame(window.name(), true, true, true, true);
frame.setContentPane(makeContentFor(window));
windowCache.put(window, frame);
frame.pack();
frame.setLocation(initialX, initialY);
frame.setVisible(true);
desktopPane.add(frame);
initialX += 20;
initialY += 20;
}
try {
frame.setSelected(true);
} catch (PropertyVetoException ex) {
}
frame.toFront();
}
protected JPanel makeContentFor(Window window) {
switch (window) {
case FIRST:
return new FirstPane(this);
case SECOND:
return new SecondPane();
}
return null;
}
}

How to make a class run after two buttons are pressed

I am making my first game, and the last time I asked this question, I kinda didn't explain it very well. Basically, below is the opening screen of the game. I know, not very good, but it is just a rough draft. Then I also built the game.
There are two buttons in the opening screen, for it is a 2 player game. Both players must click ready, and then I want to program to end, and to start the second program. However I'm not sure how to do that.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class OpeningScreen {
JFrame frame;
JPanel main;
JButton ready1;
JButton ready2;
JPanel bottom;
JLabel label;
public OpeningScreen(){
UIManager.put("Button.background", Color.cyan);
UIManager.put("Button.foreground", Color.magenta);
UIManager.put("ToolTip.background", Color.magenta);
frame=new JFrame("Super Tuesday");
main=new JPanel();
ready1=new JButton("CLICK IF READY");
ready2=new JButton("CLICK IF READY");
label=new JLabel("SUPER TUESDAY");
bottom=new JPanel();
label.setFont(label.getFont().deriveFont(50.0f));
frame.setSize(480, 800);
frame.setLayout(new BorderLayout());
frame.add(main, BorderLayout.CENTER);
bottom.setLayout(new BorderLayout());
ready1.setToolTipText("CLICK ME TO START THE GAME");
ready2.setToolTipText("CLICK ME TO START THE GAME");
main.setBackground(Color.gray);
label.setForeground(Color.white);
ready1.setFont(ready1.getFont().deriveFont(20.0f));
ready2.setFont(ready2.getFont().deriveFont(20.0f));
ready1.setForeground(Color.pink);
ready2.setForeground(Color.pink);
ready1.setPreferredSize(new Dimension(240,150 ));
ready2.setPreferredSize(new Dimension(240, 150));
bottom.setPreferredSize(new Dimension(600, 150));
main.setLayout(new FlowLayout());
main.add(label, BorderLayout.NORTH);
frame.add(bottom, BorderLayout.SOUTH);
bottom.add(ready1, BorderLayout.WEST);
bottom.add(ready2, BorderLayout.EAST);
MyMouseManager1 mmm1=new MyMouseManager1();
MyMouseManager2 mmm2=new MyMouseManager2();
ready1.addMouseListener(mmm1);
ready2.addMouseListener(mmm2);
frame.setVisible(true);
}
class MyMouseManager1 implements MouseListener{
public void mouseClicked(MouseEvent e) {
ready1.setBackground(Color.green);
ready1.setForeground(Color.white);
ready1.setText("READY!");
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
}
}
class MyMouseManager2 implements MouseListener{
public void mouseClicked(MouseEvent e) {
ready2.setBackground(Color.green);
ready2.setForeground(Color.white);
ready2.setText("READY!");
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
}
}
public static void main(String[] args){
OpeningScreen smartie=new OpeningScreen();
}
}
Here is the second program. Please don't copy. heh.
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.applet.Applet;
public class Clickasfastasyoucan extends java.applet.Applet{
private JFrame w;
private JPanel b;
private Button p;
private JPanel d;
private int times;
private JLabel number;
JPanel n;
JFrame x;
public Clickasfastasyoucan() {
x=new JFrame(" ");
n=new JPanel();
times=0;
number=new JLabel("How fast can you click?");
w = new JFrame("My Smart Button");
w.setSize(1500, 1000);
b = new JPanel();
p = new Button("Swipe as fast as you can");
w.setSize(500, 500);
b.setPreferredSize(new Dimension(1000,1500));
d=new JPanel();
w.add(b);
b.add(p);
b.setLayout(new GridLayout(1, 1));
b.add(number, BorderLayout.CENTER);
d.setSize(500, 500);
MyMouseManager mmm = new MyMouseManager();
p.addMouseListener(mmm);
p.addMouseMotionListener(mmm);
p.setForeground(Color.white);
p.setBackground(Color.black);
p.setFont(p.getFont().deriveFont(20.0f));
p.setFont(p.getFont().deriveFont(20.0f));
b.setSize(600, 600);
w.setVisible(true);
}
class MyMouseManager implements MouseListener, MouseMotionListener {
public void mouseClicked(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
n.setBackground(Color.blue);
x.add(n);
x.setSize(500, 500);
n.setSize(500, 500);
x.setVisible(true);
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
n.setBackground(Color.blue);
}
public void mouseExited(MouseEvent e) {
n.setBackground(Color.white);
}
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {times++;
number.setFont(number.getFont().deriveFont(100.0f));
number.setText(" "+times+" ");
if (times>=100&&times<999){
b.setBackground(Color.red);
number.setFont(number.getFont().deriveFont(80.0f));
times=times+1;
}
if(times>=1000&&times<10000){
b.setBackground(Color.green);
number.setFont(number.getFont().deriveFont(70.0f));
times=times+4;
}
if(times>=10000&&times<50000){
b.setBackground(Color.yellow);
number.setFont(number.getFont().deriveFont(70.0f));
times=times+100;
}if(times>=50000&&times<500000){
b.setBackground(Color.blue);
number.setFont(number.getFont().deriveFont(70.0f));
times=times+500;
}
if(times>=500000&&times<4999999){
b.setBackground(Color.pink);
number.setFont(number.getFont().deriveFont(40.0f));
times=times+1000;
}
if(times>=5000000){
b.setBackground(Color.orange);
number.setFont(number.getFont().deriveFont(20.0f));
number.setText("WOW! YOU WON. CHECK THE OUTPUT TO SEE HOW YOU SCORED!");
System.out.println("1 day: Are you still there?");
System.out.println("24 hour: Snail speed");
System.out.println("15 hours: Fail");
System.out.println("5 hours: Slow Fingers");
System.out.println("1 hour: Fast Fingers");
System.out.println("30 minutes: Champion");
System.out.println("15 minutes: You beat me!");
System.out.println("2 minutes: Cheater");
System.out.println("1 minute: Speed of Light");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("___________________________-");
}
}
}
public static void main(String[] args) {
Clickasfastasyoucan clickgame= new Clickasfastasyoucan();
}
}
I want this one to replace the first program. I'm not sure how to even start with this though, since this is my first attempt at any game, or anything beyond a one class program.
No, you really don't want a java.awt.Applet to replace a JFrame, trust me. They're both used in two vastly different situations, and while the Swing library that underlies JFrames is about 4 years out of date, the AWT library that underlies java.awt.Applet is about 20 years out of date. Just stay clear of Applet.
Instead your GUI classes should be geared towards creating JPanels, which can then be placed into JFrames or JDialogs, or JTabbedPanes, or swapped via CardLayouts, wherever needed. This will greatly increase the flexibility of your GUI coding, and in fact this is what I recommend -- that you swap views via a CardLayout.
Also -- don't use MouseListeners for your JButton listeners but instead use ActionListeners. MouseListeners won't respond to space bar presses, won't be disabled if the button becomes disabled, and can be capricious if you base behavior on the mouseClicked method. Use the proper tool for the job: ActionListeners, or even better, Actions.
For example:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.geom.AffineTransform;
import javax.swing.*;
public class MainGui extends JPanel {
private CardLayout cardLayout = new CardLayout();
private StartUpPanel startUpPanel = new StartUpPanel(this);
private GamePanel gamePanel = new GamePanel(this);
public MainGui() {
setLayout(cardLayout);
add(startUpPanel, startUpPanel.getName());
add(gamePanel, gamePanel.getName());
}
public void nextCard() {
cardLayout.next(this);
}
private static void createAndShowGui() {
MainGui mainPanel = new MainGui();
JFrame frame = new JFrame("MainGui");
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 StartUpPanel extends JPanel {
public static final String CLICK_IF_READY = "Click If Ready";
public static String SUPER_TUESDAY = "SUPER TUESDAY";
public static final String READY = "READY";
public static final int MAX_READY = 2;
private static final float TITLE_FONT_POINTS = 40f;
public static final String START_UP_PANEL = "Startup Panel";
private static final int PREF_W = 600;
private static final int PREF_H = PREF_W;
private int readyCount = 0;
private MainGui mainGui;
public StartUpPanel(MainGui mainGui) {
this.mainGui = mainGui;
setName(START_UP_PANEL);
JLabel titleLabel = new JLabel(SUPER_TUESDAY, SwingConstants.CENTER);
titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, TITLE_FONT_POINTS));
JButton button1 = new JButton(new StartupAction());
JButton button2 = new JButton(new StartupAction());
button1.setFont(button1.getFont().deriveFont(Font.BOLD, TITLE_FONT_POINTS));
button2.setFont(button1.getFont());
JPanel southPanel = new JPanel(new GridLayout(1, 0));
southPanel.add(button1);
southPanel.add(button2);
setLayout(new BorderLayout());
add(titleLabel, BorderLayout.CENTER);
add(southPanel, BorderLayout.PAGE_END);
}
#Override
public Dimension getPreferredSize() {
Dimension superSize = super.getPreferredSize();
if (isPreferredSizeSet()) {
return superSize;
}
int prefW = Math.max(superSize.width, PREF_W);
int prefH = Math.max(superSize.height, PREF_H);
return new Dimension(prefW, prefH);
}
private class StartupAction extends AbstractAction {
public StartupAction() {
super(CLICK_IF_READY);
}
#Override
public void actionPerformed(ActionEvent e) {
if (getValue(NAME).equals(CLICK_IF_READY)) { // check if button active
putValue(NAME, READY); // swap button's name
((AbstractButton) e.getSource()).setFocusable(false); // lose focus
readyCount++; // increment ready count.
if (readyCount >= MAX_READY) { // if all buttons pushed
mainGui.nextCard(); // tell main GUI to swap cards
}
}
}
}
}
// simple mock class to represent the game
class GamePanel extends JPanel {
public static final String GAME = "Game";
private static final float FONT_POINTS = 30F;
private MainGui mainGui;
public GamePanel(MainGui mainGui) {
this.mainGui = mainGui;
setName(GAME);
JLabel label = new JLabel(GAME, SwingConstants.CENTER);
label.setFont(label.getFont().deriveFont(Font.BOLD, FONT_POINTS));
setLayout(new GridBagLayout());
add(label);
}
}

Creating GUI with using border layout Swing

I'm trying to create a GUI with java. My gui will be simple. You can see what I want from here : http://sketchtoy.com/64839370
In order to do that, I have decided to use BorderLayout as suggested on the web. I have two Jpanel object and I have put them into jFrame whose layout is borderlayout. You can see my simplified code below :
private Display display= new Display(); // Display extends JPanel
public Simulation()
{
super();
// frame settings
setTitle("Label of JFrame ");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setBounds(100,100,1094,560);
contentPane=this.getContentPane();
setResizable(false);
contentPane.setLayout(new BorderLayout());
try {
LeftPanelLogo=ImageIO.read(new File("logo.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// generate left panel (information panel)
leftPanel=new JPanel(){
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d=(Graphics2D)g;
g2d.drawImage(LeftPanelLogo, 10, 250, null);
}
};
//leftPanel.setLayout(null);
// add panels to contentPane
leftPanel.setBackground(Color.WHITE);
display.setBackground(Color.BLACK);
contentPane.add(leftPanel,BorderLayout.WEST);
contentPane.add(display,BorderLayout.CENTER);
}
In Display class constructor I have only the following code:
try
{
bgPicture = ImageIO.read(new File("bg.jpg"));
}
catch (IOException e)
{
e.printStackTrace();
}
When I run the code, I saw that almost all the screen is fulfilled with the panel which is on the center, and I could not see the leftPanel, (in other words, all screen was black since I set the background of display panel to black)
So, how could I fix it ?
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class LogoLayout {
private JComponent ui = null;
LogoLayout() {
initUI();
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new BorderLayout(4,4));
ui.setBorder(new EmptyBorder(4,4,4,4));
BufferedImage logo = new BufferedImage(
276,560,BufferedImage.TYPE_INT_RGB);
/* All that's needed */
ui.add(new JLabel(new ImageIcon(logo)), BorderLayout.LINE_START);
ui.add(new JTextArea("Display", 3, 44));
/* All that's needed */
}
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) {
}
LogoLayout o = new LogoLayout();
JFrame f = new JFrame("Logo Layout");
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);
}
}

Prevent scrollbars disappearing when exiting component inside the JScrollPane

I made a JPanel that contains a JScrollPane that surrounds a JTextArea. I want to hide the scrollbars when the mouse exits the JScrollPane.
If I set the MouseListener on the JScrollPane, then nothing happens. If I set it on the JTextArea then the scrollbars hide/unhide correctly, but you cannot click them because they are outside the bounds of the JTextArea.\
How can I prevent the scrollbars from disappearing when you try to click them?
Code example 1. Hiding and unhiding + changing transparency works.
Problem: You cannot click the scrollbars, they disappear because you exit the JTextArea.
public class TransparentTextArea extends JTextArea {
private static final Color LIGHT_TRANSPARENT = new Color(0, 0, 0, 150);
private static final Color HEAVY_TRANSPARENT = new Color(0, 0, 0, 50);
public TransparentTextArea(final GameModel model) {
setOpaque(false);
setForeground(Color.WHITE);
setBackground(HEAVY_TRANSPARENT);
setEditable(false);
addMouseListener(new MouseListener() {
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
model.setLogActive(false);
setBackground(HEAVY_TRANSPARENT);
}
#Override
public void mouseEntered(MouseEvent e) {
model.setLogActive(true);
setBackground(LIGHT_TRANSPARENT);
}
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
});
}
}
public class Logger extends JScrollPane implements PanelObserver,
ChangeListener {
private GameModel model;
public Logger(final GameModel model) {
super(new TransparentTextArea(model));
this.model = model;
setOpaque(false);
getViewport().setOpaque(false);
setBorder(BorderFactory.createEmptyBorder());
setViewportBorder(BorderFactory.createEmptyBorder());
model.addPanelObserver(this);
model.addChangeListener(this);
}
#Override
public void panelResized() {
float x = model.getPanelWidth() * 0.01f;
float y = model.getPanelHeight() * 0.70f;
float width = model.getPanelWidth() * 0.30f;
float height = model.getPanelHeight() * 0.28f;
setBounds((int) x, (int) y, (int) width, (int) height);
}
#Override
public void stateChanged(ChangeEvent e) {
if (model.isLogActive()) {
setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
} else {
setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
}
}
}
Code example 2.
Problem I tried to fix this by creating a Panel around it and using that MouseExited, but it does not work since the childs consume it.
public class Logger extends JPanel implements PanelObserver, MouseListener {
private static final Color LIGHT_TRANSPARENT = new Color(0, 0, 0, 150);
private static final Color HEAVY_TRANSPARENT = new Color(0, 0, 0, 50);
private GameModel model;
private JTextArea textArea;
private JScrollPane scrollPane;
public Logger(GameModel model) {
super(null);
this.model = model;
setOpaque(false);
textArea = new JTextArea();
textArea.setOpaque(false);
textArea.setForeground(Color.WHITE);
textArea.setBackground(HEAVY_TRANSPARENT);
textArea.setEditable(false);
scrollPane = new JScrollPane(textArea);
scrollPane.setOpaque(false);
scrollPane.getViewport().setOpaque(false);
scrollPane.setBorder(BorderFactory.createEmptyBorder());
scrollPane.setViewportBorder(BorderFactory.createEmptyBorder());
add(scrollPane);
model.addPanelObserver(this);
addMouseListener(this);
}
#Override
public void panelResized() {
float x = model.getPanelWidth() * 0.01f;
float y = model.getPanelHeight() * 0.70f;
float width = model.getPanelWidth() * 0.30f;
float height = model.getPanelHeight() * 0.28f;
setBounds((int) x, (int) y, (int) width, (int) height);
scrollPane.setBounds(0, 0, (int) width, (int) height);
}
#Override
public void mouseClicked(MouseEvent e) {}
#Override
public void mousePressed(MouseEvent e) {}
#Override
public void mouseReleased(MouseEvent e) {}
#Override
public void mouseEntered(MouseEvent e) {
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
textArea.setBackground(LIGHT_TRANSPARENT);
}
#Override
public void mouseExited(MouseEvent e) {
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
textArea.setBackground(HEAVY_TRANSPARENT);
}
}
works for me, but there are a few mistakes
JScrollPane (in the case that is container) react to only one pixel around its child (1pixel Border)
mouse event are consumed by its childs, then whatever added to JScrollPane inside JPanel to consume() mouse event
JPanel has FlowLayout implementer in API, change that
don't to use NullLayout, use proper LayourManager for JPanel (BorderLayout, GridLayout)
JComponents can quite to easilly returns PreferredSize back to the container override getPreferredSize for JPanel, JTextArea(20, 20) etc
JPanel must be larger that JViewport in JScrollPane, otherwise (without override JScrollBars) JScrollBar never will be visible
near to true were #Omid +1
. . . . .
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
//http://stackoverflow.com/q/16344529/714968
public class MyLogger {
private JTextArea textArea;
private JScrollPane scrollPane;
public MyLogger() {
textArea = new JTextArea(20, 20);
scrollPane = new JScrollPane(textArea);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
textArea.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
}
#Override
public void mouseExited(MouseEvent e) {
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
}
});
JFrame frame = new JFrame();
frame.add(scrollPane);
frame.setPreferredSize(new Dimension(100, 100));// JFrame must be smaller
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
MyLogger myLogger = new MyLogger();
}
});
}
}
EDIT
again back to answer posted by #Omid, see what happens
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
//http://stackoverflow.com/q/16344529/714968
public class MyLogger {
private JTextArea textArea;
private JScrollPane scrollPane;
public MyLogger() {
textArea = new JTextArea(20, 20);
textArea.setText("This text pane contains no html. It supports letter wrapping, "
+ "\nThis text pane contains no html. It supports letter wrapping!, "
+ "\nThis text pane contains no html. It supports letter wrapping!, "
+ "\nThis text pane contains no html. It supports letter wrapping!, "
+ "\nThis text pane contains no html. It supports letter wrapping!, "
+ "\nThis text pane contains no html. It supports letter wrapping!");
textArea.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
}
});
scrollPane = new JScrollPane(textArea);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.addMouseListener(new MouseAdapter() {
#Override
public void mouseExited(MouseEvent e) {
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
}
});
JFrame frame = new JFrame();
frame.add(scrollPane);
frame.setPreferredSize(new Dimension(100, 100));// JFrame must be smaller
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
MyLogger myLogger = new MyLogger();
}
});
}
}
Just tried this and it works fine:
textArea.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseMoved(MouseEvent arg0) {
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
}
});
scrollPane.addMouseListener(new MouseAdapter() {
#Override
public void mouseExited(MouseEvent e) {
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
}
});
The idea is that as long as the mouse is moving within the textArea, the ScrollBar is visible and works fine. As soon as it moves outside the ScrollPane it's not visible anymore.
You may have to put the listener on the JScrollPane itself rather than on the backing JPanel. The JScrollPane encapsulates your JPanel so adding the mouse listener to the JPanel only will only tell you when the mouse enters/leaves that JPanel specifically, not the encapsulating JScrollPane.
scrollPane.addMouseListener(this);
You may actually have to have listeners in both, depending on how you want this all to work, and maybe set up a lock so that as long as the mouse is in at least one of them, the scroll bars will show, but if the mouse is in neither then make them invisible.

How to Remove JFrame Border as to Let an Image Touch The Edge

I had a friend make a background for the program I made so that it wouldn't look so plain, and I thought the best way to place the images would be to make a JLabel, fill it with an image, and set it to the size of the screen. This worked fine, except there is a small border around the JFrame and I can't get the JLabel to touch the edges of the frame. Thoughts? I have attached a picture.
public class ProgramDriver extends JFrame {
private JPanel contentPane;
private static CardLayout cardLayout;
private JTextField addGradeN;
private JTextField addGradeD;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ProgramDriver frame = new ProgramDriver();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//Global Variables
...
manager = new StateManager(gb);
//JFrame Settings
setTitle("Grade Book");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 656, 530);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
cardLayout = new CardLayout(0,0);
contentPane.setLayout(cardLayout);
setResizable(false);
//Home Panel
final JPanel Home = new JPanel();
contentPane.add(Home, "Home");
Home.setLayout(null);
JButton btnSeeGrades = new JButton("See Grades");
...
//Grades Panel
JPanel Grades = new JPanel();
contentPane.add(Grades, "Grades");
Grades.setLayout(null);'
The problem isn't with the JFrame, the problem is with your code. We can spend the rest of our natural life at guessing what's wrong or you can post some example code.
Now it's up to you, we can keep trying to throw wrong guess after wrong guess at you, frustrating us all, or you can help us help you...
Here are two examples I did. The first uses a JLabel as the primary content for a JPanel, where the child components are placed on it. Nice and simple.
The second uses a custom JPanel which paints the image onto the background of the component. I then use this to replace the frames content pane. This is a little more involved, but it has the added benefit of been easily updated (replacing the content pane won't effect the rest of the program)
Example 1: JLabel used as background
public class TestBackground {
public static final String BACKGROUND_PATH = "/Volumes/Macintosh HD2/Dropbox/MT015.jpg";
public static void main(String[] args) {
new TestBackground();
}
public TestBackground() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new LabelPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
protected class LabelPane extends JPanel {
public LabelPane() {
BufferedImage bg = null;
try {
bg = ImageIO.read(new File(BACKGROUND_PATH));
} catch (IOException ex) {
ex.printStackTrace();
}
JLabel label = new JLabel(new ImageIcon(bg));
setLayout(new BorderLayout());
add(label);
label.setLayout(new GridBagLayout());
JLabel lblMessage = new JLabel("Look at me!");
lblMessage.setForeground(Color.WHITE);
lblMessage.setFont(lblMessage.getFont().deriveFont(Font.BOLD, 48));
label.add(lblMessage);
}
}
}
Example 2: Image used as background, replacing content pane...
public class TestBackground {
public static final String BACKGROUND_PATH = "/Volumes/Macintosh HD2/Dropbox/MT015.jpg";
public static void main(String[] args) {
new TestBackground();
}
public TestBackground() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new BackgroundPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
protected class BackgroundPane extends JPanel {
private BufferedImage bg = null;
public BackgroundPane() {
try {
bg = ImageIO.read(new File(BACKGROUND_PATH));
} catch (IOException ex) {
ex.printStackTrace();
}
setLayout(new GridBagLayout());
JLabel lblMessage = new JLabel("Look at me!");
lblMessage.setForeground(Color.WHITE);
lblMessage.setFont(lblMessage.getFont().deriveFont(Font.BOLD, 48));
add(lblMessage);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(1153, 823);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (bg != null) {
g.drawImage(bg, 0, 0, this);
}
}
}
}
To expand on Eng.Fouad's answer, you'll want to use the drawImage(...) method that takes 6 parameters, image, x and y location, image width and height, and image observer, and draw it like so from within a JPanel:
g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
For example, my sscce:
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
#SuppressWarnings("serial")
public class ExpandingImage extends JPanel {
public static final String GUITAR = "http://duke.kenai.com/Oracle/OracleStrat.png";
BufferedImage img;
public ExpandingImage(String imgUrlPath) throws IOException {
URL imgUrl = new URL(imgUrlPath);
img = ImageIO.read(imgUrl);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (img != null) {
g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
}
}
private static void createAndShowGui() {
ExpandingImage mainPanel;
try {
mainPanel = new ExpandingImage(GUITAR);
JFrame frame = new JFrame("ExpandingImage");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Edit
I see that you're using an EmptyBorder around the contentPane. Why if you don't want this border to be present?
As an alternative, you can override the method paintComponent(Graphics g) of JPanel (the contentPane) and use drawImage() on the Graphics object g as in this example.
have you tried JFrame function setUndecorated() ?
Make the frame undecorated. frame.setUndecorated(true)
If you want to make it move, you can use the ComponentMover of the Java2S.
Make sure that it is undecorated before it is visible.
Next, use setContentPane(new JLabel(new ImageIcon("myimage.jpg")));
After, that you can add contents as usual.

Categories