How to add close button in BasicTabbedPaneUI? - java

I'm trying to build a JTabbedPane using BasicTabbedPaneUI. I found an example of it which doesn't works perfectly. But it doesn't have a close button so that i can close the current tab.
How can i add a close button in it?
Here is my code:
public class TabbedPane extends JPanel {
private static final long serialVersionUID = 1L;
public static final JButton backButton = new JButton();
public TabbedPane() {
setLayout(new BorderLayout());
JPanel jp = new JPanel();
jp.setLayout(new BorderLayout());
JTabbedPane tb = new JTabbedPane();
tb.setUI(new CustomTabbedPaneUI());
JPanel pane = new JPanel();
tb.add("Tab1", pane);
MyCloseButton button = new MyCloseButton();
jp.add(new JLayer<JTabbedPane>(tb));
jp.add(new JButton(new AbstractAction("add tab") {
#Override
public void actionPerformed(ActionEvent e) {
tb.addTab("test", new JPanel());
}
}), BorderLayout.SOUTH);
jp.add(tb, BorderLayout.CENTER);
add(jp, BorderLayout.CENTER);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new TabbedPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 200);
frame.setVisible(true);
}
}
and
public class CustomTabbedPaneUI extends BasicTabbedPaneUI {
private Color selectColor;
private Color deSelectColor;
private int inclTab = 4;
private int anchoFocoV = inclTab;
private int anchoFocoH = 4;
private int anchoCarpetas = 18;
private Polygon shape;
public static ComponentUI createUI(JComponent c) {
return new CustomTabbedPaneUI();
}
#Override
protected void installDefaults() {
super.installDefaults();
selectColor = new Color(250, 192, 192);
deSelectColor = new Color(197, 193, 168);
tabAreaInsets.right = anchoCarpetas;
}
#Override
protected void paintTabArea(Graphics g, int tabPlacement, int selectedIndex) {
if (runCount > 1) {
int lines[] = new int[runCount];
for (int i = 0; i < runCount; i++) {
lines[i] = rects[tabRuns[i]].y + (tabPlacement == TOP ? maxTabHeight : 0);
}
Arrays.sort(lines);
if (tabPlacement == TOP) {
int fila = runCount;
for (int i = 0; i < lines.length - 1; i++, fila--) {
Polygon carp = new Polygon();
carp.addPoint(0, lines[i]);
carp.addPoint(tabPane.getWidth() - 2 * fila - 2, lines[i]);
carp.addPoint(tabPane.getWidth() - 2 * fila, lines[i] + 3);
if (i < lines.length - 2) {
carp.addPoint(tabPane.getWidth() - 2 * fila, lines[i + 1]);
carp.addPoint(0, lines[i + 1]);
} else {
carp.addPoint(tabPane.getWidth() - 2 * fila, lines[i] + rects[selectedIndex].height);
carp.addPoint(0, lines[i] + rects[selectedIndex].height);
}
carp.addPoint(0, lines[i]);
g.setColor(hazAlfa(fila));
g.fillPolygon(carp);
g.setColor(darkShadow.darker());
g.drawPolygon(carp);
}
} else {
int fila = 0;
for (int i = 0; i < lines.length - 1; i++, fila++) {
Polygon carp = new Polygon();
carp.addPoint(0, lines[i]);
carp.addPoint(tabPane.getWidth() - 2 * fila - 1, lines[i]);
carp.addPoint(tabPane.getWidth() - 2 * fila - 1, lines[i + 1] - 3);
carp.addPoint(tabPane.getWidth() - 2 * fila - 3, lines[i + 1]);
carp.addPoint(0, lines[i + 1]);
carp.addPoint(0, lines[i]);
g.setColor(hazAlfa(fila + 2));
g.fillPolygon(carp);
g.setColor(darkShadow.darker());
g.drawPolygon(carp);
}
}
}
super.paintTabArea(g, tabPlacement,selectedIndex);
}
#Override
protected void paintTabBackground(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) {
Graphics2D g2D = (Graphics2D) g;
GradientPaint gradientShadow;
int xp[] = null; // Para la forma
int yp[] = null;
switch (tabPlacement) {
case LEFT:
xp = new int[]{x, x, x + w, x + w, x};
yp = new int[]{y, y + h - 3, y + h - 3, y, y};
gradientShadow = new GradientPaint(x, y, new Color(100, 100, 255), x, y + h, Color.ORANGE);
break;
case RIGHT:
xp = new int[]{x, x, x + w - 2, x + w - 2, x};
yp = new int[]{y, y + h - 3, y + h - 3, y, y};
gradientShadow = new GradientPaint(x, y, new Color(100, 100, 255), x, y + h, new Color(153, 186, 243));
break;
case BOTTOM:
xp = new int[]{x, x, x + 3, x + w - inclTab - 6, x + w - inclTab - 2, x + w - inclTab, x + w - 3, x};
yp = new int[]{y, y + h - 3, y + h, y + h, y + h - 1, y + h - 3, y, y};
gradientShadow = new GradientPaint(x, y, new Color(100, 100, 255), x, y + h, Color.BLUE);
break;
case TOP:
default:
xp = new int[]{x, x, x + 3, x + w - inclTab - 6, x + w - inclTab - 2, x + w - inclTab, x + w - inclTab, x};
yp = new int[]{y + h, y + 3, y, y, y + 1, y + 3, y + h, y + h};
gradientShadow = new GradientPaint(0, 0, Color.ORANGE, 0, y + h / 2, new Color(240, 255, 210));
break;
}
shape = new Polygon(xp, yp, xp.length);
if (isSelected) {
g2D.setColor(selectColor);
g2D.setPaint(gradientShadow);
} else {
if (tabPane.isEnabled() && tabPane.isEnabledAt(tabIndex)) {
g2D.setColor(deSelectColor);
GradientPaint gradientShadowTmp = new GradientPaint(0, 0, new Color(255, 255, 200), 0, y + h / 2, new Color(240, 255, 210));
g2D.setPaint(gradientShadowTmp);
} else {
GradientPaint gradientShadowTmp = new GradientPaint(0, 0, new Color(240, 255, 210), 0, y + 15 + h / 2, new Color(204, 204, 204));
g2D.setPaint(gradientShadowTmp);
}
}
g2D.fill(shape);
if (runCount > 1) {
g2D.setColor(hazAlfa(getRunForTab(tabPane.getTabCount(), tabIndex) - 1));
g2D.fill(shape);
}
g2D.fill(shape);
}
#Override
protected void paintText(Graphics g, int tabPlacement, Font font, FontMetrics metrics, int tabIndex, String title, Rectangle textRect, boolean isSelected) {
super.paintText(g, tabPlacement, font, metrics, tabIndex, title, textRect, isSelected);
g.setFont(font);
View v = getTextViewForTab(tabIndex);
if (v != null) {
// html
v.paint(g, textRect);
} else {
// plain text
int mnemIndex = tabPane.getDisplayedMnemonicIndexAt(tabIndex);
if (tabPane.isEnabled() && tabPane.isEnabledAt(tabIndex)) {
MyCloseButton button = new MyCloseButton();
g.setColor(tabPane.getForegroundAt(tabIndex));
BasicGraphicsUtils.drawStringUnderlineCharAt(g, title, mnemIndex, textRect.x, textRect.y + metrics.getAscent());
} else { // tab disabled
g.setColor(Color.BLACK);
BasicGraphicsUtils.drawStringUnderlineCharAt(g, title, mnemIndex, textRect.x, textRect.y + metrics.getAscent());
g.setColor(tabPane.getBackgroundAt(tabIndex).darker());
BasicGraphicsUtils.drawStringUnderlineCharAt(g, title, mnemIndex, textRect.x - 1, textRect.y + metrics.getAscent() - 1);
}
}
}
#Override
protected int calculateTabWidth(int tabPlacement, int tabIndex, FontMetrics metrics) {
return 20 + inclTab + super.calculateTabWidth(tabPlacement, tabIndex, metrics);
}
#Override
protected int calculateTabHeight(int tabPlacement, int tabIndex, int fontHeight) {
if (tabPlacement == LEFT || tabPlacement == RIGHT) {
return super.calculateTabHeight(tabPlacement, tabIndex, fontHeight);
} else {
return anchoFocoH + super.calculateTabHeight(tabPlacement, tabIndex, fontHeight);
}
}
#Override
protected void paintTabBorder(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) {
}
#Override
protected void paintFocusIndicator(Graphics g, int tabPlacement, Rectangle[] rects, int tabIndex, Rectangle iconRect, Rectangle textRect, boolean isSelected) {
if (tabPane.hasFocus() && isSelected) {
g.setColor(UIManager.getColor("ScrollBar.thumbShadow"));
g.drawPolygon(shape);
}
}
protected Color hazAlfa(int fila) {
int alfa = 0;
if (fila >= 0) {
alfa = 50 + (fila > 7 ? 70 : 10 * fila);
}
return new Color(0, 0, 0, alfa);
}
}
Here is my Button class which i want to add in the code above
class MyCloseButton extends JButton{
public MyCloseButton() {
super("X");
setBorder(BorderFactory.createEmptyBorder());
setFocusPainted(false);
setBorderPainted(false);
setContentAreaFilled(false);
setRolloverEnabled(false);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(16, 16);
}
}

Related

Eclipse game window opening very small

Whenever I run my game, the game window opens up very small, like below, how can I fix this. I believe it is something to do with JFrame.setPreferredSize(new Dimension(x,y)); but I don't know where to implement this in the code for it to work.
This is what it shows:
enter image description here
Where do I implement the code? Like in the class, outside the class, or do I need to show my current code for someone to help me here?
This is my code:
public class RoadAppMain extends JFrame {
private static final int D_W = 1920; //Window dimension
private static final int D_H = 1280; //Window height
int grassWidth = 1920; //Width of grass
int vanishHeight = 768; // Height of vanishing point
int roadWidth = 900; //Width of the road
int rumbleLen = 800; //Length of each track stripe
double camDist = 0.8; //Camera distance
int N; //Size of each row or line
int playerPosX = 0; //Movement of player left and right
int playerPosY = 0; //Movement of player up and down
List<Line> lines = new ArrayList<RoadAppMain.Line>();
List<Integer> listValues = new ArrayList<Integer>();
DrawPanel drawPanel = new DrawPanel();
public RoadAppMain() {
for (int i = 0; i < 1600; i++) {
Line line = new Line();
line.z = i * rumbleLen;
int curveAngle = (int) (Math.random() * 15 + 1);
if (i > 20 && i < 70) {
line.curve = curveAngle;
}
else if (i > 100 && i < 150) {
line.curve = -curveAngle;
}
else if (i > 180 && i < 230) {
line.curve = curveAngle;
}
else if (i > 260 && i < 310) {
line.curve = -curveAngle;
}
else if (i > 340 && i < 390) {
line.curve = curveAngle;
}
else if (i > 400 && i < 420) {
}
lines.add(line);
}
N = lines.size();
//Handles action events by user
ActionListener listener = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
drawPanel.repaint();
}
};
Timer timer = new Timer(1, listener);
timer.start();
add(drawPanel);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
//Moves screen using arrow keys
private class DrawPanel extends JPanel {
public DrawPanel() {
String VK_LEFT = "VK_LEFT";
KeyStroke W = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0);
InputMap inputMap = getInputMap(WHEN_IN_FOCUSED_WINDOW); //necessary
inputMap.put(W, VK_LEFT);
ActionMap actionMap = getActionMap(); //necessary
actionMap.put(VK_LEFT, new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
playerPosX -= 200;
drawPanel.repaint();
}
});
String VK_RIGHT = "VK_RIGHT";
KeyStroke WVK_RIGHT = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0);
inputMap.put(WVK_RIGHT, VK_RIGHT);
actionMap.put(VK_RIGHT, new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
playerPosX += 200;
drawPanel.repaint();
}
});
String VK_UP = "VK_UP";
KeyStroke WVK_UP = KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0);
inputMap.put(WVK_UP, VK_UP);
actionMap.put(VK_UP, new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
playerPosY += 200;
drawPanel.repaint();
}
});
String VK_DOWN = "VK_DOWN";
KeyStroke WVK_DOWN = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0);
inputMap.put(WVK_DOWN, VK_DOWN);
actionMap.put(VK_DOWN, new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
playerPosY -= 200;
drawPanel.repaint();
}
});
}
//Drawing components feature
protected void paintComponent(Graphics g) {
drawValues(g);
g.setColor(Color.black);
g.fillRect(0, 0, 1920, 395);
}
}
private void drawValues(Graphics g) {
int startPos = playerPosY / rumbleLen;
double x = 0; //Initial X position of screen on road
double dx = 0; //Correlation between the angle of the road and player
double maxY = vanishHeight;
int camH = 1700 + (int) lines.get(startPos).y; //Height of the camera
//Starting position
for (int n = startPos; n < startPos + 300; n++) {
Line l = lines.get(n % N); //Position of line
l.project(playerPosX - (int) x, camH, playerPosY);
x += dx;
dx += l.curve;
if (l.Y > 0 && l.Y < maxY) {
maxY = l.Y;
Color grass = ((n / 2) % 2) == 0 ? new Color(21, 153, 71) : new Color(22, 102, 52); //Color for grass (first is for lighter, second for darker)
Color rumble = ((n / 2) % 2) == 0 ? new Color(255, 255, 255) : new Color(222, 4, 4); // Color for rumble (first is white, second is red)
Color road = new Color(54, 52, 52); // Color of road or asphalt
Color midel = ((n / 2) % 2) == 0 ? new Color(255, 255, 255) : new Color(54, 52, 52); //Color of hashed lines (first for white lines, second for gap)
Color car = new Color(104, 104, 104);
Color tire = new Color(0, 0, 0);
Color stripe = new Color(0, 0, 0);
Color light = new Color(253, 0, 0);
Color hood = new Color(0, 0, 0);
Color frame = new Color(0,0,255);
Line p = null;
if (n == 0) {
p = l;
} else {
p = lines.get((n - 1) % N);
}
draw(g, grass, 0, (int) p.Y, grassWidth, 0, (int) l.Y, grassWidth); //(Graphics g, Color c, int x1, int y1, int w1, int x2, int y2, int w2)
draw(g, rumble, (int) p.X, (int) p.Y, (int) (p.W * 2.03), (int) l.X, (int) l.Y, (int) (l.W * 2.03)); //Affects width of rumble
draw(g, road, (int) p.X, (int) p.Y, (int) (p.W * 1.8), (int) l.X, (int) l.Y, (int) (l.W * 1.8));
draw(g, midel, (int) p.X, (int) p.Y, (int) (p.W * 0.78), (int) l.X, (int) l.Y, (int) (l.W * 0.78)); //ADD HERE
draw(g, road, (int) p.X, (int) p.Y, (int) (p.W * 0.7), (int) l.X, (int) l.Y, (int) (l.W* 0.7)); //To cover the gap in between each midel. Must be after to allow it to colour over it
draw(g, car, 965, 927, 125, 965, 1005, 125);
draw(g, tire, 875, 1005, 35, 875, 1050, 35);
draw(g, tire, 1055, 1005, 35, 1055, 1050, 35);
draw(g, stripe, 1050, 965, 30, 870, 980, 30);
draw(g, stripe, 1050, 950, 30, 870, 965, 30);
draw(g, hood, 965, 880, 90, 965, 927, 125);
draw(g, light, 875, 950, 5, 875, 980, 5);
draw(g, light, 890, 950, 5, 890, 980, 5);
draw(g, light, 905, 950, 5, 905, 980, 5);
draw(g, light, 1025, 950, 5, 1025, 980, 5);
draw(g, light, 1040, 950, 5, 1040, 980, 5);
draw(g, light, 1055, 950, 5, 1055, 980, 5);
draw(g, frame, 965, 874, 86, 965, 880, 90);
draw(g, light, 965, 874, 35, 965, 880, 45);
}
}
}
void draw(Graphics g, Color c, int x1, int y1, int w1, int x2, int y2, int w2) {
Graphics g9d = g;
int[] x9Points = { x1 - w1, x2 - w2, x2 + w2, x1 + w1 };
int[] y9Points = { y1, y2, y2, y1 };
int n9Points = 4;
g9d.setColor(c);
g9d.fillPolygon(x9Points, y9Points, n9Points);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new RoadAppMain();
}
});
}
class Line {
double x, y, z;
double X, Y, W;
double scale, curve;
public Line() {
curve = x = y = z = 0;
}
void project(int camX, int camY, int camZ) {
scale = camDist / (z - camZ);
X = (1 + scale * (x - camX)) * grassWidth / 2;
Y = (1 - scale * (y - camY)) * vanishHeight / 2;
W = scale * roadWidth * grassWidth / 2;
}
}
}

Move game screen diagonally using arrow keys

I'm creating a car game where it creates a 3D pseudo effect by moving the screen backwards and the car itself just stays still on the map, using the arrow keys. It only takes in one input at a time, meaning you have to let go of an arrow key first. I have some code that I've got to show what I'm aiming for the screen to do as well, as the screen only moves forwards, backwards, left, and right.
Example of what I want the screen to do:
public class Main extends JFrame {
private static final long serialVersionUID = 7722803326073073681L;
private boolean left = false;
private boolean up = false;
private boolean down = false;
private boolean right = false;
public JLabel lbl = new JLabel ("mn");
public Main() {
// Just setting up the window and objects
setSize(400, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
lbl.setBounds(100, 100, 20, 20);
add(lbl);
setLocationRelativeTo(null);
// Key listener, will not move the JLabel, just set where to
addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {}
#Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) left = false;
if (e.getKeyCode() == KeyEvent.VK_RIGHT) right = false;
if (e.getKeyCode() == KeyEvent.VK_UP) up = false;
if (e.getKeyCode() == KeyEvent.VK_DOWN) down = false;
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) left = true;
if (e.getKeyCode() == KeyEvent.VK_RIGHT) right = true;
if (e.getKeyCode() == KeyEvent.VK_UP) up = true;
if (e.getKeyCode() == KeyEvent.VK_DOWN) down = true;
}
});
// This thread will read the 4 variables left/right/up/down at every 30 milliseconds
// It will check the combination of keys (left and up, right and down, just left, just up...)
// And move the label 3 pixels
new Thread(new Runnable() {
#Override
public void run() {
try {
while (true) {
if (left && up) {
lbl.setBounds(lbl.getX() - 10, lbl.getY() - 10, 20, 20);
} else if (left && down) {
lbl.setBounds(lbl.getX() - 10, lbl.getY() + 10, 20, 20);
} else if (right && up) {
lbl.setBounds(lbl.getX() + 10, lbl.getY() - 10, 20, 20);
} else if (right && down) {
lbl.setBounds(lbl.getX() + 10, lbl.getY() + 10, 20, 20);
} else if (left) {
lbl.setBounds(lbl.getX() - 10, lbl.getY(), 20, 20);
} else if (up) {
lbl.setBounds(lbl.getX(), lbl.getY() - 10, 20, 20);
} else if (right) {
lbl.setBounds(lbl.getX() + 10, lbl.getY(), 20, 20);
} else if (down) {
lbl.setBounds(lbl.getX(), lbl.getY() + 10, 20, 20);
}
Thread.sleep(30);
}
} catch (Exception ex) {
ex.printStackTrace();
System.exit(0);
}
}
}).start();
}
public static void main(String[] args) {
new Main();
}
}
However, since the code above only moves the letters, I'm having a lot of difficulty in implementing it in the game as well. This is what I'm currently using to move the screen. (If I were to delete this method, nothing would appear).
What is currently happening:
public class RoadAppMain extends JFrame {
private static final int D_W = 1920; //Window dimension
private static final int D_H = 1280; //Window height
int grassWidth = 1920; //Width of grass
int vanishHeight = 768; // Height of vanishing point
int roadWidth = 900; //Width of the road
int rumbleLen = 800; //Length of each track stripe
double camDist = 0.8; //Camera distance
int N; //Size of each row or line
int playerPosX = 0; //Movement of player left and right
int playerPosY = 0; //Movement of player up and down
List<Line> lines = new ArrayList<RoadAppMain.Line>();
List<Integer> listValues = new ArrayList<Integer>();
DrawPanel drawPanel = new DrawPanel();
public RoadAppMain() {
for (int i = 0; i < 1600; i++) {
Line line = new Line();
line.z = i * rumbleLen;
int curveAngle = (int) (Math.random() * 15 + 1);
if (i > 20 && i < 70) {
line.curve = curveAngle;
}
else if (i > 100 && i < 150) {
line.curve = -curveAngle;
}
else if (i > 180 && i < 230) {
line.curve = curveAngle;
}
else if (i > 260 && i < 310) {
line.curve = -curveAngle;
}
else if (i > 340 && i < 390) {
line.curve = curveAngle;
}
else if (i > 400 && i < 420) {
}
lines.add(line);
}
N = lines.size();
//Handles action events by user
ActionListener listener = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
drawPanel.repaint();
}
};
Timer timer = new Timer(1, listener);
timer.start();
add(drawPanel);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
//Moves screen using arrow keys - THIS IS THE PART IM TALKING ABOUT
private class DrawPanel extends JPanel {
public DrawPanel() {
String VK_LEFT = "VK_LEFT";
KeyStroke W = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0);
InputMap inputMap = getInputMap(WHEN_IN_FOCUSED_WINDOW); //necessary
inputMap.put(W, VK_LEFT);
ActionMap actionMap = getActionMap(); //necessary
actionMap.put(VK_LEFT, new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
playerPosX -= 200;
drawPanel.repaint();
}
});
String VK_RIGHT = "VK_RIGHT";
KeyStroke WVK_RIGHT = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0);
inputMap.put(WVK_RIGHT, VK_RIGHT);
actionMap.put(VK_RIGHT, new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
playerPosX += 200;
drawPanel.repaint();
}
});
String VK_UP = "VK_UP";
KeyStroke WVK_UP = KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0);
inputMap.put(WVK_UP, VK_UP);
actionMap.put(VK_UP, new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
playerPosY += 200;
drawPanel.repaint();
}
});
String VK_DOWN = "VK_DOWN";
KeyStroke WVK_DOWN = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0);
inputMap.put(WVK_DOWN, VK_DOWN);
actionMap.put(VK_DOWN, new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
playerPosY -= 200;
drawPanel.repaint();
}
});
}
//Drawing components feature
protected void paintComponent(Graphics g) {
drawValues(g);
g.setColor(Color.black);
g.fillRect(0, 0, 1920, 395);
}
}
private void drawValues(Graphics g) {
int startPos = playerPosY / rumbleLen;
double x = 0; //Initial X position of screen on road
double dx = 0; //Correlation between the angle of the road and player
double maxY = vanishHeight;
int camH = 1700 + (int) lines.get(startPos).y; //Height of the camera
//Starting position
for (int n = startPos; n < startPos + 300; n++) {
Line l = lines.get(n % N); //Position of line
l.project(playerPosX - (int) x, camH, playerPosY);
x += dx;
dx += l.curve;
if (l.Y > 0 && l.Y < maxY) {
maxY = l.Y;
Color grass = ((n / 2) % 2) == 0 ? new Color(21, 153, 71) : new Color(22, 102, 52); //Color for grass (first is for lighter, second for darker)
Color rumble = ((n / 2) % 2) == 0 ? new Color(255, 255, 255) : new Color(222, 4, 4); // Color for rumble (first is white, second is red)
Color road = new Color(54, 52, 52); // Color of road or asphalt
Color midel = ((n / 2) % 2) == 0 ? new Color(255, 255, 255) : new Color(54, 52, 52); //Color of hashed lines (first for white lines, second for gap)
Color car = new Color(104, 104, 104);
Color tire = new Color(0, 0, 0);
Color stripe = new Color(0, 0, 0);
Color light = new Color(253, 0, 0);
Color hood = new Color(0, 0, 0);
Color frame = new Color(0,0,255);
Line p = null;
if (n == 0) {
p = l;
} else {
p = lines.get((n - 1) % N);
}
draw(g, grass, 0, (int) p.Y, grassWidth, 0, (int) l.Y, grassWidth); //(Graphics g, Color c, int x1, int y1, int w1, int x2, int y2, int w2)
draw(g, rumble, (int) p.X, (int) p.Y, (int) (p.W * 2.03), (int) l.X, (int) l.Y, (int) (l.W * 2.03)); //Affects width of rumble
draw(g, road, (int) p.X, (int) p.Y, (int) (p.W * 1.8), (int) l.X, (int) l.Y, (int) (l.W * 1.8));
draw(g, midel, (int) p.X, (int) p.Y, (int) (p.W * 0.78), (int) l.X, (int) l.Y, (int) (l.W * 0.78)); //ADD HERE
draw(g, road, (int) p.X, (int) p.Y, (int) (p.W * 0.7), (int) l.X, (int) l.Y, (int) (l.W* 0.7)); //To cover the gap in between each midel. Must be after to allow it to colour over it
draw(g, car, 965, 927, 125, 965, 1005, 125);
draw(g, tire, 875, 1005, 35, 875, 1050, 35);
draw(g, tire, 1055, 1005, 35, 1055, 1050, 35);
draw(g, stripe, 1050, 965, 30, 870, 980, 30);
draw(g, stripe, 1050, 950, 30, 870, 965, 30);
draw(g, hood, 965, 880, 90, 965, 927, 125);
draw(g, light, 875, 950, 5, 875, 980, 5);
draw(g, light, 890, 950, 5, 890, 980, 5);
draw(g, light, 905, 950, 5, 905, 980, 5);
draw(g, light, 1025, 950, 5, 1025, 980, 5);
draw(g, light, 1040, 950, 5, 1040, 980, 5);
draw(g, light, 1055, 950, 5, 1055, 980, 5);
draw(g, frame, 965, 874, 86, 965, 880, 90);
draw(g, light, 965, 874, 35, 965, 880, 45);
}
}
}
void draw(Graphics g, Color c, int x1, int y1, int w1, int x2, int y2, int w2) {
Graphics g9d = g;
int[] x9Points = { x1 - w1, x2 - w2, x2 + w2, x1 + w1 };
int[] y9Points = { y1, y2, y2, y1 };
int n9Points = 4;
g9d.setColor(c);
g9d.fillPolygon(x9Points, y9Points, n9Points);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new RoadAppMain();
}
});
}
class Line {
double x, y, z;
double X, Y, W;
double scale, curve;
public Line() {
curve = x = y = z = 0;
}
void project(int camX, int camY, int camZ) {
scale = camDist / (z - camZ);
X = (1 + scale * (x - camX)) * grassWidth / 2;
Y = (1 - scale * (y - camY)) * vanishHeight / 2;
W = scale * roadWidth * grassWidth / 2;
}
}
}
How could I implement that movement into my game as well?

How to optimize this kind of loop?

I'm trying to make this GUi.
I write my own layout because existing layout manager don't meet my requirements
It works but I attempt to optimize the creation of all buttons by using loops.
Test.class
public class Test {
public static void main(String[] args) {
JFrame f = new JFrame();
JPanel parent = new JPanel();
f.add(parent);
parent.setLayout(new BoxLayout(parent, BoxLayout.X_AXIS));
JPanel[] children = new JPanel[6];
for (int i = 1; i < children.length; i++) {
children[i] = new JPanel();
children[i].setLayout(new XYLayout());
children[i].setBorder(new LineBorder(Color.red));
parent.add(children[i]);
}
int x = 0, y = 375, w = 0, h = 50;
children[1].add(new JButton("8"), new XYConstraints(0, 25, 0, 50));
children[1].add(new JButton("7"), new XYConstraints(0, 75, 0, 50));
children[1].add(new JButton("6"), new XYConstraints(0, 125, 0, 50));
children[1].add(new JButton("5"), new XYConstraints(0, 175, 0, 50));
children[1].add(new JButton("4"), new XYConstraints(0, 225, 0, 50));
children[1].add(new JButton("3"), new XYConstraints(0, 275, 0, 50));
children[1].add(new JButton("2"), new XYConstraints(0, 325, 0, 50));
children[1].add(new JButton("1"), new XYConstraints(0, 375, 0, 50));
children[2].add(new JButton("7"), new XYConstraints(240, 25, 0, 100));
children[2].add(new JButton("6"), new XYConstraints(200, 75, 0, 100));
children[2].add(new JButton("5"), new XYConstraints(160, 125, 0, 100));
children[2].add(new JButton("4"), new XYConstraints(120, 175, 0, 100));
children[2].add(new JButton("3"), new XYConstraints(80, 225, 0, 100));
children[2].add(new JButton("2"), new XYConstraints(40, 275, 0, 100));
children[2].add(new JButton("1"), new XYConstraints(0, 325, 0, 100));
children[3].add(new JButton("6"), new XYConstraints(200, 25, 0, 150));
children[3].add(new JButton("5"), new XYConstraints(160, 75, 0, 150));
children[3].add(new JButton("4"), new XYConstraints(120, 125, 0, 150));
children[3].add(new JButton("3"), new XYConstraints(80, 175, 0, 150));
children[3].add(new JButton("2"), new XYConstraints(40, 225, 0, 150));
children[3].add(new JButton("1"), new XYConstraints(0, 275, 0, 150));
//children[4],//children[5]...
f.setSize(800, 600);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
The custom layout in one file : XYLayout
public class XYLayout implements LayoutManager2, Serializable {
private int width;
private int height;
Hashtable<Component, Object> info;
static final XYConstraints defaultConstraints = new XYConstraints();
public XYLayout() {
info = new Hashtable<Component, Object>();
}
public XYLayout(int width, int height) {
info = new Hashtable<Component, Object>();
this.width = width;
this.height = height;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
/*
* (non-Javadoc)
*
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("XYLayout [width=").append(width).append(", height=").append(height).append("]");
return builder.toString();
}
public void addLayoutComponent(String s, Component component1) {
}
public void removeLayoutComponent(Component component) {
info.remove(component);
}
public Dimension preferredLayoutSize(Container target) {
return getLayoutSize(target, true);
}
public Dimension minimumLayoutSize(Container target) {
return getLayoutSize(target, false);
}
public void layoutContainer(Container target) {
Insets insets = target.getInsets();
int count = target.getComponentCount();
for (int i = 0; i < count; i++) {
Component component = target.getComponent(i);
if (component.isVisible()) {
Rectangle r = getComponentBounds(component, true);
component.setBounds(insets.left + r.x, insets.top + r.y, r.width, r.height);
}
}
}
public void addLayoutComponent(Component component, Object constraints) {
if (constraints instanceof XYConstraints)
info.put(component, constraints);
}
public Dimension maximumLayoutSize(Container target) {
return new Dimension(0x7fffffff, 0x7fffffff);
}
public float getLayoutAlignmentX(Container target) {
return 0.5F;
}
public float getLayoutAlignmentY(Container target) {
return 0.5F;
}
public void invalidateLayout(Container container) {
}
public Rectangle getComponentBounds(Component component, boolean doPreferred) {
XYConstraints constraints = (XYConstraints) info.get(component);
if (constraints == null)
constraints = defaultConstraints;
Rectangle r = new Rectangle(constraints.getX(), constraints.getY(), constraints.getW(), constraints.getH());
if (r.width <= 0 || r.height <= 0) {
Dimension d = doPreferred ? component.getPreferredSize() : component.getMinimumSize();
if (r.width <= 0)
r.width = d.width;
if (r.height <= 0)
r.height = d.height;
}
return r;
}
public Dimension getLayoutSize(Container target, boolean doPreferred) {
Dimension dim = new Dimension(0, 0);
if (width <= 0 || height <= 0) {
int count = target.getComponentCount();
for (int i = 0; i < count; i++) {
Component component = target.getComponent(i);
if (component.isVisible()) {
Rectangle r = getComponentBounds(component, doPreferred);
dim.width = Math.max(dim.width, r.x + r.width);
dim.height = Math.max(dim.height, r.y + r.height);
}
}
}
if (width > 0)
dim.width = width;
if (height > 0)
dim.height = height;
Insets insets = target.getInsets();
dim.width += insets.left + insets.right;
dim.height += insets.top + insets.bottom;
return dim;
}
}
class XYConstraints implements Cloneable, Serializable {
private int x;
private int y;
private int w;
private int h;
public XYConstraints() {
this(0, 0, 0, 0);
}
public XYConstraints(int x, int y, int w, int h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getW() {
return w;
}
public void setW(int w) {
this.w = w;
}
public int getH() {
return h;
}
public void setH(int h) {
this.h = h;
}
/*
* (non-Javadoc)
*
* #see java.lang.Object#hashCode()
*/
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + h;
result = prime * result + w;
result = prime * result + x;
result = prime * result + y;
return result;
// return x ^ y * 37 ^ w * 43 ^ h * 47;
}
public boolean equals(Object that) {
if (that instanceof XYConstraints) {
XYConstraints other = (XYConstraints) that;
return other.x == x && other.y == y && other.w == w && other.h == h;
} else {
return false;
}
}
public Object clone() {
return new XYConstraints(x, y, w, h);
}
/*
* (non-Javadoc)
*
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("XYConstraints [x=").append(x).append(", y=").append(y).append(", w=").append(w).append(", h=").append(h).append("]");
return builder.toString();
}
My first attempt was:
for (y = 375; y > 0; y = y - 50)
children[1].add(new JButton("1"), new XYConstraints(x, y, w, h));
for (y = 325, x = 0; y > 0 && x < 280; y = y - 50, x = x + 40)
children[2].add(new JButton("2"), new XYConstraints(x, y, w, 2 * h));
for (y = 275, x = 0; y > 0 && x < 240; y = y - 50, x = x + 40)
children[3].add(new JButton("3"), new XYConstraints(x, y, w, 3 * h));
but something's missing like a loop for "children[i]".I'm sure there is a better solution to improve the loop Any idea of improvement or suggestion ? Thanks
I write my own layout because existing layout manager don't meet my requirements
Right idea, but your implementation is incorrect. The fact that you need to provide the x/y values means you are not using a layout manager but just hardcoding some values.
Instead you need to provide information to the layout manager to define the parameters of the layout, maybe something like:
MyLayout layout = new MyLayout(xSize, ySize, xOffset, yOffset);
So for the first panel you would use:
MyLayout layout = new MyLayout(50, 50, 0, 50);
This code would say that each component is (50, 50). As you add components to the panel you change the x offset by 0 and the y offset = -50.
You know you have 8 buttons so you can use math to figure out the width/height of the panel. You can then use a loop inside the layout manager to position each component.
So now you add components to the panel like:
panel.add( new JButton("1") );
panel.add( new JButton("2") );
panel.add( new JButton("3") );
For the second panel you might use:
MyLayout layout = new MyLayout(50, 100, 50, 50);
So this time it means each button know has a size of (50, 100) and each button is placed (50, -50) to the previous button.
This is how layout managers should be created. You should not need complex loops to build the constraints of each component that you add to the panel. That is the job of the layout manager.
You could try:
for( int i=1; i<=3; i++ ) {
x = 0;
for( y=375-((i-1)*50; y>0; y-=50, x+=40 ) {
children[i].add(new JButton((String)i), new XYConstraints(x, y, w, i*h));
}
}

Change Hue of Picture in Graphics

Ok so i need help changing the hue of this slider. I cant seem to figure it out. Please no #override. I need something that will run on Ready to Program. The hue will change back to normal when the slider is back at 0. I dont need to get too complex. Just a simple Hue slider will be great. Thanks!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.Applet;
import javax.swing.event.*;
import java.applet.*;
public class test extends Applet implements ActionListener, ChangeListener
{
//Widgets, Panels
JSlider slider;
Panel flow;
int colorr;
int colorg;
int colorb;
int stars;
//House Coordinates, initialized to 1. (Top Right and No Scaling)
public void init ()
{ //Set Up Input Fields for House Coordinates
resize (380, 240);
setBackground (new Color (102, 179, 255));
slider = new JSlider ();
slider.setValue (0);
slider.setBackground (new Color (102, 179, 255));
slider.setForeground (Color.white);
slider.setMajorTickSpacing (20);
slider.setMinorTickSpacing (5);
slider.setPaintTicks (true);
slider.addChangeListener (this);
//Set up layout, add widgets
setLayout (new BorderLayout ());
flow = new Panel (new FlowLayout ());
flow.add (slider);
add (flow, "South");
}
public void paint (Graphics g)
{
Graphics2D g2d = (Graphics2D) g;
Color color1 = getBackground ();
Color color2 = color1.darker ();
int x = getWidth ();
int y = getHeight () - 30;
GradientPaint gp = new GradientPaint (
0, 0, color1,
0, y, color2);
g2d.setPaint (gp);
g2d.fillRect (0, 0, x, y);
stars (10, 10);
}
public void stars (int x, int y)
{
Graphics g = getGraphics ();
//sun
g.setColor (new Color (139, 166, 211));
g.fillOval (-200, 170, 1000, 400);
g.setColor (new Color (206, 75, 239));
g.fillOval (x, y, 10, 10); //First medium star
g.drawLine (x + 5, y, x + 5, 0);
g.drawLine (x, y + 5, 0, y + 5);
g.drawLine (x + 5, y + 10, x + 5, y + 20);
g.drawLine (x + 10, y + 5, x + 20, y + 5);
g.fillOval (x + 80, y + 30, 12, 12); //Middle medium star
g.drawLine (x + 86, y + 30, x + 86, y + 18);
g.drawLine (x + 80, y + 36, x + 68, y + 36);
g.drawLine (x + 92, y + 36, x + 104, y + 36);
g.drawLine (x + 86, y + 42, x + 86, y + 52);
colorr = (int) (Math.random () * 255) + 1;
colorg = (int) (Math.random () * 255) + 1;
colorb = (int) (Math.random () * 255) + 1;
int randomx = (int) (Math.random () * 300) + 10;
int randomy = (int) (Math.random () * 150) + 10;
stars = 50; //Change for more stars
int ax[] = new int [stars];
int ay[] = new int [stars];
for (int i = 0 ; i < stars ; i++)
{
g.setColor (new Color (colorr, colorg, colorb));
colorr = (int) (Math.random () * 255) + 1;
colorg = (int) (Math.random () * 255) + 1;
colorb = (int) (Math.random () * 255) + 1;
while ((randomx > 88 && randomx < 116) && (randomy < 65 && randomy > 15))
{
randomx = (int) (Math.random () * 300) + 10;
randomy = (int) (Math.random () * 150) + 10;
}
while ((randomx > 0 && randomx < 25) && (randomy > 5 && randomy < 35))
{
randomx = (int) (Math.random () * 300) + 10;
randomy = (int) (Math.random () * 150) + 10;
}
g.drawOval (randomx, randomy, 5, 5);
randomx = (int) (Math.random () * 300) + 10;
randomy = (int) (Math.random () * 150) + 10;
}
g.setColor (Color.white);
g.drawLine (320, 0, 315, 40);
g.drawLine (320, 0, 325, 40);
g.drawLine (320, 120, 315, 80);
g.drawLine (320, 120, 325, 80);
g.drawLine (260, 60, 300, 55);
g.drawLine (260, 60, 300, 65);
g.drawLine (380, 60, 340, 55);
g.drawLine (380, 60, 340, 65);
fillGradOval (280, 20, 80, 80, new Color (254, 238, 44), new Color (255, 251, 191), g);
g.setColor (new Color (255, 251, 191));
fillGradOval (300, 40, 40, 40, new Color (255, 251, 191), new Color (254, 238, 44), g);
}
public void fillGradOval (int X, int Y, int H2, int W2, Color c1, Color c2, Graphics g)
{
g.setColor (c1);
g.fillOval (X, Y, W2, H2);
Color Gradient = c1;
float red = (c2.getRed () - c1.getRed ()) / (W2 / 2);
float blue = (c2.getBlue () - c1.getBlue ()) / (W2 / 2);
float green = (c2.getGreen () - c1.getGreen ()) / (W2 / 2);
int scale = 1;
int r = c1.getRed ();
int gr = c1.getGreen ();
int b = c1.getBlue ();
while (W2 > 10)
{
r = (int) (r + red);
gr = (int) (gr + green);
b = (int) (b + blue);
Gradient = new Color (r, gr, b);
g.setColor (Gradient);
W2 = W2 - 2 * scale;
H2 = H2 - 2 * scale;
X = X + scale;
Y = Y + scale;
g.fillOval (X, Y, W2, H2);
}
}
public void actionPerformed (ActionEvent e)
{
}
public void stateChanged (ChangeEvent e)
{
JSlider source = (JSlider) e.getSource ();
if (!source.getValueIsAdjusting ())
{
}
}
}
I wasn't sure what 'color' you were referring to, so I made some guesses. Here is an hybrid application/applet (much easier for development and testing) that links the color of the bottom panel, as well as the bottom color of the gradient paint, to a hue as defined using the slider.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
/* <applet code=HueSlider width=380 height=240></applet> */
public class HueSlider extends JApplet
{
public void init() {
add(new HueSliderGui());
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
HueSliderGui hsg = new HueSliderGui();
JOptionPane.showMessageDialog(null, hsg);
}
};
SwingUtilities.invokeLater(r);
}
}
class HueSliderGui extends JPanel implements ChangeListener {
//Widgets, Panels
JSlider slider;
JPanel flow;
int colorr;
int colorg;
int colorb;
Color bg = new Color (102, 179, 255);
int stars;
//House Coordinates, initialized to 1. (Top Right and No Scaling)
Dimension prefSize = new Dimension(380, 240);
HueSliderGui() {
initGui();
}
public void initGui()
{
//Set Up Input Fields for House Coordinates
// an applet size is set in HTML
//resize (380, 240);
setBackground (bg);
slider = new JSlider ();
slider.setValue (0);
slider.setBackground (new Color (102, 179, 255));
slider.setForeground (Color.white);
slider.setMajorTickSpacing (20);
slider.setMinorTickSpacing (5);
slider.setPaintTicks (true);
slider.addChangeListener (this);
//Set up layout, add widgets
setLayout (new BorderLayout ());
flow = new JPanel (new FlowLayout ());
flow.add (slider);
add (flow, "South");
validate();
}
#Override
public Dimension getPreferredSize() {
return prefSize;
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
Color color1 = getBackground ();
Color color2 = color1.darker ();
int x = getWidth ();
int y = getHeight () - 30;
GradientPaint gp = new GradientPaint (
0, 0, color1,
0, y, flow.getBackground());
g2d.setPaint (gp);
g2d.fillRect (0, 0, x, y);
stars (10, 10, g2d);
}
public void stars (int x, int y, Graphics g)
{
// Graphics g = getGraphics (); we should never call getGraphics
//sun
g.setColor (new Color (139, 166, 211));
g.fillOval (-200, 170, 1000, 400);
g.setColor (new Color (206, 75, 239));
g.fillOval (x, y, 10, 10); //First medium star
g.drawLine (x + 5, y, x + 5, 0);
g.drawLine (x, y + 5, 0, y + 5);
g.drawLine (x + 5, y + 10, x + 5, y + 20);
g.drawLine (x + 10, y + 5, x + 20, y + 5);
g.fillOval (x + 80, y + 30, 12, 12); //Middle medium star
g.drawLine (x + 86, y + 30, x + 86, y + 18);
g.drawLine (x + 80, y + 36, x + 68, y + 36);
g.drawLine (x + 92, y + 36, x + 104, y + 36);
g.drawLine (x + 86, y + 42, x + 86, y + 52);
colorr = (int) (Math.random () * 255) + 1;
colorg = (int) (Math.random () * 255) + 1;
colorb = (int) (Math.random () * 255) + 1;
int randomx = (int) (Math.random () * 300) + 10;
int randomy = (int) (Math.random () * 150) + 10;
stars = 50; //Change for more stars
int ax[] = new int [stars];
int ay[] = new int [stars];
for (int i = 0 ; i < stars ; i++)
{
g.setColor (new Color (colorr, colorg, colorb));
colorr = (int) (Math.random () * 255) + 1;
colorg = (int) (Math.random () * 255) + 1;
colorb = (int) (Math.random () * 255) + 1;
while ((randomx > 88 && randomx < 116) && (randomy < 65 && randomy > 15))
{
randomx = (int) (Math.random () * 300) + 10;
randomy = (int) (Math.random () * 150) + 10;
}
while ((randomx > 0 && randomx < 25) && (randomy > 5 && randomy < 35))
{
randomx = (int) (Math.random () * 300) + 10;
randomy = (int) (Math.random () * 150) + 10;
}
g.drawOval (randomx, randomy, 5, 5);
randomx = (int) (Math.random () * 300) + 10;
randomy = (int) (Math.random () * 150) + 10;
}
g.setColor (Color.white);
g.drawLine (320, 0, 315, 40);
g.drawLine (320, 0, 325, 40);
g.drawLine (320, 120, 315, 80);
g.drawLine (320, 120, 325, 80);
g.drawLine (260, 60, 300, 55);
g.drawLine (260, 60, 300, 65);
g.drawLine (380, 60, 340, 55);
g.drawLine (380, 60, 340, 65);
fillGradOval (280, 20, 80, 80, new Color (254, 238, 44), new Color (255, 251, 191), g);
g.setColor (new Color (255, 251, 191));
fillGradOval (300, 40, 40, 40, new Color (255, 251, 191), new Color (254, 238, 44), g);
}
public void fillGradOval (int X, int Y, int H2, int W2, Color c1, Color c2, Graphics g)
{
g.setColor (c1);
g.fillOval (X, Y, W2, H2);
Color Gradient = c1;
float red = (c2.getRed () - c1.getRed ()) / (W2 / 2);
float blue = (c2.getBlue () - c1.getBlue ()) / (W2 / 2);
float green = (c2.getGreen () - c1.getGreen ()) / (W2 / 2);
int scale = 1;
int r = c1.getRed ();
int gr = c1.getGreen ();
int b = c1.getBlue ();
while (W2 > 10)
{
r = (int) (r + red);
gr = (int) (gr + green);
b = (int) (b + blue);
Gradient = new Color (r, gr, b);
g.setColor (Gradient);
W2 = W2 - 2 * scale;
H2 = H2 - 2 * scale;
X = X + scale;
Y = Y + scale;
g.fillOval (X, Y, W2, H2);
}
}
public void stateChanged (ChangeEvent e)
{
JSlider source = (JSlider) e.getSource ();
if (!source.getValueIsAdjusting ())
{
int i = source.getValue();
System.out.println(i);
float[] hsb = Color.RGBtoHSB(bg.getRed(),bg.getGreen(),bg.getBlue(),null);
int colorHue = Color.HSBtoRGB((float)i/100f, hsb[1], hsb[2]);
Color c = new Color(colorHue);
flow.setBackground(c);
this.repaint();
}
}
}

How can I change the shape of a JTabbedPane tab?

I am trying to change the shape of the tabs in a JTabbedPane. Using setTabComponentAt(0, someComponent); doesn't change the exterior of the tab, which is a rectangle with a diagonal top-left corner. What may be done to change the shape?
correct way is only to change Look and Feel, nice example from Old.Java.Forums.Sun
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
public class TabbedPane extends JPanel {
private static final long serialVersionUID = 1L;
public TabbedPane() {
setLayout(new BorderLayout());
JPanel jp = new JPanel();
jp.setLayout(new BorderLayout());
JTabbedPane tb = new JTabbedPane();
tb.setUI(new CustomTabbedPaneUI());
tb.add("Tab1", new JTextArea(""));
tb.add("Tab2", new JTextArea(""));
tb.add("Tab3", new JTextArea(""));
tb.add("Tab4", new JTextArea(""));
tb.add("Tab5", new JTextArea(""));
jp.add(tb, BorderLayout.CENTER);
add(jp, BorderLayout.CENTER);
tb.setEnabledAt(1, false);
tb.setEnabledAt(3, false);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new TabbedPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 200);
frame.setVisible(true);
}
}
and
import java.util.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.*;
import javax.swing.plaf.basic.*;
import javax.swing.text.View;
public class CustomTabbedPaneUI extends BasicTabbedPaneUI {
private Color selectColor;
private Color deSelectColor;
private int inclTab = 4;
private int anchoFocoV = inclTab;
private int anchoFocoH = 4;
private int anchoCarpetas = 18;
private Polygon shape;
public static ComponentUI createUI(JComponent c) {
return new CustomTabbedPaneUI();
}
#Override
protected void installDefaults() {
super.installDefaults();
selectColor = new Color(250, 192, 192);
deSelectColor = new Color(197, 193, 168);
tabAreaInsets.right = anchoCarpetas;
}
#Override
protected void paintTabArea(Graphics g, int tabPlacement, int selectedIndex) {
if (runCount > 1) {
int lines[] = new int[runCount];
for (int i = 0; i < runCount; i++) {
lines[i] = rects[tabRuns[i]].y + (tabPlacement == TOP ? maxTabHeight : 0);
}
Arrays.sort(lines);
if (tabPlacement == TOP) {
int fila = runCount;
for (int i = 0; i < lines.length - 1; i++, fila--) {
Polygon carp = new Polygon();
carp.addPoint(0, lines[i]);
carp.addPoint(tabPane.getWidth() - 2 * fila - 2, lines[i]);
carp.addPoint(tabPane.getWidth() - 2 * fila, lines[i] + 3);
if (i < lines.length - 2) {
carp.addPoint(tabPane.getWidth() - 2 * fila, lines[i + 1]);
carp.addPoint(0, lines[i + 1]);
} else {
carp.addPoint(tabPane.getWidth() - 2 * fila, lines[i] + rects[selectedIndex].height);
carp.addPoint(0, lines[i] + rects[selectedIndex].height);
}
carp.addPoint(0, lines[i]);
g.setColor(hazAlfa(fila));
g.fillPolygon(carp);
g.setColor(darkShadow.darker());
g.drawPolygon(carp);
}
} else {
int fila = 0;
for (int i = 0; i < lines.length - 1; i++, fila++) {
Polygon carp = new Polygon();
carp.addPoint(0, lines[i]);
carp.addPoint(tabPane.getWidth() - 2 * fila - 1, lines[i]);
carp.addPoint(tabPane.getWidth() - 2 * fila - 1, lines[i + 1] - 3);
carp.addPoint(tabPane.getWidth() - 2 * fila - 3, lines[i + 1]);
carp.addPoint(0, lines[i + 1]);
carp.addPoint(0, lines[i]);
g.setColor(hazAlfa(fila + 2));
g.fillPolygon(carp);
g.setColor(darkShadow.darker());
g.drawPolygon(carp);
}
}
}
super.paintTabArea(g, tabPlacement, selectedIndex);
}
#Override
protected void paintTabBackground(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) {
Graphics2D g2D = (Graphics2D) g;
GradientPaint gradientShadow;
int xp[] = null; // Para la forma
int yp[] = null;
switch (tabPlacement) {
case LEFT:
xp = new int[]{x, x, x + w, x + w, x};
yp = new int[]{y, y + h - 3, y + h - 3, y, y};
gradientShadow = new GradientPaint(x, y, new Color(100, 100, 255), x, y + h, Color.ORANGE);
break;
case RIGHT:
xp = new int[]{x, x, x + w - 2, x + w - 2, x};
yp = new int[]{y, y + h - 3, y + h - 3, y, y};
gradientShadow = new GradientPaint(x, y, new Color(100, 100, 255), x, y + h, new Color(153, 186, 243));
break;
case BOTTOM:
xp = new int[]{x, x, x + 3, x + w - inclTab - 6, x + w - inclTab - 2, x + w - inclTab, x + w - 3, x};
yp = new int[]{y, y + h - 3, y + h, y + h, y + h - 1, y + h - 3, y, y};
gradientShadow = new GradientPaint(x, y, new Color(100, 100, 255), x, y + h, Color.BLUE);
break;
case TOP:
default:
xp = new int[]{x, x, x + 3, x + w - inclTab - 6, x + w - inclTab - 2, x + w - inclTab, x + w - inclTab, x};
yp = new int[]{y + h, y + 3, y, y, y + 1, y + 3, y + h, y + h};
gradientShadow = new GradientPaint(0, 0, Color.ORANGE, 0, y + h / 2, new Color(240, 255, 210));
break;
}
// ;
shape = new Polygon(xp, yp, xp.length);
if (isSelected) {
g2D.setColor(selectColor);
g2D.setPaint(gradientShadow);
} else {
if (tabPane.isEnabled() && tabPane.isEnabledAt(tabIndex)) {
g2D.setColor(deSelectColor);
GradientPaint gradientShadowTmp = new GradientPaint(0, 0, new Color(255, 255, 200), 0, y + h / 2, new Color(240, 255, 210));
g2D.setPaint(gradientShadowTmp);
} else {
GradientPaint gradientShadowTmp = new GradientPaint(0, 0, new Color(240, 255, 210), 0, y + 15 + h / 2, new Color(204, 204, 204));
g2D.setPaint(gradientShadowTmp);
}
}
//selectColor = new Color(255, 255, 200);
//deSelectColor = new Color(240, 255, 210);
g2D.fill(shape);
if (runCount > 1) {
g2D.setColor(hazAlfa(getRunForTab(tabPane.getTabCount(), tabIndex) - 1));
g2D.fill(shape);
}
g2D.fill(shape);
}
#Override
protected void paintText(Graphics g, int tabPlacement, Font font, FontMetrics metrics, int tabIndex, String title, Rectangle textRect, boolean isSelected) {
super.paintText(g, tabPlacement, font, metrics, tabIndex, title, textRect, isSelected);
g.setFont(font);
View v = getTextViewForTab(tabIndex);
if (v != null) {
// html
v.paint(g, textRect);
} else {
// plain text
int mnemIndex = tabPane.getDisplayedMnemonicIndexAt(tabIndex);
if (tabPane.isEnabled() && tabPane.isEnabledAt(tabIndex)) {
g.setColor(tabPane.getForegroundAt(tabIndex));
BasicGraphicsUtils.drawStringUnderlineCharAt(g, title, mnemIndex, textRect.x, textRect.y + metrics.getAscent());
} else { // tab disabled
g.setColor(Color.BLACK);
BasicGraphicsUtils.drawStringUnderlineCharAt(g, title, mnemIndex, textRect.x, textRect.y + metrics.getAscent());
g.setColor(tabPane.getBackgroundAt(tabIndex).darker());
BasicGraphicsUtils.drawStringUnderlineCharAt(g, title, mnemIndex, textRect.x - 1, textRect.y + metrics.getAscent() - 1);
}
}
}
/*protected void paintText(Graphics g, int tabPlacement, Font font, FontMetrics metrics, int tabIndex, String title, Rectangle textRect, boolean isSelected) {
g.setFont(font);
View v = getTextViewForTab(tabIndex);
if (v != null) {
// html
v.paint(g, textRect);
} else {
// plain text
int mnemIndex = tabPane.getDisplayedMnemonicIndexAt(tabIndex);
if (tabPane.isEnabled() && tabPane.isEnabledAt(tabIndex)) {
Color fg = tabPane.getForegroundAt(tabIndex);
if (isSelected && (fg instanceof UIResource)) {
Color selectedFG = UIManager.getColor("TabbedPane.selectedForeground");
if (selectedFG != null) {
fg = selectedFG;
}
}
g.setColor(fg);
SwingUtilities2.drawStringUnderlineCharAt(tabPane, g, title, mnemIndex, textRect.x, textRect.y + metrics.getAscent());
} else { // tab disabled
//PAY ATTENTION TO HERE
g.setColor(tabPane.getBackgroundAt(tabIndex).brighter());
SwingUtilities2.drawStringUnderlineCharAt(tabPane, g, title, mnemIndex, textRect.x, textRect.y + metrics.getAscent());
g.setColor(tabPane.getBackgroundAt(tabIndex).darker());
SwingUtilities2.drawStringUnderlineCharAt(tabPane, g, title, mnemIndex,
textRect.x - 1, textRect.y + metrics.getAscent() - 1);
}
}
}*/
#Override
protected int calculateTabWidth(int tabPlacement, int tabIndex, FontMetrics metrics) {
return 20 + inclTab + super.calculateTabWidth(tabPlacement, tabIndex, metrics);
}
#Override
protected int calculateTabHeight(int tabPlacement, int tabIndex, int fontHeight) {
if (tabPlacement == LEFT || tabPlacement == RIGHT) {
return super.calculateTabHeight(tabPlacement, tabIndex, fontHeight);
} else {
return anchoFocoH + super.calculateTabHeight(tabPlacement, tabIndex, fontHeight);
}
}
#Override
protected void paintTabBorder(Graphics g, int tabPlacement, int tabIndex, int x, int y, int w, int h, boolean isSelected) {
}
#Override
protected void paintFocusIndicator(Graphics g, int tabPlacement, Rectangle[] rects, int tabIndex, Rectangle iconRect, Rectangle textRect, boolean isSelected) {
if (tabPane.hasFocus() && isSelected) {
g.setColor(UIManager.getColor("ScrollBar.thumbShadow"));
g.drawPolygon(shape);
}
}
protected Color hazAlfa(int fila) {
int alfa = 0;
if (fila >= 0) {
alfa = 50 + (fila > 7 ? 70 : 10 * fila);
}
return new Color(0, 0, 0, alfa);
}
}
The shape is under the aegis of the tabbed pane's UI delegate, which descends from TabbedPaneUI. The MetalTabbedPaneUI subclass is an example that may help you decide how badly you want to replace the delegate.
You can put html tags into the first parameter of addTab method as following :
MyJTabbedPane.addTab("<html><h1 style='padding:20px;'>TEST</h1></html>", new JPanel());

Categories

Resources